From 5a884ad93ded2bf01cbaa79acfe4738050b5fa4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Mar 2020 08:00:45 +0100 Subject: [PATCH 01/44] Common ValueObservation code for all read-only database accessors --- GRDB/Core/DatabaseReader.swift | 62 ++++++++++++++++++++++++++++++++ GRDB/Core/DatabaseSnapshot.swift | 51 +------------------------- GRDB/Core/DatabaseWriter.swift | 4 +++ GRDB/Utils/Utils.swift | 11 ++++++ 4 files changed, 78 insertions(+), 50 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e58ddb315..c005c9511 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -294,6 +294,68 @@ extension DatabaseReader { } } +extension DatabaseReader { + // MARK: - Value Observation Support + + func addReadOnly( + observation: ValueObservation, + onError: @escaping (Error) -> Void, + onChange: @escaping (Reducer.Value) -> Void) + -> TransactionObserver + { + switch observation.scheduling { + case .mainQueue: + if DispatchQueue.isMain { + do { + try onChange(unsafeReentrantRead(observation.fetchValue)) + } catch { + onError(error) + } + } else { + asyncRead { dbResult in + let result = dbResult.tryMap(observation.fetchValue) + DispatchQueue.main.async { + do { + try onChange(result.get()) + } catch { + onError(error) + } + } + } + } + case let .async(onQueue: queue): + asyncRead { dbResult in + let result = dbResult.tryMap(observation.fetchValue) + queue.async { + do { + try onChange(result.get()) + } catch { + onError(error) + } + } + } + case .unsafe: + do { + try onChange(unsafeReentrantRead(observation.fetchValue)) + } catch { + onError(error) + } + } + + // Return a dummy observer, because read-only ValueObservation + // never changes. + return DummyObserver() + } +} + +/// Support for DatabaseReader.addReadonly(observation:onError:onChange:) +private class DummyObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } + func databaseDidChange(with event: DatabaseEvent) { } + func databaseDidCommit(_ db: Database) { } + func databaseDidRollback(_ db: Database) { } +} + /// A type-erased DatabaseReader /// /// Instances of AnyDatabaseReader forward their methods to an arbitrary diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 5e066713f..e449e21ae 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -122,59 +122,10 @@ extension DatabaseSnapshot { onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - switch observation.scheduling { - case .mainQueue: - if DispatchQueue.isMain { - do { - try onChange(serializedDatabase.reentrantSync(observation.fetchValue)) - } catch { - onError(error) - } - } else { - serializedDatabase.async { db in - let result = Result { try observation.fetchValue(db) } - DispatchQueue.main.async { - do { - try onChange(result.get()) - } catch { - onError(error) - } - } - } - } - case let .async(onQueue: queue): - serializedDatabase.async { db in - let result = Result { try observation.fetchValue(db) } - queue.async { - do { - try onChange(result.get()) - } catch { - onError(error) - } - } - } - case .unsafe: - do { - try onChange(serializedDatabase.reentrantSync(observation.fetchValue)) - } catch { - onError(error) - } - } - - // Return a dummy observer, because snapshots never change - return SnapshotValueObserver() + return addReadOnly(observation: observation, onError: onError, onChange: onChange) } public func remove(transactionObserver: TransactionObserver) { // Can't remove an observer which could not be added :-) } } - -/// An observer that does nothing, support for -/// `DatabaseSnapshot.add(observation:onError:onChange:)`. -private class SnapshotValueObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } - func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidCommit(_ db: Database) { } - func databaseDidRollback(_ db: Database) { } -} diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 70d20d0eb..c1c15de8c 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -310,6 +310,10 @@ extension DatabaseWriter { onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { + if configuration.readonly { + return addReadOnly(observation: observation, onError: onError, onChange: onChange) + } + // True if initial value must be sent to the onChange callback // before this method returns. let initialSync: Bool diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 869fc7099..7811ee18d 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -97,6 +97,17 @@ extension DispatchQueue { } } +extension Result { + func tryMap(_ transform: (Success) throws -> T) -> Result { + switch self { + case let .success(value): + return Result { try transform(value) } + case let .failure(error): + return .failure(error) + } + } +} + extension Sequence { @inlinable func count(where predicate: (Element) throws -> Bool) rethrows -> Int { From 2824636650a4c9d474acab2d4a180099051f18aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Mar 2020 08:19:01 +0100 Subject: [PATCH 02/44] Prepare for initiial concurrent fetch of ValueObservation in a DatabasePool --- GRDB/Core/DatabasePool.swift | 16 ++++++++++++++++ GRDB/Core/DatabaseQueue.swift | 16 ++++++++++++++++ GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 15 ++++++++++++++- 4 files changed, 47 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8f086efcf..8ca873f22 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -771,6 +771,22 @@ extension DatabasePool: DatabaseReader { forEachConnection { $0.remove(collation: collation) } } + // MARK: - Database Observation + + public func add( + observation: ValueObservation, + onError: @escaping (Error) -> Void, + onChange: @escaping (Reducer.Value) -> Void) + -> TransactionObserver + { + add( + observation: observation, + // DatabasePool supports concurrent reads + prependingConcurrentFetch: true, + onError: onError, + onChange: onChange) + } + // MARK: - Custom FTS5 Tokenizers #if SQLITE_ENABLE_FTS5 diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 86553a34e..e660260f8 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -446,4 +446,20 @@ extension DatabaseQueue { public func remove(collation: DatabaseCollation) { writer.sync { $0.remove(collation: collation) } } + + // MARK: - Database Observation + + public func add( + observation: ValueObservation, + onError: @escaping (Error) -> Void, + onChange: @escaping (Reducer.Value) -> Void) + -> TransactionObserver + { + add( + observation: observation, + // DatabaseQueue does not support concurrent reads + prependingConcurrentFetch: false, + onError: onError, + onChange: onChange) + } } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index e449e21ae..7122b458b 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -114,7 +114,7 @@ extension DatabaseSnapshot { serializedDatabase.sync { $0.remove(collation: collation) } } - // MARK: - Value Observation + // MARK: - Database Observation public func add( observation: ValueObservation, diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c1c15de8c..920e19f1c 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -304,8 +304,9 @@ extension DatabaseWriter { /// Default implementation for the DatabaseReader requirement. /// :nodoc: - public func add( + func add( observation: ValueObservation, + prependingConcurrentFetch: Bool, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver @@ -576,4 +577,16 @@ public final class AnyDatabaseWriter: DatabaseWriter { public func remove(collation: DatabaseCollation) { base.remove(collation: collation) } + + // MARK: - Database Observation + + /// :nodoc: + public func add( + observation: ValueObservation, + onError: @escaping (Error) -> Void, + onChange: @escaping (Reducer.Value) -> Void) + -> TransactionObserver + { + base.add(observation: observation, onError: onError, onChange: onChange) + } } From 1c592781158e22ffd1bce9ed3a6ec9b9816fbcf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Mar 2020 08:29:46 +0100 Subject: [PATCH 03/44] Prefer dbResult argument name for async read closures --- GRDB/Core/DatabasePool.swift | 12 ++++++------ GRDB/Core/DatabaseQueue.swift | 4 ++-- GRDB/Core/DatabaseReader.swift | 4 ++-- GRDB/Core/DatabaseSnapshot.swift | 4 ++-- GRDB/Core/DatabaseWriter.swift | 4 ++-- README.md | 10 +++++----- Tests/GRDBTests/DatabasePoolConcurrencyTests.swift | 14 +++++++------- Tests/GRDBTests/DatabaseReaderTests.swift | 8 ++++---- 8 files changed, 30 insertions(+), 30 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8ca873f22..af622d910 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -357,9 +357,9 @@ extension DatabasePool: DatabaseReader { /// Asynchronously executes a read-only block in a protected dispatch queue. /// - /// let players = try dbQueue.asyncRead { result in + /// let players = try dbQueue.asyncRead { dbResult in /// do { - /// let db = try result.get() + /// let db = try dbResult.get() /// let count = try Player.fetchCount(db) /// } catch { /// // Handle error @@ -486,9 +486,9 @@ extension DatabasePool: DatabaseReader { let futureSemaphore = DispatchSemaphore(value: 0) var futureResult: Result? = nil - asyncConcurrentRead { db in + asyncConcurrentRead { dbResult in // Fetch and release the future - futureResult = Result { try block(db.get()) } + futureResult = dbResult.tryMap(block) futureSemaphore.signal() } @@ -526,9 +526,9 @@ extension DatabasePool: DatabaseReader { /// try Player.deleteAll() /// /// // Count players concurrently - /// writer.asyncConcurrentRead { result in + /// writer.asyncConcurrentRead { dbResult in /// do { - /// let db = try result.get() + /// let db = try dbResult.get() /// // Guaranteed to be zero /// let count = try Player.fetchCount(db) /// } catch { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index e660260f8..f29007fec 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -202,9 +202,9 @@ extension DatabaseQueue { /// Asynchronously executes a read-only block in a protected dispatch queue. /// - /// let players = try dbQueue.asyncRead { result in + /// let players = try dbQueue.asyncRead { dbResult in /// do { - /// let db = try result.get() + /// let db = try dbResult.get() /// let count = try Player.fetchCount(db) /// } catch { /// // Handle error diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index c005c9511..683c78399 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -121,9 +121,9 @@ public protocol DatabaseReader: AnyObject { /// Guarantee 1: the block argument is isolated. Eventual concurrent /// database updates are not visible inside the block: /// - /// try reader.asyncRead { result in + /// try reader.asyncRead { dbResult in /// do ( - /// let db = try result.get() + /// let db = try dbResult.get() /// // Those two values are guaranteed to be equal, even if the /// // `player` table is modified between the two requests: /// let count1 = try Player.fetchCount(db) diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 7122b458b..8d7dbc14e 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -70,9 +70,9 @@ extension DatabaseSnapshot { /// Asynchronously executes a read-only block in a protected dispatch queue. /// - /// let players = try snapshot.asyncRead { result in + /// let players = try snapshot.asyncRead { dbResult in /// do { - /// let db = try result.get() + /// let db = try dbResult.get() /// let count = try Player.fetchCount(db) /// } catch { /// // Handle error diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 920e19f1c..cd2ccf3ed 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -166,9 +166,9 @@ public protocol DatabaseWriter: DatabaseReader { /// try Player.deleteAll() /// /// // Count players concurrently - /// writer.asyncConcurrentRead { result in + /// writer.asyncConcurrentRead { dbResult in /// do { - /// let db = try result.get() + /// let db = try dbResult.get() /// // Guaranteed to be zero /// let count = try Player.fetchCount(db) /// } catch { diff --git a/README.md b/README.md index d2560b8d2..5aac07a1b 100644 --- a/README.md +++ b/README.md @@ -7470,9 +7470,9 @@ let component = MyReadOnlyComponent(reader: dbQueue) The `asyncRead` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue: ```swift -reader.asyncRead { (result: Result) in +reader.asyncRead { (dbResult: Result) in try { - let db = try result.get() + let db = try dbResult.get() let players = try Player.fetchAll(db) } catch { // handle error @@ -7568,11 +7568,11 @@ try writer.asyncWriteWithoutTransaction { db in // <- not in a transaction here // Count players concurrently - writer.asyncConcurrentRead { (result: Result) in + writer.asyncConcurrentRead { (dbResult: Result) in try { - let db = try result.get() + let db = try dbResult.get() // Guaranteed to be zero - let count = try Player.fetchCount() + let count = try Player.fetchCount(db) } catch { // handle error } diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 5611042e2..5cb9426b0 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1100,9 +1100,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { var isInsideTransaction: Bool? = nil let expectation = self.expectation(description: "read") dbPool.writeWithoutTransaction { db in - dbPool.asyncConcurrentRead { result in + dbPool.asyncConcurrentRead { dbResult in do { - let db = try result.get() + let db = try dbResult.get() isInsideTransaction = db.isInsideTransaction do { try db.execute(sql: "BEGIN DEFERRED TRANSACTION") @@ -1142,10 +1142,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { var count: Int? = nil let expectation = self.expectation(description: "read") try dbPool.writeWithoutTransaction { db in - dbPool.asyncConcurrentRead { result in + dbPool.asyncConcurrentRead { dbResult in do { _ = s1.wait(timeout: .distantFuture) - let db = try result.get() + let db = try dbResult.get() count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! } catch { XCTFail("Unexpected error: \(error)") @@ -1166,11 +1166,11 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try dbPool.writeWithoutTransaction { db in try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE") try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - dbPool.asyncConcurrentRead { result in - guard case let .failure(error) = result, + dbPool.asyncConcurrentRead { dbResult in + guard case let .failure(error) = dbResult, let dbError = error as? DatabaseError else { - XCTFail("Unexpected result: \(result)") + XCTFail("Unexpected result: \(dbResult)") return } readError = dbError diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index b5221e0d8..c2d357c16 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -116,11 +116,11 @@ class DatabaseReaderTests : GRDBTestCase { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) var count: Int? - dbReader.asyncRead { db in + dbReader.asyncRead { dbResult in // Make sure this block executes asynchronously semaphore.wait() do { - count = try Int.fetchOne(db.get(), sql: "SELECT COUNT(*) FROM sqlite_master") + count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master") } catch { XCTFail("Unexpected error: \(error)") } @@ -141,11 +141,11 @@ class DatabaseReaderTests : GRDBTestCase { func test(_ dbReader: DatabaseReader) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) - dbReader.asyncRead { db in + dbReader.asyncRead { dbResult in // Make sure this block executes asynchronously semaphore.wait() do { - try db.get().execute(sql: "CREATE TABLE testAsyncReadPreventsDatabaseModification (a)") + try dbResult.get().execute(sql: "CREATE TABLE testAsyncReadPreventsDatabaseModification (a)") XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_READONLY) From 2b78a646ed0b4216213c626c58c76fdf962f003a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Mar 2020 20:59:54 +0100 Subject: [PATCH 04/44] Mor preparation for initiial concurrent fetch of ValueObservation in a DatabasePool --- GRDB/Core/DatabasePool.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 19 +- GRDB/ValueObservation/ValueObservation.swift | 3 +- GRDB/ValueObservation/ValueObserver.swift | 176 +++++++++--------- .../ValueReducer/ValueReducer.swift | 8 + 5 files changed, 109 insertions(+), 99 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index af622d910..8fc4c63e6 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -782,7 +782,7 @@ extension DatabasePool: DatabaseReader { add( observation: observation, // DatabasePool supports concurrent reads - prependingConcurrentFetch: true, + prependingConcurrentFetch: !observation.requiresWriteAccess, onError: onError, onChange: onChange) } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index cd2ccf3ed..bc1f6815a 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -300,10 +300,8 @@ extension DatabaseWriter { try writeWithoutTransaction { try $0.execute(sql: "VACUUM") } } - // MARK: - Value Observation - - /// Default implementation for the DatabaseReader requirement. - /// :nodoc: + // MARK: - Database Observation + func add( observation: ValueObservation, prependingConcurrentFetch: Bool, @@ -317,7 +315,8 @@ extension DatabaseWriter { // True if initial value must be sent to the onChange callback // before this method returns. - let initialSync: Bool + // This flag supersedes prependingConcurrentFetch. + let initialFetchSync: Bool // The queue for other values. Nil for any queue. let notificationQueue: DispatchQueue? @@ -328,20 +327,20 @@ extension DatabaseWriter { // Use case: observation starts on the main queue and wants // a synchronous initial fetch. This helps avoiding flashes of // missing content. - initialSync = true + initialFetchSync = true notificationQueue = DispatchQueue.main } else { // TODO: make this a fatal error when .mainQueue is no longer // the default scheduling. // Use case: observation does not start on the main queue, but // has the default scheduling .mainQueue - initialSync = false + initialFetchSync = false notificationQueue = DispatchQueue.main } case let .async(onQueue: queue): // Use case: observation must not block the target queue - initialSync = false + initialFetchSync = false notificationQueue = queue case .unsafe: @@ -356,7 +355,7 @@ extension DatabaseWriter { // // A failure to follow this rule may mess with the ordering of // initial values. - initialSync = true + initialFetchSync = true notificationQueue = nil } @@ -372,7 +371,7 @@ extension DatabaseWriter { onError: onError, onChange: onChange) - if initialSync { + if initialFetchSync { do { let initialValue: Reducer.Value = try unsafeReentrantWrite { db in observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 0adfb9bf1..0765928bc 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -126,8 +126,7 @@ extension ValueObservation { /// Returns the value. func fetchValue(_ db: Database) throws -> Reducer.Value { var reducer = makeReducer() - let fetchedValue = try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - guard let value = reducer.value(fetchedValue) else { + guard let value = try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) else { fatalError("Contract broken: reducer has no initial value") } return value diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index a1eb559e0..c8c0bf4ec 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -2,7 +2,7 @@ import Foundation /// Support for ValueObservation. /// See DatabaseWriter.add(observation:onError:onChange:) -class ValueObserver: TransactionObserver { +final class ValueObserver { var baseRegion = DatabaseRegion() { didSet { observedRegion = baseRegion.union(selectedRegion) } } @@ -42,30 +42,25 @@ class ValueObserver: TransactionObserver { } // Fetch initial value, with two side effects: - // - selectedRegion is set if observesSelectedRegion - // - reducer moves forward // // This method must be called at most once, before the observer is added // to the database writer. func fetchInitialValue(_ db: Database) throws -> Reducer.Value { - let fetchedValue: Reducer.Fetched - if observesSelectedRegion { - (fetchedValue, selectedRegion) = try db.recordingSelectedRegion { - try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } else { - fetchedValue = try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + let value = try recordingSelectedRegionIfNeeded(db) { + try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) } - guard let value = reducer.value(fetchedValue) else { - fatalError("Contract broken: reducer has no initial value") + if let value = value { + return value } - return value + fatalError("Contract broken: reducer has no initial value") } func cancel() { isCancelled = true } - +} + +extension ValueObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { if isCancelled { return false } return observedRegion.isModified(byEventsOfKind: eventKind) @@ -84,91 +79,45 @@ class ValueObserver: TransactionObserver { guard isChanged else { return } isChanged = false - // Grab future fetched value - let future: DatabaseFuture - if requiresWriteAccess { - // Synchronous read/write fetch - if observesSelectedRegion { - do { - var fetchedValue: Reducer.Fetched! - var selectedRegion: DatabaseRegion! - try db.inTransaction { - let (_fetchedValue, _selectedRegion) = try db.recordingSelectedRegion { - try reducer.fetch(db) - } - fetchedValue = _fetchedValue - selectedRegion = _selectedRegion - return .commit - } - self.selectedRegion = selectedRegion - future = DatabaseFuture(.success(fetchedValue)) - } catch { - future = DatabaseFuture(.failure(error)) + let reducer = self.reducer + let fetchedValue: DatabaseFuture + + if requiresWriteAccess || observesSelectedRegion { + // Synchronous fetch + fetchedValue = DatabaseFuture(Result { + try recordingSelectedRegionIfNeeded(db) { + try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) } - } else { - future = DatabaseFuture(Result { - var fetchedValue: Reducer.Fetched! - try db.inTransaction { - fetchedValue = try reducer.fetch(db) - return .commit - } - return fetchedValue - }) - } + }) } else { - if observesSelectedRegion { - // Synchronous read-only fetch - do { - let (fetchedValue, selectedRegion) = try db.readOnly { - try db.recordingSelectedRegion { - try reducer.fetch(db) - } - } - self.selectedRegion = selectedRegion - future = DatabaseFuture(.success(fetchedValue)) - } catch { - future = DatabaseFuture(.failure(error)) - } - } else { - // Concurrent fetch - future = writer.concurrentRead(reducer.fetch) - } + // Asynchronous fetch + fetchedValue = writer.concurrentRead(reducer.fetch) } // Wait for future fetched value in reduceQueue. This guarantees: // - that notifications have the same ordering as transactions. // - that expensive reduce operations are computed without blocking - // any database dispatch queue. + // any database dispatch queue. reduceQueue.async { [weak self] in guard let self = self else { return } if self.isCancelled { return } - self.reduce(future: future) - } - } - - private func reduce(future: DatabaseFuture) { - do { - if let value = try reducer.value(future.wait()) { + + Self.reduce(fetchedValue: fetchedValue, with: reducer) { [weak self] result in + guard let self = self else { return } if self.isCancelled { return } - if let queue = notificationQueue { - queue.async { [weak self] in - guard let self = self else { return } - if self.isCancelled { return } - self.onChange(value) - } - } else { - onChange(value) + + // Check that we're still on reduce queue. + if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { + dispatchPrecondition(condition: .onQueue(self.reduceQueue)) } - } - } catch { - if let queue = notificationQueue { - queue.async { [weak self] in - guard let self = self else { return } - if self.isCancelled { return } - self.onError(error) + + do { + let (reducer, value) = try result.get() + self.reducer = reducer + self.notify(value) + } catch { + self.notify(error) } - } else { - onError(error) } } } @@ -178,6 +127,61 @@ class ValueObserver: TransactionObserver { } } +extension ValueObserver { + private static func reduce( + fetchedValue: DatabaseFuture, + with reducer: Reducer, + completion: @escaping (Result<(Reducer, Reducer.Value), Error>) -> Void) + { + do { + var reducer = reducer + if let value = try reducer.value(fetchedValue.wait()) { + completion(.success((reducer, value))) + } + } catch { + completion(.failure(error)) + } + } + + private func recordingSelectedRegionIfNeeded(_ db: Database, _ block: () throws -> T) rethrows -> T { + if observesSelectedRegion { + let result: T + (result, selectedRegion) = try db.recordingSelectedRegion(block) + return result + } else { + return try block() + } + } + + private func notify(_ value: Reducer.Value) { + assert(!isCancelled) + if let queue = notificationQueue { + let onChange = self.onChange + queue.async { [weak self] in + guard let self = self else { return } + if self.isCancelled { return } + onChange(value) + } + } else { + onChange(value) + } + } + + private func notify(_ error: Error) { + assert(!isCancelled) + if let queue = notificationQueue { + let onError = self.onError + queue.async { [weak self] in + guard let self = self else { return } + if self.isCancelled { return } + onError(error) + } + } else { + onError(error) + } + } +} + class ValueObserverToken: TransactionObserver { // Useless junk func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index ef8c2609e..f0f8fe98a 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -9,6 +9,9 @@ public protocol _ValueReducer { associatedtype Value /// Feches database values upon changes in an observed database region. + /// + /// _ValueReducer semantics require that this method does not depend on + /// the state of the reducer: it must not use *self*. func fetch(_ db: Database) throws -> Fetched /// Transforms a fetched value into an eventual observed value. Returns nil @@ -41,6 +44,11 @@ extension _ValueReducer { } } } + + mutating func fetchAndReduce(_ db: Database, requiringWriteAccess: Bool) throws -> Value? { + let fetchedValue = try fetch(db, requiringWriteAccess: requiringWriteAccess) + return value(fetchedValue) + } } /// A namespace for types related to the _ValueReducer protocol. From 26d2245ae8d1bfc0e0f3c84b86a3c6faca2a8748 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Mar 2020 21:06:50 +0100 Subject: [PATCH 05/44] Asynchronouslu remove observer when it is cancelled --- GRDB/ValueObservation/ValueObserver.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index c8c0bf4ec..c56c8235a 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -197,10 +197,11 @@ class ValueObserverToken: TransactionObserver { self.observer = observer } - // The most ugly stuff ever deinit { + let observer = self.observer observer.cancel() - // TODO: have it not wait for the writer queue - writer?.remove(transactionObserver: observer) + writer?.asyncWriteWithoutTransaction { db in + db.remove(transactionObserver: observer) + } } } From 2bb894108cfdafe533701cb0f121b5d08759e5ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Mar 2020 21:43:36 +0100 Subject: [PATCH 06/44] Use the prependingConcurrentFetch flag --- GRDB/Core/DatabaseWriter.swift | 32 ++++++--- GRDB/ValueObservation/ValueObserver.swift | 88 ++++++++++++----------- 2 files changed, 67 insertions(+), 53 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index bc1f6815a..ccbbfa980 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -383,29 +383,39 @@ extension DatabaseWriter { } catch { onError(error) } - } else if let queue = notificationQueue { - asyncWriteWithoutTransaction { db in + } else if prependingConcurrentFetch { + asyncRead { dbResult in do { + let db = try dbResult.get() observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) - let value = try observer.fetchInitialValue(db) - queue.async { - onChange(value) + let initialValue = try observer.fetchInitialValue(db) + observer.send(initialValue) + + self.asyncWriteWithoutTransaction { [weak observer] db in + guard let observer = observer else { return } + if observer.isCancelled { return } + do { + if let value = try observer.fetchNextValue(db) { + observer.send(value) + } + db.add(transactionObserver: observer, extent: .observerLifetime) + } catch { + observer.send(error) + } } - db.add(transactionObserver: observer, extent: .observerLifetime) } catch { - queue.async { - onError(error) - } + observer.send(error) } } } else { asyncWriteWithoutTransaction { db in do { observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) - try onChange(observer.fetchInitialValue(db)) + let initialValue = try observer.fetchInitialValue(db) + observer.send(initialValue) db.add(transactionObserver: observer, extent: .observerLifetime) } catch { - onError(error) + observer.send(error) } } } diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index c56c8235a..64fe7e86a 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -6,10 +6,11 @@ final class ValueObserver { var baseRegion = DatabaseRegion() { didSet { observedRegion = baseRegion.union(selectedRegion) } } - var selectedRegion = DatabaseRegion() { + private var selectedRegion = DatabaseRegion() { didSet { observedRegion = baseRegion.union(selectedRegion) } } var observedRegion: DatabaseRegion! // internal for testability + private(set) var isCancelled = false private var reducer: Reducer private let requiresWriteAccess: Bool private let observesSelectedRegion: Bool @@ -19,7 +20,6 @@ final class ValueObserver { private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void private var isChanged = false - private var isCancelled = false init( requiresWriteAccess: Bool, @@ -40,24 +40,56 @@ final class ValueObserver { self.onError = onError self.onChange = onChange } - - // Fetch initial value, with two side effects: - // - // This method must be called at most once, before the observer is added - // to the database writer. +} + +extension ValueObserver { + /// This method must be called at most once, before the observer is added + /// to the database writer. func fetchInitialValue(_ db: Database) throws -> Reducer.Value { - let value = try recordingSelectedRegionIfNeeded(db) { + guard let value = try fetchNextValue(db) else { + fatalError("Contract broken: reducer has no initial value") + } + return value + } + + func fetchNextValue(_ db: Database) throws -> Reducer.Value? { + try recordingSelectedRegionIfNeeded(db) { try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) } - if let value = value { - return value - } - fatalError("Contract broken: reducer has no initial value") + // fatalError("Contract broken: reducer has no initial value") } func cancel() { isCancelled = true } + + func send(_ value: Reducer.Value) { + if isCancelled { return } + if let queue = notificationQueue { + let onChange = self.onChange + queue.async { [weak self] in + guard let self = self else { return } + if self.isCancelled { return } + onChange(value) + } + } else { + onChange(value) + } + } + + func send(_ error: Error) { + if isCancelled { return } + if let queue = notificationQueue { + let onError = self.onError + queue.async { [weak self] in + guard let self = self else { return } + if self.isCancelled { return } + onError(error) + } + } else { + onError(error) + } + } } extension ValueObserver: TransactionObserver { @@ -114,9 +146,9 @@ extension ValueObserver: TransactionObserver { do { let (reducer, value) = try result.get() self.reducer = reducer - self.notify(value) + self.send(value) } catch { - self.notify(error) + self.send(error) } } } @@ -152,34 +184,6 @@ extension ValueObserver { return try block() } } - - private func notify(_ value: Reducer.Value) { - assert(!isCancelled) - if let queue = notificationQueue { - let onChange = self.onChange - queue.async { [weak self] in - guard let self = self else { return } - if self.isCancelled { return } - onChange(value) - } - } else { - onChange(value) - } - } - - private func notify(_ error: Error) { - assert(!isCancelled) - if let queue = notificationQueue { - let onError = self.onError - queue.async { [weak self] in - guard let self = self else { return } - if self.isCancelled { return } - onError(error) - } - } else { - onError(error) - } - } } class ValueObserverToken: TransactionObserver { From 65b8fbb361023d3cc3a5b7c96433079f62d57398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 14:23:45 +0100 Subject: [PATCH 07/44] Remove useless print() statements --- Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift | 1 - Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift | 1 - 2 files changed, 2 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 5d8c9ad14..2cfef5e6f 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -200,7 +200,6 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - print(records) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), diff --git a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift index 1b99ee0a3..67054464f 100644 --- a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift @@ -250,7 +250,6 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - print(records) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), From 2150b6688a3fe3452dc3c5ffd4e90cb51b346a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 14:37:26 +0100 Subject: [PATCH 08/44] Fix ValueObserver cancellation --- GRDB/ValueObservation/ValueObserver.swift | 46 +++++++---------------- 1 file changed, 14 insertions(+), 32 deletions(-) diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 64fe7e86a..487b4106f 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -14,7 +14,7 @@ final class ValueObserver { private var reducer: Reducer private let requiresWriteAccess: Bool private let observesSelectedRegion: Bool - private unowned let writer: DatabaseWriter + private weak var writer: DatabaseWriter? private let notificationQueue: DispatchQueue? private let reduceQueue: DispatchQueue private let onError: (Error) -> Void @@ -56,19 +56,20 @@ extension ValueObserver { try recordingSelectedRegionIfNeeded(db) { try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) } - // fatalError("Contract broken: reducer has no initial value") } func cancel() { isCancelled = true + writer?.asyncWriteWithoutTransaction { db in + db.remove(transactionObserver: self) + } } func send(_ value: Reducer.Value) { if isCancelled { return } if let queue = notificationQueue { let onChange = self.onChange - queue.async { [weak self] in - guard let self = self else { return } + queue.async { if self.isCancelled { return } onChange(value) } @@ -81,8 +82,7 @@ extension ValueObserver { if isCancelled { return } if let queue = notificationQueue { let onError = self.onError - queue.async { [weak self] in - guard let self = self else { return } + queue.async { if self.isCancelled { return } onError(error) } @@ -107,11 +107,11 @@ extension ValueObserver: TransactionObserver { } func databaseDidCommit(_ db: Database) { + guard let writer = writer else { return } if isCancelled { return } guard isChanged else { return } isChanged = false - let reducer = self.reducer let fetchedValue: DatabaseFuture if requiresWriteAccess || observesSelectedRegion { @@ -122,7 +122,7 @@ extension ValueObserver: TransactionObserver { } }) } else { - // Asynchronous fetch + // Concurrent fetch fetchedValue = writer.concurrentRead(reducer.fetch) } @@ -130,23 +130,11 @@ extension ValueObserver: TransactionObserver { // - that notifications have the same ordering as transactions. // - that expensive reduce operations are computed without blocking // any database dispatch queue. - reduceQueue.async { [weak self] in - guard let self = self else { return } + reduceQueue.async { if self.isCancelled { return } - - Self.reduce(fetchedValue: fetchedValue, with: reducer) { [weak self] result in - guard let self = self else { return } - if self.isCancelled { return } - - // Check that we're still on reduce queue. - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - dispatchPrecondition(condition: .onQueue(self.reduceQueue)) - } - + self.reduce(fetchedValue: fetchedValue) { result in do { - let (reducer, value) = try result.get() - self.reducer = reducer - self.send(value) + try self.send(result.get()) } catch { self.send(error) } @@ -160,15 +148,13 @@ extension ValueObserver: TransactionObserver { } extension ValueObserver { - private static func reduce( + private func reduce( fetchedValue: DatabaseFuture, - with reducer: Reducer, - completion: @escaping (Result<(Reducer, Reducer.Value), Error>) -> Void) + completion: @escaping (Result) -> Void) { do { - var reducer = reducer if let value = try reducer.value(fetchedValue.wait()) { - completion(.success((reducer, value))) + completion(.success(value)) } } catch { completion(.failure(error)) @@ -202,10 +188,6 @@ class ValueObserverToken: TransactionObserver { } deinit { - let observer = self.observer observer.cancel() - writer?.asyncWriteWithoutTransaction { db in - db.remove(transactionObserver: observer) - } } } From 8f5c7985e5eabbac6530694109b6a48f8ac4bdb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 14:38:24 +0100 Subject: [PATCH 09/44] ValueObservationRecorder --- GRDB.xcodeproj/project.pbxproj | 32 + Tests/GRDBTests/FailableTestCase.swift | 184 ++++++ .../ValueObservationExpectation.swift | 221 +++++++ .../GRDBTests/ValueObservationRecorder.swift | 228 +++++++ .../ValueObservationRecorderTests.swift | 572 ++++++++++++++++++ 5 files changed, 1237 insertions(+) create mode 100644 Tests/GRDBTests/FailableTestCase.swift create mode 100644 Tests/GRDBTests/ValueObservationExpectation.swift create mode 100644 Tests/GRDBTests/ValueObservationRecorder.swift create mode 100644 Tests/GRDBTests/ValueObservationRecorderTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index bba8fca4c..00af66130 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -378,6 +378,18 @@ 5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; 5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; }; + 56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; }; + 56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; }; + 56677C11241CEE690050755D /* ValueObservationExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C10241CEE690050755D /* ValueObservationExpectation.swift */; }; + 56677C12241CEE690050755D /* ValueObservationExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C10241CEE690050755D /* ValueObservationExpectation.swift */; }; + 56677C13241CEE690050755D /* ValueObservationExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C10241CEE690050755D /* ValueObservationExpectation.swift */; }; + 56677C15241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; }; + 56677C16241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; }; + 56677C17241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; }; + 56677C19241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */; }; + 56677C1A241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */; }; + 56677C1B241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */; }; 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; @@ -1325,6 +1337,10 @@ 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = ""; }; + 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = ""; }; + 56677C10241CEE690050755D /* ValueObservationExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationExpectation.swift; sourceTree = ""; }; + 56677C14241D14450050755D /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = ""; }; + 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1695,6 +1711,7 @@ children = ( 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, + 56677C14241D14450050755D /* FailableTestCase.swift */, 5698AC3E1DA2BEBB0056AF8C /* FTS */, 56176CA01EACEE2A000F3F2B /* GRDBCipher */, 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, @@ -1827,6 +1844,9 @@ 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */, 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */, + 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */, + 56677C10241CEE690050755D /* ValueObservationExpectation.swift */, + 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */, ); name = ValueObservation; sourceTree = ""; @@ -3024,6 +3044,7 @@ 56A238501B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */, + 56677C12241CEE690050755D /* ValueObservationExpectation.swift in Sources */, 569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */, @@ -3081,6 +3102,7 @@ 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, + 56677C16241D14450050755D /* FailableTestCase.swift in Sources */, 5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, @@ -3155,6 +3177,7 @@ 563EF440216131D1007DAACD /* AssociationAggregateTests.swift in Sources */, 5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */, 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, 5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, @@ -3200,6 +3223,7 @@ 56DF001E228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */, 56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */, 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, + 56677C1A241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */, 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */, 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -3230,6 +3254,7 @@ 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */, + 56677C11241CEE690050755D /* ValueObservationExpectation.swift in Sources */, 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */, 562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */, @@ -3287,6 +3312,7 @@ 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 56677C15241D14450050755D /* FailableTestCase.swift in Sources */, 5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, @@ -3361,6 +3387,7 @@ 563EF43F216131D1007DAACD /* AssociationAggregateTests.swift in Sources */, 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */, 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, @@ -3406,6 +3433,7 @@ 56DF001D228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */, 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, + 56677C19241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */, 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */, 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, @@ -3568,6 +3596,7 @@ AAA4DD15230F262000C74B15 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, AAA4DD16230F262000C74B15 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, AAA4DD17230F262000C74B15 /* RowFromDictionaryTests.swift in Sources */, + 56677C13241CEE690050755D /* ValueObservationExpectation.swift in Sources */, AAA4DD18230F262000C74B15 /* SchedulingWatchdogTests.swift in Sources */, AAA4DD19230F262000C74B15 /* CompilationProtocolTests.swift in Sources */, AAA4DD1A230F262000C74B15 /* DatabaseCollationTests.swift in Sources */, @@ -3625,6 +3654,7 @@ AAA4DD4B230F262000C74B15 /* FTS5CustomTokenizerTests.swift in Sources */, AAA4DD4C230F262000C74B15 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */, + 56677C17241D14450050755D /* FailableTestCase.swift in Sources */, AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */, 5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, @@ -3699,6 +3729,7 @@ AAA4DD91230F262000C74B15 /* AssociationAggregateTests.swift in Sources */, AAA4DD92230F262000C74B15 /* DatabasePoolSchemaCacheTests.swift in Sources */, AAA4DD93230F262000C74B15 /* AssociationRowScopeSearchTests.swift in Sources */, + 56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, AAA4DD94230F262000C74B15 /* FTS4TableBuilderTests.swift in Sources */, AAA4DD95230F262000C74B15 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, AAA4DD96230F262000C74B15 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, @@ -3744,6 +3775,7 @@ AAA4DDBF230F262000C74B15 /* AssociationPrefetchingCodableRecordTests.swift in Sources */, AAA4DDC0230F262000C74B15 /* DatabaseQueueInMemoryTests.swift in Sources */, AAA4DDC1230F262000C74B15 /* RecordWithColumnNameManglingTests.swift in Sources */, + 56677C1B241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */, AAA4DDC2230F262000C74B15 /* AssociationParallelSQLTests.swift in Sources */, AAA4DDC3230F262000C74B15 /* ValueObservationReducerTests.swift in Sources */, AAA4DDC4230F262000C74B15 /* RecordUniqueIndexTests.swift in Sources */, diff --git a/Tests/GRDBTests/FailableTestCase.swift b/Tests/GRDBTests/FailableTestCase.swift new file mode 100644 index 000000000..d7a2b9e4e --- /dev/null +++ b/Tests/GRDBTests/FailableTestCase.swift @@ -0,0 +1,184 @@ +// Inspired by https://github.com/groue/CombineExpectations +import XCTest + +/// A XCTestCase subclass that can test its own failures. +class FailureTestCase: XCTestCase { + private struct Failure: Hashable { + var prefix: String + var file: String + var line: Int + var expected: Bool + + func hash(into hasher: inout Hasher) { + hasher.combine(0) + } + + static func == (lhs: Failure, rhs: Failure) -> Bool { + lhs.prefix.hasPrefix(rhs.prefix) || rhs.prefix.hasPrefix(lhs.prefix) + } + } + + private var recordedFailures: [Failure] = [] + private var isRecordingFailures = false + + func assertFailure(_ prefixes: String..., file: StaticString = #file, line: UInt = #line, _ execute: () throws -> Void) rethrows { + let recordedFailures = try recordingFailures(execute) + if prefixes.isEmpty { + if recordedFailures.isEmpty { + recordFailure( + withDescription: "No failure did happen", + inFile: file.description, + atLine: Int(line), + expected: true) + } + } else { + let expectedFailures = prefixes.map { Failure(prefix: $0, file: file.description, line: Int(line), expected: true) } + assertMatch( + recordedFailures: recordedFailures, + expectedFailures: expectedFailures) + } + } + + override func setUp() { + super.setUp() + isRecordingFailures = false + recordedFailures = [] + } + + override func recordFailure(withDescription description: String, inFile filePath: String, atLine lineNumber: Int, expected: Bool) { + if isRecordingFailures { + recordedFailures.append(Failure(prefix: description, file: filePath, line: lineNumber, expected: expected)) + } else { + super.recordFailure(withDescription: description, inFile: filePath, atLine: lineNumber, expected: expected) + } + } + + private func recordingFailures(_ execute: () throws -> Void) rethrows -> [Failure] { + let oldRecordingFailures = isRecordingFailures + let oldRecordedFailures = recordedFailures + defer { + isRecordingFailures = oldRecordingFailures + recordedFailures = oldRecordedFailures + } + isRecordingFailures = true + recordedFailures = [] + try execute() + let result = recordedFailures + return result + } + + private func assertMatch(recordedFailures: [Failure], expectedFailures: [Failure]) { + var recordedFailures = recordedFailures + var expectedFailures = expectedFailures + + while !recordedFailures.isEmpty { + let failure = recordedFailures.removeFirst() + if let index = expectedFailures.firstIndex(of: failure) { + expectedFailures.remove(at: index) + } else { + recordFailure( + withDescription: failure.prefix, + inFile: failure.file, + atLine: failure.line, + expected: failure.expected) + } + } + + while !expectedFailures.isEmpty { + let failure = expectedFailures.removeFirst() + if let index = recordedFailures.firstIndex(of: failure) { + recordedFailures.remove(at: index) + } else { + recordFailure( + withDescription: "Failure did not happen: \(failure.prefix)", + inFile: failure.file, + atLine: failure.line, + expected: failure.expected) + } + } + } + + // MARK: - Tests + + func testEmptyTest() { + } + + func testExpectedAnyFailure() { + assertFailure { + XCTFail("foo") + } + assertFailure { + XCTFail("foo") + XCTFail("bar") + } + } + + func testMissingAnyFailure() { + assertFailure("No failure did happen") { + assertFailure { + } + } + } + + func testExpectedFailure() { + assertFailure("failed - foo") { + XCTFail("foo") + } + } + + func testExpectedFailureMatchesOnPrefix() { + assertFailure("failed - foo") { + XCTFail("foobarbaz") + } + } + + func testOrderOfExpectedFailureIsIgnored() { + assertFailure("failed - foo", "failed - bar") { + XCTFail("foo") + XCTFail("bar") + } + assertFailure("failed - bar", "failed - foo") { + XCTFail("foo") + XCTFail("bar") + } + } + + func testExpectedFailureCanBeRepeated() { + assertFailure("failed - foo", "failed - foo", "failed - bar") { + XCTFail("foo") + XCTFail("bar") + XCTFail("foo") + } + } + + func testExactNumberOfRepetitionIsRequired() { + assertFailure("Failure did not happen: failed - foo") { + assertFailure("failed - foo", "failed - foo") { + XCTFail("foo") + } + } + assertFailure("failed - foo") { + assertFailure("failed - foo", "failed - foo") { + XCTFail("foo") + XCTFail("foo") + XCTFail("foo") + } + } + } + + func testUnexpectedFailure() { + assertFailure("Failure did not happen: failed - foo") { + assertFailure("failed - foo") { + } + } + } + + func testMissedFailure() { + assertFailure("failed - bar") { + assertFailure("failed - foo") { + XCTFail("foo") + XCTFail("bar") + } + } + } +} diff --git a/Tests/GRDBTests/ValueObservationExpectation.swift b/Tests/GRDBTests/ValueObservationExpectation.swift new file mode 100644 index 000000000..49d7b52da --- /dev/null +++ b/Tests/GRDBTests/ValueObservationExpectation.swift @@ -0,0 +1,221 @@ +// Inspired by https://github.com/groue/CombineExpectations +import Foundation +import XCTest +#if GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +public enum ValueRecordingError: Error { + case notEnoughValues + case notFailed +} + +extension ValueRecordingError: LocalizedError { + public var errorDescription: String? { + switch self { + case .notEnoughValues: + return "ValueRecordingError.notEnoughValues" + case .notFailed: + return "ValueRecordingError.notFailed" + } + } +} + +public protocol _ValueObservationExpectationBase { + func _setup(_ expectation: XCTestExpectation) +} + +public protocol ValueObservationExpectation: _ValueObservationExpectationBase { + associatedtype Output + func get() throws -> Output +} + +extension XCTestCase { + public func wait( + for valueObservationExpectation: E, + timeout: TimeInterval, + description: String = "") + throws -> E.Output + { + let expectation = self.expectation(description: description) + valueObservationExpectation._setup(expectation) + wait(for: [expectation], timeout: timeout) + return try valueObservationExpectation.get() + } +} + +public enum ValueObservationExpectations { } + +extension ValueObservationExpectations { + public struct Inverted: ValueObservationExpectation { + let base: Base + + public func _setup(_ expectation: XCTestExpectation) { + base._setup(expectation) + expectation.isInverted.toggle() + } + + public func get() throws -> Base.Output { + try base.get() + } + } + + public struct NextOne: ValueObservationExpectation { + let recorder: ValueObservationRecorder + + public func _setup(_ expectation: XCTestExpectation) { + recorder.fulfillOnValue(expectation, includingConsumed: false) + } + + public func get() throws -> Value { + try recorder.value { (_, error, remainingElements, consume) in + if let next = remainingElements.first { + consume(1) + return next + } + if let error = error { + throw error + } else { + throw ValueRecordingError.notEnoughValues + } + } + } + + public var inverted: NextOneInverted { + return NextOneInverted(recorder: recorder) + } + } + + public struct NextOneInverted: ValueObservationExpectation { + let recorder: ValueObservationRecorder + + public func _setup(_ expectation: XCTestExpectation) { + expectation.isInverted = true + recorder.fulfillOnValue(expectation, includingConsumed: false) + } + + public func get() throws { + try recorder.value { (_, error, remainingElements, consume) in + if remainingElements.isEmpty == false { + return + } + if let error = error { + throw error + } + } + } + } + + public struct Next: ValueObservationExpectation { + let recorder: ValueObservationRecorder + let count: Int + + init(recorder: ValueObservationRecorder, count: Int) { + precondition(count >= 0, "Invalid negative count") + self.recorder = recorder + self.count = count + } + + public func _setup(_ expectation: XCTestExpectation) { + if count == 0 { + // Such an expectation is immediately fulfilled, by essence. + expectation.expectedFulfillmentCount = 1 + expectation.fulfill() + } else { + expectation.expectedFulfillmentCount = count + recorder.fulfillOnValue(expectation, includingConsumed: false) + } + } + + public func get() throws -> [Value] { + try recorder.value { (_, error, remainingElements, consume) in + if remainingElements.count >= count { + consume(count) + return Array(remainingElements.prefix(count)) + } + if let error = error { + throw error + } else { + throw ValueRecordingError.notEnoughValues + } + } + } + } + + public struct Prefix: ValueObservationExpectation { + let recorder: ValueObservationRecorder + let maxLength: Int + + init(recorder: ValueObservationRecorder, maxLength: Int) { + precondition(maxLength >= 0, "Invalid negative count") + self.recorder = recorder + self.maxLength = maxLength + } + + public func _setup(_ expectation: XCTestExpectation) { + if maxLength == 0 { + // Such an expectation is immediately fulfilled, by essence. + expectation.expectedFulfillmentCount = 1 + expectation.fulfill() + } else { + expectation.expectedFulfillmentCount = maxLength + recorder.fulfillOnValue(expectation, includingConsumed: true) + } + } + + public func get() throws -> [Value] { + try recorder.value { (elements, error, remainingElements, consume) in + if elements.count >= maxLength { + let extraCount = max(maxLength + remainingElements.count - elements.count, 0) + consume(extraCount) + return Array(elements.prefix(maxLength)) + } + if let error = error { + throw error + } + consume(remainingElements.count) + return elements + } + } + + public var inverted: Inverted { + return Inverted(base: self) + } + } + + public struct Failure: ValueObservationExpectation { + let recorder: ValueObservationRecorder + + public func _setup(_ expectation: XCTestExpectation) { + recorder.fulfillOnError(expectation) + } + + /// Returns the expected output, or throws an error if the + /// expectation fails. + /// + /// For example: + /// + /// // SUCCESS: no error + /// func testArrayPublisherSynchronousRecording() throws { + /// let publisher = ["foo", "bar", "baz"].publisher + /// let recorder = publisher.record() + /// let recording = try recorder.recording.get() + /// XCTAssertEqual(recording.output, ["foo", "bar", "baz"]) + /// if case let .failure(error) = recording.completion { + /// XCTFail("Unexpected error \(error)") + /// } + /// } + public func get() throws -> (values: [Value], error: Error) { + try recorder.value { (elements, error, remainingElements, consume) in + if let error = error { + consume(remainingElements.count) + return (values: elements, error: error) + } else { + throw ValueRecordingError.notFailed + } + } + } + } +} diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift new file mode 100644 index 000000000..606342374 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -0,0 +1,228 @@ +// Inspired by https://github.com/groue/CombineExpectations +import XCTest +#if GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +public class ValueObservationRecorder { + private struct RecorderExpectation { + var expectation: XCTestExpectation + var remainingCount: Int? // nil for error expectation + } + + /// The recorder state + private struct State { + var elements: [Element] + var error: Error? + var recorderExpectation: RecorderExpectation? + var observer: TransactionObserver? + } + + private let lock = NSLock() + private var state = State(elements: [], recorderExpectation: nil, observer: nil) + private var consumedCount = 0 + + /// The elements recorded so far. + var elementsAndError: ([Element], Error?) { + synchronized { + (state.elements, state.error) + } + } + + /// Internal for testability. Use ValueObservation.record(in:) instead. + init() { } + + private func synchronized(_ execute: () throws -> T) rethrows -> T { + lock.lock() + defer { lock.unlock() } + return try execute() + } + + // MARK: - PublisherExpectation API + + /// Registers the expectation so that it gets fulfilled when publisher + /// publishes elements or completes. + /// + /// - parameter expectation: An XCTestExpectation. + /// - parameter includingConsumed: This flag controls how elements that were + /// already published at the time this method is called fulfill the + /// expectation. If true, all published elements fulfill the expectation. + /// If false, only published elements that are not consumed yet fulfill + /// the expectation. For example, the Prefix expectation uses true, but + /// the NextOne expectation uses false. + func fulfillOnValue(_ expectation: XCTestExpectation, includingConsumed: Bool) { + synchronized { + preconditionCanFulfillExpectation() + + let expectedFulfillmentCount = expectation.expectedFulfillmentCount + + if state.error != nil { + expectation.fulfill(count: expectedFulfillmentCount) + return + } + + let elements = state.elements + let maxFulfillmentCount = includingConsumed + ? elements.count + : elements.count - consumedCount + let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount) + expectation.fulfill(count: fulfillmentCount) + + let remainingCount = expectedFulfillmentCount - fulfillmentCount + if remainingCount > 0 { + state.recorderExpectation = RecorderExpectation(expectation: expectation, remainingCount: remainingCount) + } + } + } + + /// Registers the expectation so that it gets fulfilled when + /// publisher completes. + func fulfillOnError(_ expectation: XCTestExpectation) { + synchronized { + preconditionCanFulfillExpectation() + + if state.error != nil { + expectation.fulfill() + return + } + + state.recorderExpectation = RecorderExpectation(expectation: expectation, remainingCount: nil) + } + } + + /// Returns a value based on the recorded state of the publisher. + /// + /// - parameter value: A function which returns the value, given the + /// recorded state of the publisher. + /// - parameter elements: All recorded elements. + /// - parameter remainingElements: The elements that were not consumed yet. + /// - parameter consume: A function which consumes elements. + /// - parameter count: The number of consumed elements. + /// - returns: The value + func value(_ value: ( + _ elements: [Element], + _ error: Error?, + _ remainingElements: ArraySlice, + _ consume: (_ count: Int) -> ()) throws -> T) + rethrows -> T + { + try synchronized { + let elements = state.elements + let remainingElements = elements[consumedCount...] + return try value(elements, state.error, remainingElements, { count in + precondition(count >= 0) + precondition(count <= remainingElements.count) + consumedCount += count + }) + } + } + + /// Checks that recorder can fulfill an expectation. + /// + /// The reason this method exists is that a recorder can fulfill a single + /// expectation at a given time. It is a programmer error to wait for two + /// expectations concurrently. + /// + /// This method MUST be called within a synchronized block. + private func preconditionCanFulfillExpectation() { + if let exp = state.recorderExpectation { + // We are already waiting for an expectation! Is it a programmer + // error? Recorder drops references to non-inverted expectations + // when they are fulfilled. But inverted expectations are not + // fulfilled, and thus not dropped. We can't quite know if an + // inverted expectations has expired yet, so just let it go. + precondition(exp.expectation.isInverted, "Already waiting for an expectation") + } + } + + fileprivate func receive(_ observer: TransactionObserver) { + synchronized { + if state.observer != nil { + XCTFail("Publisher recorder is already subscribed") + } + state.observer = observer + } + } + + /// Internal for testability. + func onChange(_ element: Element) { + return synchronized { + if state.error != nil { + XCTFail("Publisher recorder got unexpected element after completion: \(String(reflecting: element))") + } + + state.elements.append(element) + + if let exp = state.recorderExpectation, let remainingCount = exp.remainingCount { + assert(remainingCount > 0) + exp.expectation.fulfill() + if remainingCount > 1 { + state.recorderExpectation = RecorderExpectation(expectation: exp.expectation, remainingCount: remainingCount - 1) + } else { + state.recorderExpectation = nil + } + } + } + } + + /// Internal for testability. + func onError(_ error: Error) { + return synchronized { + if state.error != nil { + XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: error))") + } + + if let exp = state.recorderExpectation { + exp.expectation.fulfill(count: exp.remainingCount ?? 1) + state.recorderExpectation = nil + } + state.error = error + } + } +} + +// MARK: - Publisher Expectations + +extension ValueObservationRecorder { + public func failure() -> ValueObservationExpectations.Failure { + ValueObservationExpectations.Failure(recorder: self) + } + + public func next() -> ValueObservationExpectations.NextOne { + ValueObservationExpectations.NextOne(recorder: self) + } + + public func next(_ count: Int) -> ValueObservationExpectations.Next { + ValueObservationExpectations.Next(recorder: self, count: count) + } + + public func prefix(_ maxLength: Int) -> ValueObservationExpectations.Prefix { + ValueObservationExpectations.Prefix(recorder: self, maxLength: maxLength) + } +} + +// MARK: - ValueObservation + ValueObservationRecorder + +extension ValueObservation { + public func record(in reader: DatabaseReader) -> ValueObservationRecorder { + let recorder = ValueObservationRecorder() + let observer = start( + in: reader, + onError: recorder.onError, + onChange: recorder.onChange) + recorder.receive(observer) + return recorder + } +} + +// MARK: - Convenience + +extension XCTestExpectation { + fileprivate func fulfill(count: Int) { + for _ in 0..() + recorder.onChange("foo") + try XCTAssertEqual(recorder.next().get(), "foo") + recorder.onChange("bar") + try XCTAssertEqual(recorder.next().get(), "bar") + } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onChange("bar") + try XCTAssertEqual(recorder.next().get(), "foo") + try XCTAssertEqual(recorder.next().get(), "bar") + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("bar") + } + } + try XCTAssertEqual(wait(for: recorder.next(), timeout: 0.5), "foo") + try XCTAssertEqual(wait(for: recorder.next(), timeout: 0.5), "bar") + } + } + + func testNextOneError() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + _ = try recorder.next().get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + try XCTAssertEqual(recorder.next().get(), "foo") + do { + _ = try recorder.next().get() + XCTFail("Expected error") + } catch is CustomError { } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + _ = try wait(for: recorder.next(), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + } + try XCTAssertEqual(wait(for: recorder.next(), timeout: 0.5), "foo") + do { + _ = try wait(for: recorder.next(), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + } + + func testNextOneTimeout() throws { + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + _ = try wait(for: recorder.next(), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + try XCTAssertEqual(wait(for: recorder.next(), timeout: 0.5), "foo") + do { + _ = try wait(for: recorder.next(), timeout: 0.5) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + } + } + + func testNextOneNotEnoughElement() throws { + do { + let recorder = ValueObservationRecorder() + _ = try recorder.next().get() + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + try XCTAssertEqual(recorder.next().get(), "foo") + do { + _ = try recorder.next().get() + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + } + + // MARK: - NextOne Inverted + + func testNextOneInvertedSuccess() throws { + do { + let recorder = ValueObservationRecorder() + try recorder.next().inverted.get() + } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + _ = try recorder.next().get() + try recorder.next().inverted.get() + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + _ = try wait(for: recorder.next(), timeout: 0.5) + try wait(for: recorder.next().inverted, timeout: 0.5) + } + } + + func testNextOneInvertedError() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + try recorder.next().inverted.get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + _ = try recorder.next().get() + do { + try recorder.next().inverted.get() + XCTFail("Expected error") + } catch is CustomError { } + } + } + + func testNextOneInvertedTimeout() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + try assertFailure("Fulfilled inverted expectation") { + try wait(for: recorder.next().inverted, timeout: 0.5) + } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("bar") + } + } + _ = try wait(for: recorder.next(), timeout: 0.5) + try assertFailure("Fulfilled inverted expectation") { + try wait(for: recorder.next().inverted, timeout: 0.5) + } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + try assertFailure("Fulfilled inverted expectation") { + do { + try wait(for: recorder.next().inverted, timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + } + _ = try wait(for: recorder.next(), timeout: 0.5) + try assertFailure("Fulfilled inverted expectation") { + do { + try wait(for: recorder.next().inverted, timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + } + } + + // MARK: - Next + + func testNextSuccess() throws { + do { + let recorder = ValueObservationRecorder() + try XCTAssertEqual(recorder.next(0).get(), []) + recorder.onChange("foo") + try XCTAssertEqual(recorder.next(1).get(), ["foo"]) + recorder.onChange("bar") + recorder.onChange("baz") + try XCTAssertEqual(recorder.next(2).get(), ["bar", "baz"]) + } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onChange("bar") + try XCTAssertEqual(recorder.next(1).get(), ["foo"]) + recorder.onChange("baz") + try XCTAssertEqual(recorder.next(2).get(), ["bar", "baz"]) + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("bar") + } + } + try XCTAssertEqual(wait(for: recorder.next(2), timeout: 0.5), ["foo", "bar"]) + } + } + + func testNextError() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + _ = try recorder.next(2).get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + _ = try recorder.next(2).get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + _ = try wait(for: recorder.next(2), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + } + _ = try wait(for: recorder.next(2), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + + func testNextTimeout() throws { + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + _ = try wait(for: recorder.next(2), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + _ = try wait(for: recorder.next(2), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + _ = try wait(for: recorder.next(2), timeout: 0.5) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + } + + func testNextNotEnoughElement() throws { + do { + let recorder = ValueObservationRecorder() + _ = try recorder.next(2).get() + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + _ = try recorder.next(2).get() + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + + // MARK: - Prefix + + func testPrefixSuccess() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + try XCTAssertEqual(recorder.prefix(0).get(), []) + recorder.onChange("foo") + try XCTAssertEqual(recorder.prefix(0).get(), []) + try XCTAssertEqual(recorder.prefix(1).get(), ["foo"]) + recorder.onChange("bar") + recorder.onChange("baz") + try XCTAssertEqual(recorder.prefix(0).get(), []) + try XCTAssertEqual(recorder.prefix(1).get(), ["foo"]) + try XCTAssertEqual(recorder.prefix(2).get(), ["foo", "bar"]) + try XCTAssertEqual(recorder.prefix(3).get(), ["foo", "bar", "baz"]) + } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + try XCTAssertEqual(recorder.prefix(0).get(), []) + } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + try XCTAssertEqual(recorder.prefix(1).get(), ["foo"]) + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("bar") + } + } + try XCTAssertEqual(wait(for: recorder.prefix(2), timeout: 0.5), ["foo", "bar"]) + } + } + + func testPrefixError() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + _ = try recorder.next(2).get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + _ = try recorder.next(2).get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + _ = try wait(for: recorder.next(2), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + } + _ = try wait(for: recorder.next(2), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + + func testPrefixTimeout() throws { + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + _ = try wait(for: recorder.next(2), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + _ = try wait(for: recorder.next(2), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + _ = try wait(for: recorder.next(2), timeout: 0.5) + XCTFail("Expected error") + } catch ValueRecordingError.notEnoughValues { } + } + } + + // MARK: - Prefix Inverted + + func testPrefixInvertedSuccess() throws { + do { + let recorder = ValueObservationRecorder() + try XCTAssertEqual(recorder.prefix(1).inverted.get(), []) + } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + try XCTAssertEqual(recorder.prefix(2).inverted.get(), ["foo"]) + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + try XCTAssertEqual(wait(for: recorder.prefix(2).inverted, timeout: 0.5), ["foo"]) + } + } + + func testPrefixInvertedError() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + _ = try recorder.prefix(1).inverted.get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + _ = try recorder.prefix(2).inverted.get() + XCTFail("Expected error") + } catch is CustomError { } + } + + func testPrefixInvertedTimeout() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + try assertFailure("Fulfilled inverted expectation") { + _ = try wait(for: recorder.prefix(1).inverted, timeout: 0.5) + } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("bar") + } + } + try assertFailure("Fulfilled inverted expectation") { + _ = try wait(for: recorder.prefix(2).inverted, timeout: 0.5) + } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + try assertFailure("Fulfilled inverted expectation") { + do { + _ = try wait(for: recorder.prefix(1).inverted, timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + } + try assertFailure("Fulfilled inverted expectation") { + do { + _ = try wait(for: recorder.prefix(2).inverted, timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + } + } + + // MARK: - Failure + + func testFailureSuccess() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + let (elements, error) = try recorder.failure().get() + XCTAssertEqual(elements, []) + XCTAssert(error is CustomError) + } + } + + func testFailureTimeout() throws { + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + _ = try wait(for: recorder.failure(), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notFailed { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + _ = try wait(for: recorder.failure(), timeout: 0.1) + XCTFail("Expected error") + } catch ValueRecordingError.notFailed { } + } + try assertFailure("Asynchronous wait failed") { + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + _ = try wait(for: recorder.failure(), timeout: 0.5) + XCTFail("Expected error") + } catch ValueRecordingError.notFailed { } + } + } + + func testFailureNotFailed() throws { + do { + let recorder = ValueObservationRecorder() + _ = try recorder.failure().get() + XCTFail("Expected error") + } catch ValueRecordingError.notFailed { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + _ = try recorder.failure().get() + XCTFail("Expected error") + } catch ValueRecordingError.notFailed { } + } +} From 3c891b7ebde161ba3d3620d47d5d5e5fd6496c49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 15:10:16 +0100 Subject: [PATCH 10/44] ValueObservationRecorder cleanup --- GRDB.xcodeproj/project.pbxproj | 12 +- GRDBCustom.xcodeproj/project.pbxproj | 12 + .../ValueObservationExpectation.swift | 221 ----------- .../GRDBTests/ValueObservationRecorder.swift | 370 ++++++++++++++---- .../ValueObservationRecorderTests.swift | 20 + 5 files changed, 322 insertions(+), 313 deletions(-) delete mode 100644 Tests/GRDBTests/ValueObservationExpectation.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 00af66130..fb4c0af20 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -381,9 +381,6 @@ 56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; }; 56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; }; 56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; }; - 56677C11241CEE690050755D /* ValueObservationExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C10241CEE690050755D /* ValueObservationExpectation.swift */; }; - 56677C12241CEE690050755D /* ValueObservationExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C10241CEE690050755D /* ValueObservationExpectation.swift */; }; - 56677C13241CEE690050755D /* ValueObservationExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C10241CEE690050755D /* ValueObservationExpectation.swift */; }; 56677C15241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; }; 56677C16241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; }; 56677C17241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; }; @@ -1338,7 +1335,6 @@ 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = ""; }; 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = ""; }; - 56677C10241CEE690050755D /* ValueObservationExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationExpectation.swift; sourceTree = ""; }; 56677C14241D14450050755D /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = ""; }; 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; @@ -1839,14 +1835,13 @@ 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */, 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, + 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */, + 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */, 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */, 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */, - 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */, - 56677C10241CEE690050755D /* ValueObservationExpectation.swift */, - 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */, ); name = ValueObservation; sourceTree = ""; @@ -3044,7 +3039,6 @@ 56A238501B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */, - 56677C12241CEE690050755D /* ValueObservationExpectation.swift in Sources */, 569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */, @@ -3254,7 +3248,6 @@ 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */, - 56677C11241CEE690050755D /* ValueObservationExpectation.swift in Sources */, 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */, 562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */, @@ -3596,7 +3589,6 @@ AAA4DD15230F262000C74B15 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, AAA4DD16230F262000C74B15 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, AAA4DD17230F262000C74B15 /* RowFromDictionaryTests.swift in Sources */, - 56677C13241CEE690050755D /* ValueObservationExpectation.swift in Sources */, AAA4DD18230F262000C74B15 /* SchedulingWatchdogTests.swift in Sources */, AAA4DD19230F262000C74B15 /* CompilationProtocolTests.swift in Sources */, AAA4DD1A230F262000C74B15 /* DatabaseCollationTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index f294dc1c3..5f6c9d238 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -265,6 +265,10 @@ 5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */; }; 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */; }; + 56677C25241E6EA20050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C23241E6EA10050755D /* ValueObservationRecorderTests.swift */; }; + 56677C26241E6EA20050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C23241E6EA10050755D /* ValueObservationRecorderTests.swift */; }; + 56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C24241E6EA20050755D /* ValueObservationRecorder.swift */; }; + 56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C24241E6EA20050755D /* ValueObservationRecorder.swift */; }; 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; @@ -876,6 +880,8 @@ 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = ""; }; 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = ""; }; + 56677C23241E6EA10050755D /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = ""; }; + 56677C24241E6EA20050755D /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = ""; }; 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; @@ -1331,6 +1337,8 @@ 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */, 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, + 56677C24241E6EA20050755D /* ValueObservationRecorder.swift */, + 56677C23241E6EA10050755D /* ValueObservationRecorderTests.swift */, 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */, @@ -2343,6 +2351,7 @@ 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, 5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, + 56677C26241E6EA20050755D /* ValueObservationRecorderTests.swift in Sources */, 5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, 5698AC501DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, 5665FA1F2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, @@ -2416,6 +2425,7 @@ 5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, 563B06DA2185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, @@ -2681,6 +2691,7 @@ F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5656A7F622946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, + 56677C25241E6EA20050755D /* ValueObservationRecorderTests.swift in Sources */, 5615B258222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, 5665FA1E2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */, @@ -2754,6 +2765,7 @@ 5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, 563B06D92185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationExpectation.swift b/Tests/GRDBTests/ValueObservationExpectation.swift deleted file mode 100644 index 49d7b52da..000000000 --- a/Tests/GRDBTests/ValueObservationExpectation.swift +++ /dev/null @@ -1,221 +0,0 @@ -// Inspired by https://github.com/groue/CombineExpectations -import Foundation -import XCTest -#if GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - import GRDB -#endif - -public enum ValueRecordingError: Error { - case notEnoughValues - case notFailed -} - -extension ValueRecordingError: LocalizedError { - public var errorDescription: String? { - switch self { - case .notEnoughValues: - return "ValueRecordingError.notEnoughValues" - case .notFailed: - return "ValueRecordingError.notFailed" - } - } -} - -public protocol _ValueObservationExpectationBase { - func _setup(_ expectation: XCTestExpectation) -} - -public protocol ValueObservationExpectation: _ValueObservationExpectationBase { - associatedtype Output - func get() throws -> Output -} - -extension XCTestCase { - public func wait( - for valueObservationExpectation: E, - timeout: TimeInterval, - description: String = "") - throws -> E.Output - { - let expectation = self.expectation(description: description) - valueObservationExpectation._setup(expectation) - wait(for: [expectation], timeout: timeout) - return try valueObservationExpectation.get() - } -} - -public enum ValueObservationExpectations { } - -extension ValueObservationExpectations { - public struct Inverted: ValueObservationExpectation { - let base: Base - - public func _setup(_ expectation: XCTestExpectation) { - base._setup(expectation) - expectation.isInverted.toggle() - } - - public func get() throws -> Base.Output { - try base.get() - } - } - - public struct NextOne: ValueObservationExpectation { - let recorder: ValueObservationRecorder - - public func _setup(_ expectation: XCTestExpectation) { - recorder.fulfillOnValue(expectation, includingConsumed: false) - } - - public func get() throws -> Value { - try recorder.value { (_, error, remainingElements, consume) in - if let next = remainingElements.first { - consume(1) - return next - } - if let error = error { - throw error - } else { - throw ValueRecordingError.notEnoughValues - } - } - } - - public var inverted: NextOneInverted { - return NextOneInverted(recorder: recorder) - } - } - - public struct NextOneInverted: ValueObservationExpectation { - let recorder: ValueObservationRecorder - - public func _setup(_ expectation: XCTestExpectation) { - expectation.isInverted = true - recorder.fulfillOnValue(expectation, includingConsumed: false) - } - - public func get() throws { - try recorder.value { (_, error, remainingElements, consume) in - if remainingElements.isEmpty == false { - return - } - if let error = error { - throw error - } - } - } - } - - public struct Next: ValueObservationExpectation { - let recorder: ValueObservationRecorder - let count: Int - - init(recorder: ValueObservationRecorder, count: Int) { - precondition(count >= 0, "Invalid negative count") - self.recorder = recorder - self.count = count - } - - public func _setup(_ expectation: XCTestExpectation) { - if count == 0 { - // Such an expectation is immediately fulfilled, by essence. - expectation.expectedFulfillmentCount = 1 - expectation.fulfill() - } else { - expectation.expectedFulfillmentCount = count - recorder.fulfillOnValue(expectation, includingConsumed: false) - } - } - - public func get() throws -> [Value] { - try recorder.value { (_, error, remainingElements, consume) in - if remainingElements.count >= count { - consume(count) - return Array(remainingElements.prefix(count)) - } - if let error = error { - throw error - } else { - throw ValueRecordingError.notEnoughValues - } - } - } - } - - public struct Prefix: ValueObservationExpectation { - let recorder: ValueObservationRecorder - let maxLength: Int - - init(recorder: ValueObservationRecorder, maxLength: Int) { - precondition(maxLength >= 0, "Invalid negative count") - self.recorder = recorder - self.maxLength = maxLength - } - - public func _setup(_ expectation: XCTestExpectation) { - if maxLength == 0 { - // Such an expectation is immediately fulfilled, by essence. - expectation.expectedFulfillmentCount = 1 - expectation.fulfill() - } else { - expectation.expectedFulfillmentCount = maxLength - recorder.fulfillOnValue(expectation, includingConsumed: true) - } - } - - public func get() throws -> [Value] { - try recorder.value { (elements, error, remainingElements, consume) in - if elements.count >= maxLength { - let extraCount = max(maxLength + remainingElements.count - elements.count, 0) - consume(extraCount) - return Array(elements.prefix(maxLength)) - } - if let error = error { - throw error - } - consume(remainingElements.count) - return elements - } - } - - public var inverted: Inverted { - return Inverted(base: self) - } - } - - public struct Failure: ValueObservationExpectation { - let recorder: ValueObservationRecorder - - public func _setup(_ expectation: XCTestExpectation) { - recorder.fulfillOnError(expectation) - } - - /// Returns the expected output, or throws an error if the - /// expectation fails. - /// - /// For example: - /// - /// // SUCCESS: no error - /// func testArrayPublisherSynchronousRecording() throws { - /// let publisher = ["foo", "bar", "baz"].publisher - /// let recorder = publisher.record() - /// let recording = try recorder.recording.get() - /// XCTAssertEqual(recording.output, ["foo", "bar", "baz"]) - /// if case let .failure(error) = recording.completion { - /// XCTFail("Unexpected error \(error)") - /// } - /// } - public func get() throws -> (values: [Value], error: Error) { - try recorder.value { (elements, error, remainingElements, consume) in - if let error = error { - consume(remainingElements.count) - return (values: elements, error: error) - } else { - throw ValueRecordingError.notFailed - } - } - } - } -} diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 606342374..596f9de67 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -1,12 +1,14 @@ // Inspired by https://github.com/groue/CombineExpectations import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite +import GRDBCustomSQLite #else - import GRDB +import GRDB #endif -public class ValueObservationRecorder { +// MARK: - ValueObservationRecorder + +public class ValueObservationRecorder { private struct RecorderExpectation { var expectation: XCTestExpectation var remainingCount: Int? // nil for error expectation @@ -14,23 +16,16 @@ public class ValueObservationRecorder { /// The recorder state private struct State { - var elements: [Element] + var values: [Value] var error: Error? var recorderExpectation: RecorderExpectation? var observer: TransactionObserver? } private let lock = NSLock() - private var state = State(elements: [], recorderExpectation: nil, observer: nil) + private var state = State(values: [], recorderExpectation: nil, observer: nil) private var consumedCount = 0 - /// The elements recorded so far. - var elementsAndError: ([Element], Error?) { - synchronized { - (state.elements, state.error) - } - } - /// Internal for testability. Use ValueObservation.record(in:) instead. init() { } @@ -40,18 +35,48 @@ public class ValueObservationRecorder { return try execute() } - // MARK: - PublisherExpectation API + // MARK: ValueObservation API + + // Internal for testability. + func onChange(_ value: Value) { + return synchronized { + if state.error != nil { + // This is possible with ValueObservation, but not supported by ValueObservationRecorder + XCTFail("ValueObservationRecorder got unexpected value after error: \(String(reflecting: value))") + } + + state.values.append(value) + + if let exp = state.recorderExpectation, let remainingCount = exp.remainingCount { + assert(remainingCount > 0) + exp.expectation.fulfill() + if remainingCount > 1 { + state.recorderExpectation = RecorderExpectation(expectation: exp.expectation, remainingCount: remainingCount - 1) + } else { + state.recorderExpectation = nil + } + } + } + } + + // Internal for testability. + func onError(_ error: Error) { + return synchronized { + if state.error != nil { + // This is possible with ValueObservation, but not supported by ValueObservationRecorder + XCTFail("f got unexpected error after error: \(String(describing: error))") + } + + if let exp = state.recorderExpectation { + exp.expectation.fulfill(count: exp.remainingCount ?? 1) + state.recorderExpectation = nil + } + state.error = error + } + } + + // MARK: ValueObservationExpectation API - /// Registers the expectation so that it gets fulfilled when publisher - /// publishes elements or completes. - /// - /// - parameter expectation: An XCTestExpectation. - /// - parameter includingConsumed: This flag controls how elements that were - /// already published at the time this method is called fulfill the - /// expectation. If true, all published elements fulfill the expectation. - /// If false, only published elements that are not consumed yet fulfill - /// the expectation. For example, the Prefix expectation uses true, but - /// the NextOne expectation uses false. func fulfillOnValue(_ expectation: XCTestExpectation, includingConsumed: Bool) { synchronized { preconditionCanFulfillExpectation() @@ -63,22 +88,22 @@ public class ValueObservationRecorder { return } - let elements = state.elements + let values = state.values let maxFulfillmentCount = includingConsumed - ? elements.count - : elements.count - consumedCount + ? values.count + : values.count - consumedCount let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount) expectation.fulfill(count: fulfillmentCount) let remainingCount = expectedFulfillmentCount - fulfillmentCount if remainingCount > 0 { state.recorderExpectation = RecorderExpectation(expectation: expectation, remainingCount: remainingCount) + } else { + state.recorderExpectation = nil } } } - /// Registers the expectation so that it gets fulfilled when - /// publisher completes. func fulfillOnError(_ expectation: XCTestExpectation) { synchronized { preconditionCanFulfillExpectation() @@ -92,28 +117,28 @@ public class ValueObservationRecorder { } } - /// Returns a value based on the recorded state of the publisher. + /// Returns a value based on the recorded state. /// /// - parameter value: A function which returns the value, given the - /// recorded state of the publisher. - /// - parameter elements: All recorded elements. - /// - parameter remainingElements: The elements that were not consumed yet. - /// - parameter consume: A function which consumes elements. - /// - parameter count: The number of consumed elements. + /// recorded state. + /// - parameter values: All recorded values. + /// - parameter remainingValues: The values that were not consumed yet. + /// - parameter consume: A function which consumes values. + /// - parameter count: The number of consumed values. /// - returns: The value func value(_ value: ( - _ elements: [Element], + _ values: [Value], _ error: Error?, - _ remainingElements: ArraySlice, + _ remainingValues: ArraySlice, _ consume: (_ count: Int) -> ()) throws -> T) rethrows -> T { try synchronized { - let elements = state.elements - let remainingElements = elements[consumedCount...] - return try value(elements, state.error, remainingElements, { count in + let values = state.values + let remainingValues = values[consumedCount...] + return try value(values, state.error, remainingValues, { count in precondition(count >= 0) - precondition(count <= remainingElements.count) + precondition(count <= remainingValues.count) consumedCount += count }) } @@ -140,65 +165,29 @@ public class ValueObservationRecorder { fileprivate func receive(_ observer: TransactionObserver) { synchronized { if state.observer != nil { - XCTFail("Publisher recorder is already subscribed") + XCTFail("ValueObservationRecorder is already observing") } state.observer = observer } } - - /// Internal for testability. - func onChange(_ element: Element) { - return synchronized { - if state.error != nil { - XCTFail("Publisher recorder got unexpected element after completion: \(String(reflecting: element))") - } - - state.elements.append(element) - - if let exp = state.recorderExpectation, let remainingCount = exp.remainingCount { - assert(remainingCount > 0) - exp.expectation.fulfill() - if remainingCount > 1 { - state.recorderExpectation = RecorderExpectation(expectation: exp.expectation, remainingCount: remainingCount - 1) - } else { - state.recorderExpectation = nil - } - } - } - } - - /// Internal for testability. - func onError(_ error: Error) { - return synchronized { - if state.error != nil { - XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: error))") - } - - if let exp = state.recorderExpectation { - exp.expectation.fulfill(count: exp.remainingCount ?? 1) - state.recorderExpectation = nil - } - state.error = error - } - } } -// MARK: - Publisher Expectations +// MARK: - ValueObservationRecorder + Expectations extension ValueObservationRecorder { - public func failure() -> ValueObservationExpectations.Failure { + public func failure() -> ValueObservationExpectations.Failure { ValueObservationExpectations.Failure(recorder: self) } - public func next() -> ValueObservationExpectations.NextOne { + public func next() -> ValueObservationExpectations.NextOne { ValueObservationExpectations.NextOne(recorder: self) } - public func next(_ count: Int) -> ValueObservationExpectations.Next { + public func next(_ count: Int) -> ValueObservationExpectations.Next { ValueObservationExpectations.Next(recorder: self, count: count) } - public func prefix(_ maxLength: Int) -> ValueObservationExpectations.Prefix { + public func prefix(_ maxLength: Int) -> ValueObservationExpectations.Prefix { ValueObservationExpectations.Prefix(recorder: self, maxLength: maxLength) } } @@ -217,6 +206,223 @@ extension ValueObservation { } } +// MARK: - ValueObservationExpectation + +public enum ValueRecordingError: Error { + case notEnoughValues + case notFailed +} + +extension ValueRecordingError: LocalizedError { + public var errorDescription: String? { + switch self { + case .notEnoughValues: + return "ValueRecordingError.notEnoughValues" + case .notFailed: + return "ValueRecordingError.notFailed" + } + } +} + +public protocol _ValueObservationExpectationBase { + func _setup(_ expectation: XCTestExpectation) +} + +public protocol ValueObservationExpectation: _ValueObservationExpectationBase { + associatedtype Output + func get() throws -> Output +} + +// MARK: - XCTestCase + ValueObservationExpectation + +extension XCTestCase { + public func wait( + for valueObservationExpectation: E, + timeout: TimeInterval, + description: String = "") + throws -> E.Output + { + let expectation = self.expectation(description: description) + valueObservationExpectation._setup(expectation) + wait(for: [expectation], timeout: timeout) + return try valueObservationExpectation.get() + } +} + +// MARK: - ValueObservationExpectations + +public enum ValueObservationExpectations { } + +extension ValueObservationExpectations { + + // MARK: Inverted + + public struct Inverted: ValueObservationExpectation { + let base: Base + + public func _setup(_ expectation: XCTestExpectation) { + base._setup(expectation) + expectation.isInverted.toggle() + } + + public func get() throws -> Base.Output { + try base.get() + } + } + + // MARK: NextOne + + public struct NextOne: ValueObservationExpectation { + let recorder: ValueObservationRecorder + + public func _setup(_ expectation: XCTestExpectation) { + recorder.fulfillOnValue(expectation, includingConsumed: false) + } + + public func get() throws -> Value { + try recorder.value { (_, error, remainingValues, consume) in + if let next = remainingValues.first { + consume(1) + return next + } + if let error = error { + throw error + } else { + throw ValueRecordingError.notEnoughValues + } + } + } + + public var inverted: NextOneInverted { + return NextOneInverted(recorder: recorder) + } + } + + // MARK: NextOneInverted + + public struct NextOneInverted: ValueObservationExpectation { + let recorder: ValueObservationRecorder + + public func _setup(_ expectation: XCTestExpectation) { + expectation.isInverted = true + recorder.fulfillOnValue(expectation, includingConsumed: false) + } + + public func get() throws { + try recorder.value { (_, error, remainingValues, consume) in + if remainingValues.isEmpty == false { + return + } + if let error = error { + throw error + } + } + } + } + + // MARK: Next + + public struct Next: ValueObservationExpectation { + let recorder: ValueObservationRecorder + let count: Int + + init(recorder: ValueObservationRecorder, count: Int) { + precondition(count >= 0, "Invalid negative count") + self.recorder = recorder + self.count = count + } + + public func _setup(_ expectation: XCTestExpectation) { + if count == 0 { + // Such an expectation is immediately fulfilled, by essence. + expectation.expectedFulfillmentCount = 1 + expectation.fulfill() + } else { + expectation.expectedFulfillmentCount = count + recorder.fulfillOnValue(expectation, includingConsumed: false) + } + } + + public func get() throws -> [Value] { + try recorder.value { (_, error, remainingValues, consume) in + if remainingValues.count >= count { + consume(count) + return Array(remainingValues.prefix(count)) + } + if let error = error { + throw error + } else { + throw ValueRecordingError.notEnoughValues + } + } + } + } + + // MARK: Prefix + + public struct Prefix: ValueObservationExpectation { + let recorder: ValueObservationRecorder + let maxLength: Int + + init(recorder: ValueObservationRecorder, maxLength: Int) { + precondition(maxLength >= 0, "Invalid negative count") + self.recorder = recorder + self.maxLength = maxLength + } + + public func _setup(_ expectation: XCTestExpectation) { + if maxLength == 0 { + // Such an expectation is immediately fulfilled, by essence. + expectation.expectedFulfillmentCount = 1 + expectation.fulfill() + } else { + expectation.expectedFulfillmentCount = maxLength + recorder.fulfillOnValue(expectation, includingConsumed: true) + } + } + + public func get() throws -> [Value] { + try recorder.value { (values, error, remainingValues, consume) in + if values.count >= maxLength { + let extraCount = max(maxLength + remainingValues.count - values.count, 0) + consume(extraCount) + return Array(values.prefix(maxLength)) + } + if let error = error { + throw error + } + consume(remainingValues.count) + return values + } + } + + public var inverted: Inverted { + return Inverted(base: self) + } + } + + // MARK: Failure + + public struct Failure: ValueObservationExpectation { + let recorder: ValueObservationRecorder + + public func _setup(_ expectation: XCTestExpectation) { + recorder.fulfillOnError(expectation) + } + + public func get() throws -> (values: [Value], error: Error) { + try recorder.value { (values, error, remainingValues, consume) in + if let error = error { + consume(remainingValues.count) + return (values: values, error: error) + } else { + throw ValueRecordingError.notFailed + } + } + } + } +} + // MARK: - Convenience extension XCTestExpectation { diff --git a/Tests/GRDBTests/ValueObservationRecorderTests.swift b/Tests/GRDBTests/ValueObservationRecorderTests.swift index 171b966dc..6243fb350 100644 --- a/Tests/GRDBTests/ValueObservationRecorderTests.swift +++ b/Tests/GRDBTests/ValueObservationRecorderTests.swift @@ -19,6 +19,13 @@ class ValueObservationRecorderTests: FailureTestCase { try XCTAssertEqual(recorder.next().get(), "foo") try XCTAssertEqual(recorder.next().get(), "bar") } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onChange("bar") + try XCTAssertEqual(wait(for: recorder.next(), timeout: 0.5), "foo") + try XCTAssertEqual(wait(for: recorder.next(), timeout: 0.5), "bar") + } do { let recorder = ValueObservationRecorder() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { @@ -40,6 +47,12 @@ class ValueObservationRecorderTests: FailureTestCase { _ = try recorder.next().get() XCTFail("Expected error") } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + _ = try wait(for: recorder.next(), timeout: 0.1) + XCTFail("Expected error") + } catch is CustomError { } do { let recorder = ValueObservationRecorder() recorder.onChange("foo") @@ -526,6 +539,13 @@ class ValueObservationRecorderTests: FailureTestCase { XCTAssertEqual(elements, []) XCTAssert(error is CustomError) } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + let (elements, error) = try wait(for: recorder.failure(), timeout: 0.1) + XCTAssertEqual(elements, []) + XCTAssert(error is CustomError) + } } func testFailureTimeout() throws { From 79351683797acd60f708668f0cd5d2c12cf1307b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 16:44:43 +0100 Subject: [PATCH 11/44] ValueObservation test refactoring WIP --- .../ValueObservationCountTests.swift | 51 +++++++++++-------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index a625aa5c2..48cc1701e 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -12,25 +12,15 @@ import XCTest class ValueObservationCountTests: GRDBTestCase { func testCount() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 5 - - struct T: TableRecord { } - let observation = T.all().observationForCount() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, scheduling: ValueObservationScheduling) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + struct T: TableRecord { } + var observation = T.all().observationForCount() + observation.scheduling = scheduling + let recorder = observation.record(in: writer) + + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 try db.execute(sql: "UPDATE t SET id = id") // = try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 @@ -43,8 +33,27 @@ class ValueObservationCountTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2, 3, 2]) + // We don't expect more than five values: [0, 1, 2, 3, 2] + let expectedValues = [0, 1, 2, 3, 2] + let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let context = "\(type(of: writer)), \(scheduling)" + XCTAssert(!values.isEmpty, context) + for count in 1...max(expectedValues.count, values.count) where count <= values.count { + XCTAssertEqual( + expectedValues.suffix(count), + values.suffix(count), + context) + } + } + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + for scheduling in schedulings { + try test(writer: DatabaseQueue(), scheduling: scheduling) + try test(writer: makeDatabaseQueue(), scheduling: scheduling) + try test(writer: makeDatabasePool(), scheduling: scheduling) } } From ed6673f2f5bf994f9b6a330a462f7010024fcf3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 17:09:40 +0100 Subject: [PATCH 12/44] ValueObservation test refactoring WIP --- .../ValueObservationCountTests.swift | 67 ++++++------------- 1 file changed, 19 insertions(+), 48 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 48cc1701e..1f7d5df9a 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -12,12 +12,9 @@ import XCTest class ValueObservationCountTests: GRDBTestCase { func testCount() throws { - func test(writer: DatabaseWriter, scheduling: ValueObservationScheduling) throws { + func test(writer: DatabaseWriter, observation: ValueObservation>>) throws { try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - struct T: TableRecord { } - var observation = T.all().observationForCount() - observation.scheduling = scheduling let recorder = observation.record(in: writer) try writer.writeWithoutTransaction { db in @@ -36,7 +33,7 @@ class ValueObservationCountTests: GRDBTestCase { // We don't expect more than five values: [0, 1, 2, 3, 2] let expectedValues = [0, 1, 2, 3, 2] let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) - let context = "\(type(of: writer)), \(scheduling)" + let context = "\(type(of: writer)), \(observation.scheduling)" XCTAssert(!values.isEmpty, context) for count in 1...max(expectedValues.count, values.count) where count <= values.count { XCTAssertEqual( @@ -45,52 +42,26 @@ class ValueObservationCountTests: GRDBTestCase { context) } } - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - for scheduling in schedulings { - try test(writer: DatabaseQueue(), scheduling: scheduling) - try test(writer: makeDatabaseQueue(), scheduling: scheduling) - try test(writer: makeDatabasePool(), scheduling: scheduling) - } - } - - func testTableRecordStaticCount() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 5 struct T: TableRecord { } - let observation = T.observationForCount() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 - try db.execute(sql: "UPDATE t SET id = id") // = - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "DELETE FROM t WHERE id = 1") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1 - } + let observations = [ + T.all().observationForCount(), + T.observationForCount()] + + for var observation in observations { + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2, 3, 2]) + for scheduling in schedulings { + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } } } From 4ffced0b7b6d63a43e6b19cdb50dc73ab3310fab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 20:16:15 +0100 Subject: [PATCH 13/44] assertValueObservationRecordingMatch --- .../ValueObservationCountTests.swift | 13 +- ...rvationDatabaseValueConvertibleTests.swift | 52 ++++---- .../GRDBTests/ValueObservationRecorder.swift | 59 +++++++++ .../ValueObservationRecorderTests.swift | 114 ++++++++++++++++++ 4 files changed, 207 insertions(+), 31 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 1f7d5df9a..9b85be278 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -30,17 +30,12 @@ class ValueObservationCountTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1 } - // We don't expect more than five values: [0, 1, 2, 3, 2] let expectedValues = [0, 1, 2, 3, 2] let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) - let context = "\(type(of: writer)), \(observation.scheduling)" - XCTAssert(!values.isEmpty, context) - for count in 1...max(expectedValues.count, values.count) where count <= values.count { - XCTAssertEqual( - expectedValues.suffix(count), - values.suffix(count), - context) - } + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") } struct T: TableRecord { } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 14ead2dbf..74b4fd57a 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -12,7 +12,7 @@ import XCTest @testable import GRDB #endif -private struct Name: DatabaseValueConvertible { +private struct Name: DatabaseValueConvertible, Equatable { var rawValue: String var databaseValue: DatabaseValue { rawValue.databaseValue } @@ -27,24 +27,12 @@ private struct Name: DatabaseValueConvertible { class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { func testAll() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Name]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { names in - results.append(names) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let recorder = observation.record(in: writer) + + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -56,12 +44,32 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.rawValue)}, [ + let expectedValues = [ [], ["foo"], ["foo", "bar"], - ["bar"]]) + ["bar"]] + let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + .map { $0.map(\.rawValue) } + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 596f9de67..c5a4d654a 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -247,6 +247,65 @@ extension XCTestCase { wait(for: [expectation], timeout: timeout) return try valueObservationExpectation.get() } + + /// See testAssertValueObservationRecordingMatch() + public func assertValueObservationRecordingMatch( + recorded recordedValues: [Value], + expected expectedValues: [Value], + _ message: @autoclosure () -> String = "", + file: StaticString = #file, + line: UInt = #line) + throws + where Value: Equatable + { + try assertValueObservationRecordingMatch( + recorded: recordedValues, + expected: expectedValues, + // Last value can't be missed, this is the most important of all! + allowMissingLastValue: false, + message(), file: file, line: line) + } + + private func assertValueObservationRecordingMatch( + recorded recordedValues: R, + expected expectedValues: E, + allowMissingLastValue: Bool, + _ message: @autoclosure () -> String = "", + file: StaticString = #file, + line: UInt = #line) + throws + where + R: BidirectionalCollection, + E: BidirectionalCollection, + R.Element == E.Element, + R.Element: Equatable + { + guard let value = expectedValues.last else { + if !recordedValues.isEmpty { + XCTFail("unexpected recorded prefix \(Array(recordedValues)) - \(message())", file: file, line: line) + } + return + } + + let recordedSuffix = recordedValues.reversed().prefix(while: { $0 == value }) + let expectedSuffix = expectedValues.reversed().prefix(while: { $0 == value }) + if !allowMissingLastValue { + // Both missing and duplicated values are allowed in the recorded values. + // This is because of asynchronous DatabasePool observations. + if recordedSuffix.isEmpty { + XCTFail("missing expected value \(value) - \(message())", file: file, line: line) + } + } + + let remainingRecordedValues = recordedValues.prefix(recordedValues.count - recordedSuffix.count) + let remainingExpectedValues = expectedValues.prefix(expectedValues.count - expectedSuffix.count) + try assertValueObservationRecordingMatch( + recorded: remainingRecordedValues, + expected: remainingExpectedValues, + // Other values can be missed + allowMissingLastValue: true, + message(), file: file, line: line) + } } // MARK: - ValueObservationExpectations diff --git a/Tests/GRDBTests/ValueObservationRecorderTests.swift b/Tests/GRDBTests/ValueObservationRecorderTests.swift index 6243fb350..d7e1d1075 100644 --- a/Tests/GRDBTests/ValueObservationRecorderTests.swift +++ b/Tests/GRDBTests/ValueObservationRecorderTests.swift @@ -589,4 +589,118 @@ class ValueObservationRecorderTests: FailureTestCase { XCTFail("Expected error") } catch ValueRecordingError.notFailed { } } + + // MARK: - assertValueObservationRecordingMatch + + func testAssertValueObservationRecordingMatch() throws { + do { + let expected = [3] + try assertValueObservationRecordingMatch(recorded: [3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + try assertFailure("failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [2]", "failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [2]") { + try assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) + } + } + do { + let expected = [2, 3] + try assertValueObservationRecordingMatch(recorded: [3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [2, 2, 3, 3], expected: expected) + try assertFailure("failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [], expected: expected) + } + try assertFailure("failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + } + try assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") { + try assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [1]") { + try assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [1]") { + try assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) + } + } + do { + let expected = [3, 3] + try assertValueObservationRecordingMatch(recorded: [3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected) + try assertFailure("failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [], expected: expected) + } + try assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [2]") { + try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [2]") { + try assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [2, 2]") { + try assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [1, 2]") { + try assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) + } + } + do { + let expected = [1, 2, 2, 3] + try assertValueObservationRecordingMatch(recorded: [3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 3, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 1, 3, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 2, 2, 3], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) + try assertFailure("failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [], expected: expected) + } + try assertFailure("failed - missing expected value 3") { + try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + } + try assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") { + try assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [2]") { + try assertValueObservationRecordingMatch(recorded: [2, 1, 3], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [0]") { + try assertValueObservationRecordingMatch(recorded: [0, 3], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [0]") { + try assertValueObservationRecordingMatch(recorded: [0, 1, 2, 3], expected: expected) + } + } + do { + let expected = [1, 2, 1] + try assertValueObservationRecordingMatch(recorded: [1], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 1], expected: expected) + try assertValueObservationRecordingMatch(recorded: [2, 1], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 2, 1], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 1, 2, 1], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 2, 1, 1], expected: expected) + try assertValueObservationRecordingMatch(recorded: [1, 2, 2, 1], expected: expected) + try assertFailure("failed - missing expected value 1") { + try assertValueObservationRecordingMatch(recorded: [], expected: expected) + } + try assertFailure("failed - missing expected value 1") { + try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + } + try assertFailure("failed - missing expected value 1") { + try assertValueObservationRecordingMatch(recorded: [1, 2], expected: expected) + } + try assertFailure("failed - unexpected recorded prefix [0]") { + try assertValueObservationRecordingMatch(recorded: [0, 1], expected: expected) + } + } + } } From 3ee231afd3ab05a8f4c68774c94c78158c3e0556 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 20:44:58 +0100 Subject: [PATCH 14/44] Cleanup _OptionalProtocol --- GRDB/Core/DatabaseValueConvertible.swift | 10 +++++----- GRDB/Core/StatementColumnConvertible.swift | 10 +++++----- GRDB/Fixit/GRDB-5.0.swift | 4 ++-- GRDB/Utils/Utils.swift | 8 ++------ .../ValueObservation+DatabaseValueConvertible.swift | 6 +++--- 5 files changed, 17 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index a4d57c5ee..d87db3bf7 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -599,7 +599,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { } } -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { // MARK: Fetching Optional values @@ -619,8 +619,8 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - parameter db: A database connection. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { - try Optional.fetchCursor(db, self) + public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { + try Optional.fetchCursor(db, self) } /// An array of fetched optional values. @@ -631,7 +631,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - try Optional.fetchAll(db, self) + public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { + try Optional.fetchAll(db, self) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 12245ea59..452ed0b27 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -606,7 +606,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv extension FetchRequest where RowDecoder: _OptionalProtocol, - RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible + RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible { // MARK: Fetching Optional values @@ -627,8 +627,8 @@ extension FetchRequest /// - parameter db: A database connection. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor { - try Optional.fetchCursor(db, self) + public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor { + try Optional.fetchCursor(db, self) } /// An array of fetched optional values. @@ -639,7 +639,7 @@ extension FetchRequest /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - try Optional.fetchAll(db, self) + public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { + try Optional.fetchAll(db, self) } } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 2e0935825..1d5f8fb99 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -177,9 +177,9 @@ extension ValueObservation where Reducer == Never { @available(*, unavailable, message: "Use request.observationForAll() instead") public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: _OptionalProtocol, - Request.RowDecoder._Wrapped: DatabaseValueConvertible + Request.RowDecoder.Wrapped: DatabaseValueConvertible { preconditionFailure() } @available(*, unavailable, message: "Use request.observationForAll() instead") diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 7811ee18d..41d4caa50 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -29,7 +29,7 @@ public func databaseQuestionMarks(count: Int) -> String { public protocol _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - associatedtype _Wrapped + associatedtype Wrapped } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -37,11 +37,7 @@ public protocol _OptionalProtocol { /// This conformance is an implementation detail of GRDB. Don't rely on it. /// /// :nodoc: -extension Optional: _OptionalProtocol { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public typealias _Wrapped = Wrapped -} +extension Optional: _OptionalProtocol { } // MARK: - Internal diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index bca7b616e..e9a87c967 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -61,7 +61,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { } } -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { // MARK: - Observation @@ -88,7 +88,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// `start` is deallocated. /// /// - returns: a ValueObservation. - public func observationForAll() -> ValueObservation> { + public func observationForAll() -> ValueObservation> { ValueObservation( baseRegion: databaseRegion, makeReducer: { ValueReducers.AllOptionalValues { try DatabaseValue.fetchAll($0, self) } }) @@ -117,7 +117,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// `start` is deallocated. /// /// - returns: a ValueObservation. - public func observationForFirst() -> ValueObservation> { + public func observationForFirst() -> ValueObservation> { ValueObservation( baseRegion: databaseRegion, makeReducer: { ValueReducers.OneValue { try DatabaseValue.fetchOne($0, self) } }) From 22086c088f31a3aa6bf5b535952c4f2e0243c46b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 20:45:33 +0100 Subject: [PATCH 15/44] More test refactoring with assertValueObservationRecordingMatch --- ...rvationDatabaseValueConvertibleTests.swift | 101 ++++++++++-------- 1 file changed, 57 insertions(+), 44 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 74b4fd57a..6b5e10247 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -50,9 +50,8 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { ["foo", "bar"], ["bar"]] let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) - .map { $0.map(\.rawValue) } try assertValueObservationRecordingMatch( - recorded: values, + recorded: values.map { $0.map(\.rawValue) }, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") } @@ -74,24 +73,12 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } func testOne() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Name?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 7 - - let observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { name in - results.append(name) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let recorder = observation.record(in: writer) + + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") try db.inTransaction { @@ -108,37 +95,44 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "UPDATE t SET name = 'qux'") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.rawValue)}, [ + let expectedValues = [ nil, "foo", "bar", nil, "baz", nil, - "qux"]) + "qux"] + let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values.map { $0.map(\.rawValue) }, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testAllOptional() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Name?]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { names in - results.append(names) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let recorder = observation.record(in: writer) + + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -150,12 +144,31 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map { $0?.rawValue }}, [ + let expectedValues = [ [], ["foo"], ["foo", nil], - [nil]]) + [nil]] + let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values.map { $0.map { $0?.rawValue }}, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } From 7ab9a8b29a8634d2699e58f0b5a61360a9c67403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 20:56:09 +0100 Subject: [PATCH 16/44] More test refactoring with assertValueObservationRecordingMatch --- ...rvationDatabaseValueConvertibleTests.swift | 49 +++++++++++-------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 6b5e10247..9d457d286 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -173,24 +173,12 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } func testOneOptional() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Name?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 7 - - let observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { name in - results.append(name) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let recorder = observation.record(in: writer) + + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") try db.inTransaction { @@ -207,15 +195,34 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "UPDATE t SET name = 'qux'") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.rawValue)}, [ + let expectedValues = [ nil, "foo", "bar", nil, "baz", nil, - "qux"]) + "qux"] + let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values.map { $0.map(\.rawValue)}, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } From 3e0486743bd4bcae249fcb24c7dd748499780d56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 15:21:24 +0100 Subject: [PATCH 17/44] More test refactoring with assertValueObservationRecordingMatch --- .../ValueObservationCountTests.swift | 6 +- ...rvationDatabaseValueConvertibleTests.swift | 42 ++++-- .../ValueObservationFetchTests.swift | 122 ++++++++++-------- 3 files changed, 102 insertions(+), 68 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 9b85be278..810403f1e 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -31,7 +31,11 @@ class ValueObservationCountTests: GRDBTestCase { } let expectedValues = [0, 1, 2, 3, 2] - let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) try assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 9d457d286..4d2fa844a 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -1,15 +1,15 @@ import XCTest #if GRDBCUSTOMSQLITE - @testable import GRDBCustomSQLite +@testable import GRDBCustomSQLite #else - #if GRDBCIPHER - import SQLCipher - #elseif SWIFT_PACKAGE - import CSQLite - #else - import SQLite3 - #endif - @testable import GRDB +#if GRDBCIPHER +import SQLCipher +#elseif SWIFT_PACKAGE +import CSQLite +#else +import SQLite3 +#endif +@testable import GRDB #endif private struct Name: DatabaseValueConvertible, Equatable { @@ -49,7 +49,11 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { ["foo"], ["foo", "bar"], ["bar"]] - let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) try assertValueObservationRecordingMatch( recorded: values.map { $0.map(\.rawValue) }, expected: expectedValues, @@ -103,7 +107,11 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { "baz", nil, "qux"] - let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) try assertValueObservationRecordingMatch( recorded: values.map { $0.map(\.rawValue) }, expected: expectedValues, @@ -149,7 +157,11 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { ["foo"], ["foo", nil], [nil]] - let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) try assertValueObservationRecordingMatch( recorded: values.map { $0.map { $0?.rawValue }}, expected: expectedValues, @@ -203,7 +215,11 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { "baz", nil, "qux"] - let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) try assertValueObservationRecordingMatch( recorded: values.map { $0.map(\.rawValue)}, expected: expectedValues, diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index 4deb31679..a8fe8ccf7 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -21,72 +21,86 @@ class ValueObservationFetchTests: GRDBTestCase { } func testFetch() throws { - func test(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 + let recorder = observation.record(in: writer) - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "UPDATE t SET id = id") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 1, 2]) + try writer.writeWithoutTransaction { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "UPDATE t SET id = id") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } + + let expectedValues = [0, 1, 1, 2] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") } - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }) + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } func testRemoveDuplicated() throws { - func test(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + func test(writer: DatabaseWriter, observation: ValueObservation>>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 + let recorder = observation.record(in: writer) - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }).removeDuplicates() - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "UPDATE t SET id = id") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2]) + try writer.writeWithoutTransaction { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "UPDATE t SET id = id") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } + + let expectedValues = [0, 1, 2] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") } - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }).removeDuplicates() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } } From 031b55eca62b55100369a629d78912b0faa0204f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 15:50:36 +0100 Subject: [PATCH 18/44] More test refactoring with assertValueObservationRecordingMatch --- .../GRDBTests/ValueObservationMapTests.swift | 68 ++++++++++--------- 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index 153db17ae..981cd7cd8 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -12,45 +12,47 @@ import XCTest class ValueObservationMapTests: GRDBTestCase { func testMap() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(writer: DatabaseWriter, observation: ValueObservation, String>>) throws { // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - var counts: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 + let recorder = observation.record(in: writer) - // Create an observation - var count = 0 - let observation = ValueObservation - .tracking(DatabaseRegion.fullDatabase, fetch: { _ -> Int in - count += 1 - return count - }) - .map { count -> String in return "\(count)" } - - // Start observation - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, ["1", "2", "3"]) + try writer.writeWithoutTransaction { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } + + let expectedValues = ["0", "1", "2"] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") } - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = ValueObservation + .tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }) + .map { "\($0)" } + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } func testMapPreservesConfiguration() { From b392458c1c87fb94a7965b78838cc35fd865e570 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 16:23:41 +0100 Subject: [PATCH 19/44] More test refactoring with assertValueObservationRecordingMatch --- ...bservationQueryInterfaceRequestTests.swift | 216 ++++++++---------- 1 file changed, 101 insertions(+), 115 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 62b244e8e..fad8095a1 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -51,166 +51,125 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { func testOneRowWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() - - var results: [Row?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - let request = Parent .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() .asRequest(of: Row.self) let observation = request.observationForFirst() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { row in - results.append(row) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.count, 2) - - XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[0]!.prefetchedRows["children"], [ - ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], - ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) - - XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[1]!.prefetchedRows["children"], []) + + let recorder = observation.record(in: dbQueue) + try dbQueue.inDatabase { db in + try db.execute(sql: "DELETE FROM child") } + let results = try wait(for: recorder.next(2), timeout: 1) + + XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[0]!.prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + + XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[1]!.prefetchedRows["children"], []) } func testAllRowsWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() - - var results: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - let request = Parent .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() .asRequest(of: Row.self) let observation = request.observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { rows in - results.append(rows) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.count, 2) - - XCTAssertEqual(results[0].count, 2) - XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[0][0].prefetchedRows["children"], [ - ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], - ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) - XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"]) - XCTAssertEqual(results[0][1].prefetchedRows["children"], [ - ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) - - XCTAssertEqual(results[1].count, 2) - XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[1][0].prefetchedRows["children"], []) - XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"]) - XCTAssertEqual(results[1][1].prefetchedRows["children"], []) + + let recorder = observation.record(in: dbQueue) + try dbQueue.inDatabase { db in + try db.execute(sql: "DELETE FROM child") } + let results = try wait(for: recorder.next(2), timeout: 1) + + XCTAssertEqual(results[0].count, 2) + XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[0][0].prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[0][1].prefetchedRows["children"], [ + ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) + + XCTAssertEqual(results[1].count, 2) + XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[1][0].prefetchedRows["children"], []) + XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[1][1].prefetchedRows["children"], []) } func testOneRecordWithPrefetchedRows() throws { - let dbQueue = try makeDatabaseQueue() - - var results: [ParentInfo?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: ParentInfo.self) - let observation = request.observationForFirst() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { parentInfo in - results.append(parentInfo) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "DELETE FROM child") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ + let expectedValues = [ ParentInfo( parent: Parent(id: 1, name: "foo"), children: [ Child(id: 1, parentId: 1, name: "fooA"), Child(id: 2, parentId: 1, name: "fooB"), - ]), + ]), ParentInfo( parent: Parent(id: 1, name: "foo"), children: []), - ]) + ] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + let request = Parent + .including(all: Parent.children.orderByPrimaryKey()) + .orderByPrimaryKey() + .asRequest(of: ParentInfo.self) + var observation = request.observationForFirst() + observation.scheduling = scheduling + + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testAllRecordsWithPrefetchedRows() throws { - let dbQueue = try makeDatabaseQueue() - - var results: [[ParentInfo]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: ParentInfo.self) - let observation = request.observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { parentInfos in - results.append(parentInfos) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "DELETE FROM child") } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ + + let expectedValues = [ [ ParentInfo( parent: Parent(id: 1, name: "foo"), children: [ Child(id: 1, parentId: 1, name: "fooA"), Child(id: 2, parentId: 1, name: "fooB"), - ]), + ]), ParentInfo( parent: Parent(id: 2, name: "bar"), children: [ Child(id: 3, parentId: 2, name: "barA"), - ]), + ]), ], [ ParentInfo( @@ -220,7 +179,34 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { parent: Parent(id: 2, name: "bar"), children: []), ], - ]) + ] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + let request = Parent + .including(all: Parent.children.orderByPrimaryKey()) + .orderByPrimaryKey() + .asRequest(of: ParentInfo.self) + var observation = request.observationForAll() + observation.scheduling = scheduling + + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } } From 9d4bef1c9a506c3b50b160915010aab73cd95377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 17:04:18 +0100 Subject: [PATCH 20/44] More test refactoring with assertValueObservationRecordingMatch --- .../ValueObservationReadonlyTests.swift | 222 ++++++++++-------- 1 file changed, 130 insertions(+), 92 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift index e9a83e2ce..25cbe03ff 100644 --- a/Tests/GRDBTests/ValueObservationReadonlyTests.swift +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -1,125 +1,163 @@ import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite +import GRDBCustomSQLite #else - #if SWIFT_PACKAGE - import CSQLite - #else - import SQLite3 - #endif - import GRDB +#if SWIFT_PACKAGE +import CSQLite +#else +import SQLite3 +#endif +import GRDB #endif class ValueObservationReadonlyTests: GRDBTestCase { func testReadOnlyObservation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + let recorder = observation.record(in: writer) + try writer.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + let expectedValues = [0, 1] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }) + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testWriteObservationFailsByDefaultWithErrorHandling() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + let recorder = observation.record(in: writer) + + let (values, error) = try wait(for: recorder.failure(), timeout: 0.5) + XCTAssert(values.isEmpty) + do { + throw error + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_READONLY) + XCTAssertEqual(error.message, "attempt to write a readonly database") + XCTAssertEqual(error.sql!, "INSERT INTO t DEFAULT VALUES") + XCTAssertEqual(error.description, "SQLite error 8 with statement `INSERT INTO t DEFAULT VALUES`: attempt to write a readonly database") + } + } - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - return 0 - }) + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] - var error: DatabaseError! - _ = observation.start( - in: dbQueue, - onError: { error = $0 as? DatabaseError }, - onChange: { _ in fatalError() }) - - XCTAssertEqual(error.resultCode, .SQLITE_READONLY) - XCTAssertEqual(error.message, "attempt to write a readonly database") - XCTAssertEqual(error.sql!, "INSERT INTO t DEFAULT VALUES") - XCTAssertEqual(error.description, "SQLite error 8 with statement `INSERT INTO t DEFAULT VALUES`: attempt to write a readonly database") + for scheduling in schedulings { + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + return 0 + }) + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } func testWriteObservation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in - XCTAssert(db.isInsideTransaction, "expected a wrapping transaction") - try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t") - let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")! - try db.execute(sql: "DROP TABLE temp") - return result - }) - observation.requiresWriteAccess = true - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + let recorder = observation.record(in: writer) + try writer.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + let expectedValues = [0, 1] + let values = try wait(for: recorder.next(2), timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in + XCTAssert(db.isInsideTransaction, "expected a wrapping transaction") + try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t") + let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")! + try db.execute(sql: "DROP TABLE temp") + return result + }) + observation.requiresWriteAccess = true + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testWriteObservationIsWrappedInSavepointWithErrorHandling() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { - try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") - } - struct TestError: Error { } - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - throw TestError() - }) - observation.requiresWriteAccess = true - var error: Error? - _ = observation.start( - in: dbQueue, - onError: { error = $0 }, - onChange: { _ in fatalError() }) - guard error is TestError else { - XCTFail("Expected TestError") - return + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + let recorder = observation.record(in: writer) + + let (_, error) = try wait(for: recorder.failure(), timeout: 0.5) + do { + throw error + } catch is TestError { + let count = try writer.read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } + XCTAssertEqual(count, 0) + } } - let count = try dbQueue.read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } - XCTAssertEqual(count, 0) + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + throw TestError() + }) + observation.requiresWriteAccess = true + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } } From e16b320cda31f650c533c976fe3c61b6d111adf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 17:42:22 +0100 Subject: [PATCH 21/44] More test refactoring with assertValueObservationRecordingMatch --- .../ValueObservationReadonlyTests.swift | 4 +- .../ValueObservationRecordTests.swift | 178 ++++++++++-------- 2 files changed, 104 insertions(+), 78 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift index 25cbe03ff..4a893f0ad 100644 --- a/Tests/GRDBTests/ValueObservationReadonlyTests.swift +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -16,7 +16,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { func test(writer: DatabaseWriter, observation: ValueObservation>) throws { try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } let recorder = observation.record(in: writer) - try writer.write { + try writer.writeWithoutTransaction { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } @@ -90,7 +90,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { func test(writer: DatabaseWriter, observation: ValueObservation>) throws { try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } let recorder = observation.record(in: writer) - try writer.write { + try writer.writeWithoutTransaction { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index 9d7b89a1a..e29dbf206 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -10,39 +10,24 @@ import XCTest import GRDB #endif -private struct Player: TableRecord, FetchableRecord { - static let databaseTableName = "t" +private struct Player: Equatable { var id: Int64 var name: String - +} + +extension Player: TableRecord, FetchableRecord { + static let databaseTableName = "t" init(row: Row) { - self.id = row["id"] - self.name = row["name"] + self.init(id: row["id"], name: row["name"]) } - - var row: Row { ["id": id, "name": name] } } class ValueObservationRecordTests: GRDBTestCase { func testAll() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Player]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { players in - results.append(players) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -54,34 +39,43 @@ class ValueObservationRecordTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.row)}, [ + let expectedValues = [ [], - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) + [Player(id: 1, name: "foo")], + [Player(id: 1, name: "foo"), Player(id: 2, name: "bar")], + [Player(id: 2, name: "bar")]] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testTableRecordStaticAll() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Player]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = Player.observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { players in - results.append(players) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -93,34 +87,43 @@ class ValueObservationRecordTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.row)}, [ + let expectedValues = [ [], - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) + [Player(id: 1, name: "foo")], + [Player(id: 1, name: "foo"), Player(id: 2, name: "bar")], + [Player(id: 2, name: "bar")]] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = Player.observationForAll() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testOne() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Player?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { player in - results.append(player) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -132,12 +135,35 @@ class ValueObservationRecordTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.row)}, [ + let expectedValues = [ nil, - ["id":1, "name":"foo"], - ["id":2, "name":"bar"], - nil]) + Player(id: 1, name: "foo"), + Player(id: 2, name: "bar"), + nil] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } } From c42aab26e387a5d454f405f440074c0751cf6218 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 17:48:24 +0100 Subject: [PATCH 22/44] Remove redundant test --- .../ValueObservationReducerTests.swift | 33 ------------------- 1 file changed, 33 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index dc71d6e7f..3324a9fb4 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -231,39 +231,6 @@ class ValueObservationReducerTests: GRDBTestCase { try test(makeDatabasePool()) } - func testValueObservationMap() throws { - func test(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - struct T: TableRecord { } - let observation = T.observationForCount().map { "\($0)" } - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, ["0", "1", "2"]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - func testReducerQueueLabel() throws { func test(_ dbWriter: DatabaseWriter, expectedLabels: [String]) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } From 6bf322f79e36e6fab5c6569e739f4ba9d092e5c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 18:16:35 +0100 Subject: [PATCH 23/44] More test refactoring with assertValueObservationRecordingMatch --- .../GRDBTests/ValueObservationRowTests.swift | 314 ++++++++++-------- 1 file changed, 180 insertions(+), 134 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index bb5ba7906..7f356cc86 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -12,24 +12,10 @@ import XCTest class ValueObservationRowTests: GRDBTestCase { func testAll() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { rows in - results.append(rows) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -41,34 +27,43 @@ class ValueObservationRowTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ + let expectedValues: [[Row]] = [ [], [["id":1, "name":"foo"]], [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) + [["id":2, "name":"bar"]]] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testOne() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Row?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { row in - results.append(row) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, observation: ValueObservation) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 @@ -79,123 +74,174 @@ class ValueObservationRowTests: GRDBTestCase { } try db.execute(sql: "DELETE FROM t") // -1 } + + let expectedValues: [Row?] = [ + nil, + ["id":1, "name":"foo"], + ["id":2, "name":"bar"], + nil] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ - nil, - ["id":1, "name":"foo"], - ["id":2, "name":"bar"], - nil]) + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst() + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } } func testFTS4Observation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.create(virtualTable: "ft_documents", using: FTS4()) - } - - var rows: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = SQLRequest(sql: "SELECT * FROM ft_documents") - let observation = ValueObservation.tracking(value: request.fetchAll) - let observer = observation.start( - in: dbQueue, - onError: { error in - XCTFail("unexpected error: \(error)") - }, - onChange: { - rows.append($0) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { try $0.create(virtualTable: "ft_documents", using: FTS4()) } + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(rows, [[], [["content":"foo"]]]) + + let expectedValues: [[Row]] = [ + [], + [["content":"foo"]]] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + let request = SQLRequest(sql: "SELECT * FROM ft_documents") + var observation = ValueObservation.tracking(value: request.fetchAll) + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testSynchronizedFTS4Observation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.create(table: "documents") { t in - t.column("id", .integer).primaryKey() - t.column("content", .text) + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { db in + try db.create(table: "documents") { t in + t.column("id", .integer).primaryKey() + t.column("content", .text) + } + try db.create(virtualTable: "ft_documents", using: FTS4()) { t in + t.synchronize(withTable: "documents") + t.column("content") + } } - try db.create(virtualTable: "ft_documents", using: FTS4()) { t in - t.synchronize(withTable: "documents") - t.column("content") - } - } - - var rows: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = SQLRequest(sql: "SELECT * FROM ft_documents") - let observation = ValueObservation.tracking(value: request.fetchAll) - let observer = observation.start( - in: dbQueue, - onError: { error in - XCTFail("unexpected error: \(error)") - }, - onChange: { - rows.append($0) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(rows, [[], [["content":"foo"]]]) + + let expectedValues: [[Row]] = [ + [], + [["content":"foo"]]] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + let request = SQLRequest(sql: "SELECT * FROM ft_documents") + var observation = ValueObservation.tracking(value: request.fetchAll) + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } func testJoinedFTS4Observation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.create(table: "document") { t in - t.autoIncrementedPrimaryKey("id") + func test(writer: DatabaseWriter, observation: ValueObservation>) throws { + try writer.write { db in + try db.create(table: "document") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(virtualTable: "ft_document", using: FTS4()) { t in + t.column("content") + } } - try db.create(virtualTable: "ft_document", using: FTS4()) { t in - t.column("content") - } - } - - var rows: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = SQLRequest(sql: """ - SELECT document.* FROM document - JOIN ft_document ON ft_document.rowid = document.id - WHERE ft_document MATCH 'foo' - """) - let observation = ValueObservation.tracking(value: request.fetchAll) - let observer = observation.start( - in: dbQueue, - onError: { error in - XCTFail("unexpected error: \(error)") - }, - onChange: { - rows.append($0) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in + let recorder = observation.record(in: writer) + try writer.write { db in try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1]) try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(rows, [[], [["id":1]]]) + + let expectedValues: [[Row]] = [ + [], + [["id":1]]] + let values = try wait( + for: recorder + .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) + .inverted, + timeout: 0.5) + try assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(type(of: writer)), \(observation.scheduling)") + } + + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + + for scheduling in schedulings { + let request = SQLRequest(sql: """ + SELECT document.* FROM document + JOIN ft_document ON ft_document.rowid = document.id + WHERE ft_document MATCH 'foo' + """) + var observation = ValueObservation.tracking(value: request.fetchAll) + observation.scheduling = scheduling + + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) } } } From e16d29f277675d8fd1011a573781f1396396a41a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Mar 2020 18:44:02 +0100 Subject: [PATCH 24/44] More test refactoring with assertValueObservationRecordingMatch --- .../ValueObservationCombineTests.swift | 994 ++++++++---------- 1 file changed, 462 insertions(+), 532 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift index 9dfafb5ac..a877535c7 100644 --- a/Tests/GRDBTests/ValueObservationCombineTests.swift +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -20,55 +20,45 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - struct T1: TableRecord { } struct T2: TableRecord { } let observation1 = T1.observationForCount() let observation2 = T2.observationForCount() let observation = ValueObservation.combine(observation1, observation2) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1 in - values.append([v0, v1]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0], - [1, 0], - [1, 1], - [2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0], + [1, 0], + [1, 1], + [2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1] }, expectedValues) } func testCombine3() throws { @@ -81,11 +71,6 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 5 - struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } @@ -93,56 +78,51 @@ class ValueObservationCombineTests: GRDBTestCase { let observation2 = T2.observationForCount() let observation3 = T3.observationForCount() let observation = ValueObservation.combine(observation1, observation2, observation3) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1, v2 in - values.append([v0, v1, v2]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0, 0], - [1, 0, 0], - [1, 1, 0], - [1, 1, 1], - [2, 2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0, 0], + [1, 0, 0], + [1, 1, 0], + [1, 1, 1], + [2, 2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1, $2] }, expectedValues) } func testCombine4() throws { @@ -156,11 +136,6 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 6 - struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } @@ -170,67 +145,62 @@ class ValueObservationCombineTests: GRDBTestCase { let observation3 = T3.observationForCount() let observation4 = T4.observationForCount() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1, v2, v3 in - values.append([v0, v1, v2, v3]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0, 0, 0], - [1, 0, 0, 0], - [1, 1, 0, 0], - [1, 1, 1, 0], - [1, 1, 1, 1], - [2, 2, 2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0, 0, 0], + [1, 0, 0, 0], + [1, 1, 0, 0], + [1, 1, 1, 0], + [1, 1, 1, 1], + [2, 2, 2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1, $2, $3] }, expectedValues) } func testCombine5() throws { @@ -245,11 +215,6 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 7 - struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } @@ -261,78 +226,73 @@ class ValueObservationCombineTests: GRDBTestCase { let observation4 = T4.observationForCount() let observation5 = T5.observationForCount() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1, v2, v3, v4 in - values.append([v0, v1, v2, v3, v4]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0, 0, 0, 0], - [1, 0, 0, 0, 0], - [1, 1, 0, 0, 0], - [1, 1, 1, 0, 0], - [1, 1, 1, 1, 0], - [1, 1, 1, 1, 1], - [2, 2, 2, 2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [1, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [2, 2, 2, 2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1, $2, $3, $4] }, expectedValues) } func testCombine6() throws { @@ -348,11 +308,6 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 8 - struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } @@ -366,89 +321,84 @@ class ValueObservationCombineTests: GRDBTestCase { let observation5 = T5.observationForCount() let observation6 = T6.observationForCount() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1, v2, v3, v4, v5 in - values.append([v0, v1, v2, v3, v4, v5]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t6") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "DELETE FROM t6") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0], - [1, 1, 1, 1, 0, 0], - [1, 1, 1, 1, 1, 0], - [1, 1, 1, 1, 1, 1], - [2, 2, 2, 2, 2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t6") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "DELETE FROM t6") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1, $2, $3, $4, $5] }, expectedValues) } func testCombine7() throws { @@ -465,11 +415,6 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 9 - struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } @@ -485,100 +430,95 @@ class ValueObservationCombineTests: GRDBTestCase { let observation6 = T6.observationForCount() let observation7 = T7.observationForCount() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1, v2, v3, v4, v5, v6 in - values.append([v0, v1, v2, v3, v4, v5, v6]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t6") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t7") - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "DELETE FROM t6") - try db.execute(sql: "DELETE FROM t7") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0], - [1, 1, 1, 1, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0], - [1, 1, 1, 1, 1, 1, 0], - [1, 1, 1, 1, 1, 1, 1], - [2, 2, 2, 2, 2, 2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t6") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t7") + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "DELETE FROM t6") + try db.execute(sql: "DELETE FROM t7") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 2, 2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1, $2, $3, $4, $5, $6] }, expectedValues) } func testCombine8() throws { @@ -596,11 +536,6 @@ class ValueObservationCombineTests: GRDBTestCase { """) } - var values: [[Int]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 10 - struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } @@ -618,111 +553,106 @@ class ValueObservationCombineTests: GRDBTestCase { let observation7 = T7.observationForCount() let observation8 = T8.observationForCount() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7, observation8) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { v0, v1, v2, v3, v4, v5, v6, v7 in - values.append([v0, v1, v2, v3, v4, v5, v6, v7]) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t6") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t7") - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t8") - try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "DELETE FROM t1") - try db.execute(sql: "DELETE FROM t2") - try db.execute(sql: "DELETE FROM t3") - try db.execute(sql: "DELETE FROM t4") - try db.execute(sql: "DELETE FROM t5") - try db.execute(sql: "DELETE FROM t6") - try db.execute(sql: "DELETE FROM t7") - try db.execute(sql: "DELETE FROM t8") - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") - } - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(values, [ - [0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0, 0], - [1, 1, 1, 1, 1, 1, 0, 0], - [1, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 1, 1, 1, 1, 1, 1], - [2, 2, 2, 2, 2, 2, 2, 2]]) + let recorder = observation.record(in: dbQueue) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t6") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t7") + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t8") + try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "DELETE FROM t1") + try db.execute(sql: "DELETE FROM t2") + try db.execute(sql: "DELETE FROM t3") + try db.execute(sql: "DELETE FROM t4") + try db.execute(sql: "DELETE FROM t5") + try db.execute(sql: "DELETE FROM t6") + try db.execute(sql: "DELETE FROM t7") + try db.execute(sql: "DELETE FROM t8") + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t2 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t3 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t4 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t5 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t6 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t7 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t8 DEFAULT VALUES") + } + + let expectedValues = [ + [0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 2, 2, 2, 2]] + let values = try wait(for: recorder.next(expectedValues.count), timeout: 0.5) + XCTAssertEqual(values.map { [$0, $1, $2, $3, $4, $5, $6, $7] }, expectedValues) } func testHeterogeneusCombine2() throws { From 98d381ed67b6df8b9b4541e6e1d0bb8500192c6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Mar 2020 10:27:10 +0100 Subject: [PATCH 25/44] Cleanup --- .../ValueObservationCountTests.swift | 2 +- ...rvationDatabaseValueConvertibleTests.swift | 8 +- .../ValueObservationFetchTests.swift | 4 +- .../GRDBTests/ValueObservationMapTests.swift | 2 +- ...bservationQueryInterfaceRequestTests.swift | 4 +- .../ValueObservationReadonlyTests.swift | 4 +- .../ValueObservationRecordTests.swift | 6 +- .../GRDBTests/ValueObservationRecorder.swift | 36 ++++- .../ValueObservationRecorderTests.swift | 144 +++++++++--------- .../GRDBTests/ValueObservationRowTests.swift | 10 +- .../ValueObservationSchedulingTests.swift | 12 +- 11 files changed, 127 insertions(+), 105 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 810403f1e..2a0d8027b 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -36,7 +36,7 @@ class ValueObservationCountTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 4d2fa844a..f2ec8deed 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -54,7 +54,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values.map { $0.map(\.rawValue) }, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -112,7 +112,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values.map { $0.map(\.rawValue) }, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -162,7 +162,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values.map { $0.map { $0?.rawValue }}, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -220,7 +220,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values.map { $0.map(\.rawValue)}, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index a8fe8ccf7..c2c605393 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -38,7 +38,7 @@ class ValueObservationFetchTests: GRDBTestCase { .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -80,7 +80,7 @@ class ValueObservationFetchTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index 981cd7cd8..dbc5f405f 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -29,7 +29,7 @@ class ValueObservationMapTests: GRDBTestCase { .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index fad8095a1..415be9fa8 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -125,7 +125,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -185,7 +185,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift index 4a893f0ad..9620ae6ae 100644 --- a/Tests/GRDBTests/ValueObservationReadonlyTests.swift +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -26,7 +26,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -96,7 +96,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { let expectedValues = [0, 1] let values = try wait(for: recorder.next(2), timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index e29dbf206..397a97290 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -49,7 +49,7 @@ class ValueObservationRecordTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -97,7 +97,7 @@ class ValueObservationRecordTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -145,7 +145,7 @@ class ValueObservationRecordTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index c5a4d654a..44021b924 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -248,20 +248,43 @@ extension XCTestCase { return try valueObservationExpectation.get() } - /// See testAssertValueObservationRecordingMatch() + /// This test checks the fundamental promise of ValueObservation by + /// comparing recorded values with expected values. + /// + /// Recorded values match the expected values if and only if: + /// + /// - The last recorded value is the last expected value + /// - Recorded values are in the same order as expected values + /// + /// However, both missing and repeated values are allowed - with the only + /// exception of the last expected value which can not be missed. + /// + /// For example, if the expected values are [0, 1], then the following + /// recorded values match: + /// + /// - `[0, 1]` (identical values) + /// - `[1]` (missing value but the last one) + /// - `[0, 0, 1, 1]` (repeated value) + /// + /// However the following recorded values don't match, and fail the test: + /// + /// - `[1, 0]` (wrong order) + /// - `[0]` (missing last value) + /// - `[]` (missing last value) + /// - `[0, 1, 2]` (unexpected value) + /// - `[1, 0, 1]` (unexpected value) public func assertValueObservationRecordingMatch( recorded recordedValues: [Value], expected expectedValues: [Value], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) - throws where Value: Equatable { - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: recordedValues, expected: expectedValues, - // Last value can't be missed, this is the most important of all! + // Last value can't be missed allowMissingLastValue: false, message(), file: file, line: line) } @@ -273,7 +296,6 @@ extension XCTestCase { _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) - throws where R: BidirectionalCollection, E: BidirectionalCollection, @@ -290,7 +312,7 @@ extension XCTestCase { let recordedSuffix = recordedValues.reversed().prefix(while: { $0 == value }) let expectedSuffix = expectedValues.reversed().prefix(while: { $0 == value }) if !allowMissingLastValue { - // Both missing and duplicated values are allowed in the recorded values. + // Both missing and repeated values are allowed in the recorded values. // This is because of asynchronous DatabasePool observations. if recordedSuffix.isEmpty { XCTFail("missing expected value \(value) - \(message())", file: file, line: line) @@ -299,7 +321,7 @@ extension XCTestCase { let remainingRecordedValues = recordedValues.prefix(recordedValues.count - recordedSuffix.count) let remainingExpectedValues = expectedValues.prefix(expectedValues.count - expectedSuffix.count) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: remainingRecordedValues, expected: remainingExpectedValues, // Other values can be missed diff --git a/Tests/GRDBTests/ValueObservationRecorderTests.swift b/Tests/GRDBTests/ValueObservationRecorderTests.swift index d7e1d1075..4f3bc843b 100644 --- a/Tests/GRDBTests/ValueObservationRecorderTests.swift +++ b/Tests/GRDBTests/ValueObservationRecorderTests.swift @@ -592,114 +592,114 @@ class ValueObservationRecorderTests: FailureTestCase { // MARK: - assertValueObservationRecordingMatch - func testAssertValueObservationRecordingMatch() throws { + func testAssertValueObservationRecordingMatch() { do { let expected = [3] - try assertValueObservationRecordingMatch(recorded: [3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) - try assertFailure("failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [], expected: expected) + assertValueObservationRecordingMatch(recorded: [3], expected: expected) + assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + assertFailure("failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [2]", "failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + assertFailure("failed - unexpected recorded prefix [2]", "failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [2], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [2]") { - try assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [2]") { + assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) } } do { let expected = [2, 3] - try assertValueObservationRecordingMatch(recorded: [3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [2, 2, 3, 3], expected: expected) - try assertFailure("failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [], expected: expected) + assertValueObservationRecordingMatch(recorded: [3], expected: expected) + assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [2, 2, 3, 3], expected: expected) + assertFailure("failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [], expected: expected) } - try assertFailure("failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + assertFailure("failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [2], expected: expected) } - try assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") { - try assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected) + assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") { + assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [1]") { - try assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [1]") { + assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [1]") { - try assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [1]") { + assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) } } do { let expected = [3, 3] - try assertValueObservationRecordingMatch(recorded: [3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected) - try assertFailure("failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [], expected: expected) + assertValueObservationRecordingMatch(recorded: [3], expected: expected) + assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected) + assertFailure("failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [], expected: expected) } - try assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [2]") { - try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [2]") { + assertValueObservationRecordingMatch(recorded: [2], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [2]") { - try assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [2]") { + assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [2, 2]") { - try assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [2, 2]") { + assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [1, 2]") { - try assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [1, 2]") { + assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) } } do { let expected = [1, 2, 2, 3] - try assertValueObservationRecordingMatch(recorded: [3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 3, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 1, 3, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 2, 2, 3], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) - try assertFailure("failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [], expected: expected) + assertValueObservationRecordingMatch(recorded: [3], expected: expected) + assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 3, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 1, 3, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 2, 2, 3], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected) + assertFailure("failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [], expected: expected) } - try assertFailure("failed - missing expected value 3") { - try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + assertFailure("failed - missing expected value 3") { + assertValueObservationRecordingMatch(recorded: [2], expected: expected) } - try assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") { - try assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected) + assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") { + assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [2]") { - try assertValueObservationRecordingMatch(recorded: [2, 1, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [2]") { + assertValueObservationRecordingMatch(recorded: [2, 1, 3], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [0]") { - try assertValueObservationRecordingMatch(recorded: [0, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [0]") { + assertValueObservationRecordingMatch(recorded: [0, 3], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [0]") { - try assertValueObservationRecordingMatch(recorded: [0, 1, 2, 3], expected: expected) + assertFailure("failed - unexpected recorded prefix [0]") { + assertValueObservationRecordingMatch(recorded: [0, 1, 2, 3], expected: expected) } } do { let expected = [1, 2, 1] - try assertValueObservationRecordingMatch(recorded: [1], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 1], expected: expected) - try assertValueObservationRecordingMatch(recorded: [2, 1], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 2, 1], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 1, 2, 1], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 2, 1, 1], expected: expected) - try assertValueObservationRecordingMatch(recorded: [1, 2, 2, 1], expected: expected) - try assertFailure("failed - missing expected value 1") { - try assertValueObservationRecordingMatch(recorded: [], expected: expected) + assertValueObservationRecordingMatch(recorded: [1], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 1], expected: expected) + assertValueObservationRecordingMatch(recorded: [2, 1], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 2, 1], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 1, 2, 1], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 2, 1, 1], expected: expected) + assertValueObservationRecordingMatch(recorded: [1, 2, 2, 1], expected: expected) + assertFailure("failed - missing expected value 1") { + assertValueObservationRecordingMatch(recorded: [], expected: expected) } - try assertFailure("failed - missing expected value 1") { - try assertValueObservationRecordingMatch(recorded: [2], expected: expected) + assertFailure("failed - missing expected value 1") { + assertValueObservationRecordingMatch(recorded: [2], expected: expected) } - try assertFailure("failed - missing expected value 1") { - try assertValueObservationRecordingMatch(recorded: [1, 2], expected: expected) + assertFailure("failed - missing expected value 1") { + assertValueObservationRecordingMatch(recorded: [1, 2], expected: expected) } - try assertFailure("failed - unexpected recorded prefix [0]") { - try assertValueObservationRecordingMatch(recorded: [0, 1], expected: expected) + assertFailure("failed - unexpected recorded prefix [0]") { + assertValueObservationRecordingMatch(recorded: [0, 1], expected: expected) } } } diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index 7f356cc86..52b463952 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -37,7 +37,7 @@ class ValueObservationRowTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -85,7 +85,7 @@ class ValueObservationRowTests: GRDBTestCase { .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -123,7 +123,7 @@ class ValueObservationRowTests: GRDBTestCase { .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -171,7 +171,7 @@ class ValueObservationRowTests: GRDBTestCase { .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") @@ -218,7 +218,7 @@ class ValueObservationRowTests: GRDBTestCase { .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) .inverted, timeout: 0.5) - try assertValueObservationRecordingMatch( + assertValueObservationRecordingMatch( recorded: values, expected: expectedValues, "\(type(of: writer)), \(observation.scheduling)") diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index e0fe56bad..e4c15d50a 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -60,8 +60,8 @@ class ValueObservationSchedulingTests: GRDBTestCase { var counts: [Int] = [] let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 + notificationExpectation.expectedFulfillmentCount = 4 + notificationExpectation.isInverted = true let key = DispatchSpecificKey<()>() DispatchQueue.main.setSpecific(key: key, value: ()) @@ -85,8 +85,8 @@ class ValueObservationSchedulingTests: GRDBTestCase { } withExtendedLifetime(observer) { - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + waitForExpectations(timeout: 0.5, handler: nil) + assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1]) } } @@ -174,8 +174,8 @@ class ValueObservationSchedulingTests: GRDBTestCase { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + waitForExpectations(timeout: 0.5, handler: nil) + assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1]) } } From 7a583e02e8e2ab21d54aa36ce9b8f73d54583faf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Mar 2020 13:31:05 +0100 Subject: [PATCH 26/44] Refactor ValueObservation tests around a common pattern --- .../ValueObservationCountTests.swift | 63 ++--- ...rvationDatabaseValueConvertibleTests.swift | 228 ++++----------- .../ValueObservationFetchTests.swift | 92 ++---- .../GRDBTests/ValueObservationMapTests.swift | 53 +--- ...bservationQueryInterfaceRequestTests.swift | 124 +++----- .../ValueObservationReadonlyTests.swift | 176 ++++-------- .../ValueObservationRecordTests.swift | 172 ++++------- .../GRDBTests/ValueObservationRecorder.swift | 111 ++++++++ .../GRDBTests/ValueObservationRowTests.swift | 267 +++++------------- 9 files changed, 436 insertions(+), 850 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 2a0d8027b..b492b6f47 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -12,55 +12,30 @@ import XCTest class ValueObservationCountTests: GRDBTestCase { func testCount() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 - try db.execute(sql: "UPDATE t SET id = id") // = - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "DELETE FROM t WHERE id = 1") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1 - } - - let expectedValues = [0, 1, 2, 3, 2] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - struct T: TableRecord { } let observations = [ T.all().observationForCount(), T.observationForCount()] - for var observation in observations { - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + for observation in observations { + try assertValueObservation( + observation, + records: [0, 1, 2, 3, 2], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "UPDATE t SET id = id") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "DELETE FROM t WHERE id = 1") + return .commit + } + try db.execute(sql: "DELETE FROM t WHERE id = 2") + }) } } } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index f2ec8deed..3d1cce461 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -27,62 +27,44 @@ private struct Name: DatabaseValueConvertible, Equatable { class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { func testAll() throws { - func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 + try assertValueObservation( + SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll(), + records: [ + [], + [Name(rawValue: "foo")], + [Name(rawValue: "foo"), Name(rawValue: "bar")], + [Name(rawValue: "bar")]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") try db.execute(sql: "DELETE FROM t WHERE id = 3") return .commit } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - let expectedValues = [ - [], - ["foo"], - ["foo", "bar"], - ["bar"]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values.map { $0.map(\.rawValue) }, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) } func testOne() throws { - func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in + try assertValueObservation( + SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst(), + records: [ + nil, + Name(rawValue: "foo"), + Name(rawValue: "bar"), + nil, + Name(rawValue: "baz"), + nil, + Name(rawValue: "qux")], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") try db.inTransaction { @@ -97,100 +79,48 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t") try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") try db.execute(sql: "UPDATE t SET name = 'qux'") - } - - let expectedValues = [ - nil, - "foo", - "bar", - nil, - "baz", - nil, - "qux"] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values.map { $0.map(\.rawValue) }, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }) } func testAllOptional() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 + try assertValueObservation( + SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll(), + records: [ + [], + [Name(rawValue: "foo")], + [Name(rawValue: "foo"), nil], + [nil]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, NULL)") try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") try db.execute(sql: "DELETE FROM t WHERE id = 3") return .commit } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - let expectedValues = [ - [], - ["foo"], - ["foo", nil], - [nil]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values.map { $0.map { $0?.rawValue }}, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) } func testOneOptional() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in + try assertValueObservation( + SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst(), + records: [ + nil, + Name(rawValue: "foo"), + Name(rawValue: "bar"), + nil, + Name(rawValue: "baz"), + nil, + Name(rawValue: "qux")], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") try db.inTransaction { @@ -205,41 +135,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t") try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") try db.execute(sql: "UPDATE t SET name = 'qux'") - } - - let expectedValues = [ - nil, - "foo", - "bar", - nil, - "baz", - nil, - "qux"] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values.map { $0.map(\.rawValue)}, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }) } func testViewOptimization() throws { diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index c2c605393..ca8de09de 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -21,86 +21,34 @@ class ValueObservationFetchTests: GRDBTestCase { } func testFetch() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in + try assertValueObservation( + ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }), + records: [0, 1, 1, 2], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") try db.execute(sql: "UPDATE t SET id = id") try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - let expectedValues = [0, 1, 1, 2] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }) } func testRemoveDuplicated() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in + try assertValueObservation( + ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }).removeDuplicates(), + records: [0, 1, 2], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") try db.execute(sql: "UPDATE t SET id = id") try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - let expectedValues = [0, 1, 2] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }).removeDuplicates() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }) } } diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index dbc5f405f..9b8822be4 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -12,47 +12,22 @@ import XCTest class ValueObservationMapTests: GRDBTestCase { func testMap() throws { - func test(writer: DatabaseWriter, observation: ValueObservation, String>>) throws { - // We need something to change - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let recorder = observation.record(in: writer) - - try writer.writeWithoutTransaction { db in + let valueObservation = ValueObservation + .tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! + }) + .map { "\($0)" } + + try assertValueObservation( + valueObservation, + records: ["0", "1", "2"], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - let expectedValues = ["0", "1", "2"] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation - .tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - .map { "\($0)" } - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }) } func testMapPreservesConfiguration() { diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 415be9fa8..006a2d1cc 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -28,29 +28,28 @@ private struct ParentInfo: FetchableRecord, Decodable, Equatable { } class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { db in - try db.create(table: "parent") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text) - } - try db.create(table: "child") { t in - t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent", onDelete: .cascade) - t.column("name", .text) - } - try db.execute(sql: """ + private func setup(_ db: Database) throws { + try db.create(table: "parent") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.create(table: "child") { t in + t.autoIncrementedPrimaryKey("id") + t.column("parentId", .integer).references("parent", onDelete: .cascade) + t.column("name", .text) + } + try db.execute(sql: """ INSERT INTO parent (id, name) VALUES (1, 'foo'); INSERT INTO parent (id, name) VALUES (2, 'bar'); INSERT INTO child (id, parentId, name) VALUES (1, 1, 'fooA'); INSERT INTO child (id, parentId, name) VALUES (2, 1, 'fooB'); INSERT INTO child (id, parentId, name) VALUES (3, 2, 'barA'); """) - } } func testOneRowWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() + try dbQueue.write(setup) let request = Parent .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() @@ -74,6 +73,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { func testAllRowsWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() + try dbQueue.write(setup) let request = Parent .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() @@ -103,13 +103,14 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } func testOneRecordWithPrefetchedRows() throws { - func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "DELETE FROM child") - } - - let expectedValues = [ + let request = Parent + .including(all: Parent.children.orderByPrimaryKey()) + .orderByPrimaryKey() + .asRequest(of: ParentInfo.self) + + try assertValueObservation( + request.observationForFirst(), + records: [ ParentInfo( parent: Parent(id: 1, name: "foo"), children: [ @@ -119,45 +120,22 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { ParentInfo( parent: Parent(id: 1, name: "foo"), children: []), - ] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: ParentInfo.self) - var observation = request.observationForFirst() - observation.scheduling = scheduling - - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + ], + setup: setup, + recordedUpdates: { db in + try db.execute(sql: "DELETE FROM child") + }) } func testAllRecordsWithPrefetchedRows() throws { - func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "DELETE FROM child") - } - - let expectedValues = [ + let request = Parent + .including(all: Parent.children.orderByPrimaryKey()) + .orderByPrimaryKey() + .asRequest(of: ParentInfo.self) + + try assertValueObservation( + request.observationForAll(), + records: [ [ ParentInfo( parent: Parent(id: 1, name: "foo"), @@ -179,34 +157,10 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { parent: Parent(id: 2, name: "bar"), children: []), ], - ] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: ParentInfo.self) - var observation = request.observationForAll() - observation.scheduling = scheduling - - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + ], + setup: setup, + recordedUpdates: { db in + try db.execute(sql: "DELETE FROM child") + }) } } diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift index 9620ae6ae..5e6d9f841 100644 --- a/Tests/GRDBTests/ValueObservationReadonlyTests.swift +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -13,151 +13,73 @@ import GRDB class ValueObservationReadonlyTests: GRDBTestCase { func testReadOnlyObservation() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - let expectedValues = [0, 1] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try assertValueObservation( + ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }), + records: [0, 1], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + }) } func testWriteObservationFailsByDefaultWithErrorHandling() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - let recorder = observation.record(in: writer) - - let (values, error) = try wait(for: recorder.failure(), timeout: 0.5) - XCTAssert(values.isEmpty) - do { - throw error - } catch let error as DatabaseError { + try assertValueObservation( + ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + return 0 + }), + fails: { (error: DatabaseError, _: DatabaseWriter) in XCTAssertEqual(error.resultCode, .SQLITE_READONLY) XCTAssertEqual(error.message, "attempt to write a readonly database") XCTAssertEqual(error.sql!, "INSERT INTO t DEFAULT VALUES") XCTAssertEqual(error.description, "SQLite error 8 with statement `INSERT INTO t DEFAULT VALUES`: attempt to write a readonly database") - } - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - return 0 - }) - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }, + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }) } func testWriteObservation() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - let expectedValues = [0, 1] - let values = try wait(for: recorder.next(2), timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in + XCTAssert(db.isInsideTransaction, "expected a wrapping transaction") + try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t") + let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")! + try db.execute(sql: "DROP TABLE temp") + return result + }) + observation.requiresWriteAccess = true - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in - XCTAssert(db.isInsideTransaction, "expected a wrapping transaction") - try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t") - let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")! - try db.execute(sql: "DROP TABLE temp") - return result - }) - observation.requiresWriteAccess = true - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + try assertValueObservation( + observation, + records: [0, 1], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + }) } func testWriteObservationIsWrappedInSavepointWithErrorHandling() throws { struct TestError: Error { } + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + throw TestError() + }) + observation.requiresWriteAccess = true - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - let recorder = observation.record(in: writer) - - let (_, error) = try wait(for: recorder.failure(), timeout: 0.5) - do { - throw error - } catch is TestError { + try assertValueObservation( + observation, + fails: { (_: TestError, writer: DatabaseWriter) in let count = try writer.read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } XCTAssertEqual(count, 0) - } - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - throw TestError() - }) - observation.requiresWriteAccess = true - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }, + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }) } } diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index 397a97290..7da7ffbf5 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -24,146 +24,74 @@ extension Player: TableRecord, FetchableRecord { class ValueObservationRecordTests: GRDBTestCase { func testAll() throws { - func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 + try assertValueObservation( + SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll(), + records: [ + [], + [Player(id: 1, name: "foo")], + [Player(id: 1, name: "foo"), Player(id: 2, name: "bar")], + [Player(id: 2, name: "bar")]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") try db.execute(sql: "DELETE FROM t WHERE id = 3") return .commit } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - let expectedValues = [ - [], - [Player(id: 1, name: "foo")], - [Player(id: 1, name: "foo"), Player(id: 2, name: "bar")], - [Player(id: 2, name: "bar")]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) } func testTableRecordStaticAll() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - let expectedValues = [ + try assertValueObservation( + Player.observationForAll(), + records: [ [], [Player(id: 1, name: "foo")], [Player(id: 1, name: "foo"), Player(id: 2, name: "bar")], - [Player(id: 2, name: "bar")]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = Player.observationForAll() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } - } - - func testOne() throws { - func test(writer: DatabaseWriter, observation: ValueObservation.RowDecoder>>) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 + [Player(id: 2, name: "bar")]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") try db.execute(sql: "DELETE FROM t WHERE id = 3") return .commit } - try db.execute(sql: "DELETE FROM t") // -1 - } - - let expectedValues = [ + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) + } + + func testOne() throws { + try assertValueObservation( + SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(), + records: [ nil, Player(id: 1, name: "foo"), Player(id: 2, name: "bar"), - nil] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + nil], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t") + }) } } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 44021b924..468508e08 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -330,6 +330,117 @@ extension XCTestCase { } } +// MARK: - GRDBTestCase + ValueObservationExpectation + +extension GRDBTestCase { + func assertValueObservation( + _ valueObservation: ValueObservation, + records expectedValues: [Reducer.Value], + setup: (Database) throws -> Void, + recordedUpdates: (Database) throws -> Void, + file: StaticString = #file, + line: UInt = #line) + throws + where Reducer.Value: Equatable + { + func testRecordingEqual(writer: DatabaseWriter, observation: ValueObservation) throws { + try writer.write(setup) + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction(recordedUpdates) + let expectation = recorder.next(expectedValues.count) + let values = try wait(for: expectation, timeout: 0.3) + XCTAssertEqual(values, expectedValues, file: file, line: line) + } + + func testRecordingMatch(writer: DatabaseWriter, observation: ValueObservation) throws { + try writer.write(setup) + let recorder = observation.record(in: writer) + try writer.writeWithoutTransaction(recordedUpdates) + let expectation = recorder + .prefix(expectedValues.count + 2 /* pool may perform double initial fetch */) + .inverted + let values = try wait(for: expectation, timeout: 0.3) + assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + file: file, line: line) + } + + do { + var observation = valueObservation + observation.scheduling = .mainQueue + try testRecordingEqual(writer: DatabaseQueue(), observation: observation) + try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) + try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + } + + do { + var observation = valueObservation + observation.scheduling = .async(onQueue: .main) + try testRecordingEqual(writer: DatabaseQueue(), observation: observation) + try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) + if valueObservation.requiresWriteAccess { + try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + } else { + // DatabasePool performs an immediate async fetch and may miss initial changes + try testRecordingMatch(writer: makeDatabasePool(), observation: observation) + } + } + + do { + var observation = valueObservation + observation.scheduling = .unsafe + try testRecordingEqual(writer: DatabaseQueue(), observation: observation) + try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) + try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + } + } + + func assertValueObservation( + _ valueObservation: ValueObservation, + fails testFailure: (Failure, DatabaseWriter) throws -> Void, + setup: (Database) throws -> Void, + file: StaticString = #file, + line: UInt = #line) + throws + { + func test(writer: DatabaseWriter, observation: ValueObservation) throws { + try writer.write(setup) + let recorder = observation.record(in: writer) + let (_, error) = try wait(for: recorder.failure(), timeout: 0.3) + if let error = error as? Failure { + try testFailure(error, writer) + } else { + throw error + } + } + + do { + var observation = valueObservation + observation.scheduling = .mainQueue + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } + + do { + var observation = valueObservation + observation.scheduling = .async(onQueue: .main) + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } + + do { + var observation = valueObservation + observation.scheduling = .unsafe + try test(writer: DatabaseQueue(), observation: observation) + try test(writer: makeDatabaseQueue(), observation: observation) + try test(writer: makeDatabasePool(), observation: observation) + } + } +} + // MARK: - ValueObservationExpectations public enum ValueObservationExpectations { } diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index 52b463952..508f3d36f 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -12,143 +12,74 @@ import XCTest class ValueObservationRowTests: GRDBTestCase { func testAll() throws { - func test(writer: DatabaseWriter, observation: ValueObservation) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - let expectedValues: [[Row]] = [ + try assertValueObservation( + SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll(), + records: [ [], [["id":1, "name":"foo"]], [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } - } - - func testOne() throws { - func test(writer: DatabaseWriter, observation: ValueObservation) throws { - try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 + [["id":2, "name":"bar"]]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") try db.execute(sql: "DELETE FROM t WHERE id = 3") return .commit } - try db.execute(sql: "DELETE FROM t") // -1 - } - - let expectedValues: [Row?] = [ + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) + } + + func testOne() throws { + try assertValueObservation( + SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(), + records: [ nil, ["id":1, "name":"foo"], ["id":2, "name":"bar"], - nil] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - var observation = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst() - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + nil], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t") + }) } func testFTS4Observation() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { try $0.create(virtualTable: "ft_documents", using: FTS4()) } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"]) - } - - let expectedValues: [[Row]] = [ + try assertValueObservation( + SQLRequest(sql: "SELECT * FROM ft_documents").observationForAll(), + records: [ [], - [["content":"foo"]]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - let request = SQLRequest(sql: "SELECT * FROM ft_documents") - var observation = ValueObservation.tracking(value: request.fetchAll) - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + [["content":"foo"]]], + setup: { db in + try db.create(virtualTable: "ft_documents", using: FTS4()) + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"]) + }) } func testSynchronizedFTS4Observation() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { db in + try assertValueObservation( + SQLRequest(sql: "SELECT * FROM ft_documents").observationForAll(), + records: [ + [], + [["content":"foo"]]], + setup: { db in try db.create(table: "documents") { t in t.column("id", .integer).primaryKey() t.column("content", .text) @@ -157,91 +88,37 @@ class ValueObservationRowTests: GRDBTestCase { t.synchronize(withTable: "documents") t.column("content") } - } - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction { db in + }, + recordedUpdates: { db in try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) - } - - let expectedValues: [[Row]] = [ - [], - [["content":"foo"]]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - let request = SQLRequest(sql: "SELECT * FROM ft_documents") - var observation = ValueObservation.tracking(value: request.fetchAll) - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }) } func testJoinedFTS4Observation() throws { - func test(writer: DatabaseWriter, observation: ValueObservation>) throws { - try writer.write { db in + try assertValueObservation( + SQLRequest(sql: """ + SELECT document.* FROM document + JOIN ft_document ON ft_document.rowid = document.id + WHERE ft_document MATCH 'foo' + """) + .observationForAll(), + records: [ + [], + [["id":1]]], + setup: { db in try db.create(table: "document") { t in t.autoIncrementedPrimaryKey("id") } try db.create(virtualTable: "ft_document", using: FTS4()) { t in t.column("content") } - } - let recorder = observation.record(in: writer) - try writer.write { db in - try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1]) - try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"]) - } - - let expectedValues: [[Row]] = [ - [], - [["id":1]]] - let values = try wait( - for: recorder - .prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */) - .inverted, - timeout: 0.5) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - "\(type(of: writer)), \(observation.scheduling)") - } - - let schedulings: [ValueObservationScheduling] = [ - .mainQueue, - .async(onQueue: .main), - .unsafe - ] - - for scheduling in schedulings { - let request = SQLRequest(sql: """ - SELECT document.* FROM document - JOIN ft_document ON ft_document.rowid = document.id - WHERE ft_document MATCH 'foo' - """) - var observation = ValueObservation.tracking(value: request.fetchAll) - observation.scheduling = scheduling - - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) - } + }, + recordedUpdates: { db in + try db.inTransaction { + try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1]) + try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"]) + return .commit + } + }) } } From e824c70e7d33e4284be0a908634e4ce97e0957c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Mar 2020 13:46:34 +0100 Subject: [PATCH 27/44] Fix SQLCipher tests --- .../GRDBTests.xcodeproj/project.pbxproj | 18 ++++++++++++++++++ .../GRDBTests.xcodeproj/project.pbxproj | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index ff5bb33f9..c5caf8361 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -395,6 +395,12 @@ 56915794231C0D6A00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915792231C0D6A00E1D237 /* PoolTests.swift */; }; 569BBA31228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 569BBA32228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; + 56C8123A24279584004FBBFF /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123724279584004FBBFF /* FailableTestCase.swift */; }; + 56C8123B24279584004FBBFF /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123724279584004FBBFF /* FailableTestCase.swift */; }; + 56C8123C24279584004FBBFF /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123824279584004FBBFF /* ValueObservationRecorderTests.swift */; }; + 56C8123D24279584004FBBFF /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123824279584004FBBFF /* ValueObservationRecorderTests.swift */; }; + 56C8123E24279584004FBBFF /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123924279584004FBBFF /* ValueObservationRecorder.swift */; }; + 56C8123F24279585004FBBFF /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123924279584004FBBFF /* ValueObservationRecorder.swift */; }; 56DF0027228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0028228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0029228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; @@ -607,6 +613,9 @@ 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; + 56C8123724279584004FBBFF /* FailableTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = ""; }; + 56C8123824279584004FBBFF /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = ""; }; + 56C8123924279584004FBBFF /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = ""; }; 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; @@ -749,6 +758,7 @@ 564A1F6D226B89D5001F64F1 /* DropWhileCursorTests.swift */, 564A1F5E226B89D3001F64F1 /* EncryptionTests.swift */, 564A1FB0226B89DC001F64F1 /* EnumeratedCursorTests.swift */, + 56C8123724279584004FBBFF /* FailableTestCase.swift */, 564A1FDA226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift */, 564A1F8E226B89D9001F64F1 /* FetchableRecordDecodableTests.swift */, 564A1FBC226B89DE001F64F1 /* FetchableRecordTests.swift */, @@ -852,6 +862,8 @@ 564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */, 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, + 56C8123924279584004FBBFF /* ValueObservationRecorder.swift */, + 56C8123824279584004FBBFF /* ValueObservationRecorderTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */, @@ -1099,6 +1111,7 @@ 564A2033226B89E1001F64F1 /* AssociationHasManySQLTests.swift in Sources */, 564A204A226B89E1001F64F1 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 564A207B226B89E1001F64F1 /* FTS5TokenizerTests.swift in Sources */, + 56C8123E24279584004FBBFF /* ValueObservationRecorder.swift in Sources */, 564A202D226B89E1001F64F1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 564A2044226B89E1001F64F1 /* FTS4RecordTests.swift in Sources */, 564A2086226B89E1001F64F1 /* AssociationTableAliasTestsSQLTests.swift in Sources */, @@ -1172,6 +1185,7 @@ 564A200F226B89E1001F64F1 /* StatementArguments+FoundationTests.swift in Sources */, 564A207A226B89E1001F64F1 /* FoundationDateComponentsTests.swift in Sources */, 564A204E226B89E1001F64F1 /* PrimaryKeyInfoTests.swift in Sources */, + 56C8123C24279584004FBBFF /* ValueObservationRecorderTests.swift in Sources */, 564A2085226B89E1001F64F1 /* MutablePersistableRecordTests.swift in Sources */, 564A2037226B89E1001F64F1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 564A201C226B89E1001F64F1 /* DatabaseErrorTests.swift in Sources */, @@ -1218,6 +1232,7 @@ 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C682291D0AC00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, + 56C8123A24279584004FBBFF /* FailableTestCase.swift in Sources */, 564A1FEB226B89E1001F64F1 /* FoundationNSUUIDTests.swift in Sources */, 564A1FFE226B89E1001F64F1 /* FilterCursorTests.swift in Sources */, 564A208A226B89E1001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, @@ -1302,6 +1317,7 @@ 564A20B3226B8E18001F64F1 /* AssociationHasManySQLTests.swift in Sources */, 564A20B4226B8E18001F64F1 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 564A20B5226B8E18001F64F1 /* FTS5TokenizerTests.swift in Sources */, + 56C8123F24279585004FBBFF /* ValueObservationRecorder.swift in Sources */, 564A20B6226B8E18001F64F1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 564A20B7226B8E18001F64F1 /* FTS4RecordTests.swift in Sources */, 564A20B8226B8E18001F64F1 /* AssociationTableAliasTestsSQLTests.swift in Sources */, @@ -1375,6 +1391,7 @@ 564A20F8226B8E18001F64F1 /* StatementArguments+FoundationTests.swift in Sources */, 564A20F9226B8E18001F64F1 /* FoundationDateComponentsTests.swift in Sources */, 564A20FA226B8E18001F64F1 /* PrimaryKeyInfoTests.swift in Sources */, + 56C8123D24279584004FBBFF /* ValueObservationRecorderTests.swift in Sources */, 564A20FB226B8E18001F64F1 /* MutablePersistableRecordTests.swift in Sources */, 564A20FC226B8E18001F64F1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 564A20FD226B8E18001F64F1 /* DatabaseErrorTests.swift in Sources */, @@ -1421,6 +1438,7 @@ 564A2123226B8E18001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2124226B8E18001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C692291D0AC00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, + 56C8123B24279584004FBBFF /* FailableTestCase.swift in Sources */, 564A2125226B8E18001F64F1 /* FoundationNSUUIDTests.swift in Sources */, 564A2126226B8E18001F64F1 /* FilterCursorTests.swift in Sources */, 564A2127226B8E18001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 0c13d2822..9fff6a351 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -397,6 +397,12 @@ 56915791231C0D5100E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578F231C0D5100E1D237 /* PoolTests.swift */; }; 569BBA2E228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 569BBA2F228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; + 56C8123124279549004FBBFF /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8122E24279549004FBBFF /* FailableTestCase.swift */; }; + 56C8123224279549004FBBFF /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8122E24279549004FBBFF /* FailableTestCase.swift */; }; + 56C8123324279549004FBBFF /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */; }; + 56C8123424279549004FBBFF /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */; }; + 56C8123524279549004FBBFF /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123024279549004FBBFF /* ValueObservationRecorderTests.swift */; }; + 56C8123624279549004FBBFF /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C8123024279549004FBBFF /* ValueObservationRecorderTests.swift */; }; 56DF0021228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF0022228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF0023228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; @@ -610,6 +616,9 @@ 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; + 56C8122E24279549004FBBFF /* FailableTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = ""; }; + 56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = ""; }; + 56C8123024279549004FBBFF /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = ""; }; 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; @@ -753,6 +762,7 @@ 564A1F6D226B89D5001F64F1 /* DropWhileCursorTests.swift */, 564A1F5E226B89D3001F64F1 /* EncryptionTests.swift */, 564A1FB0226B89DC001F64F1 /* EnumeratedCursorTests.swift */, + 56C8122E24279549004FBBFF /* FailableTestCase.swift */, 564A1FDA226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift */, 564A1F8E226B89D9001F64F1 /* FetchableRecordDecodableTests.swift */, 564A1FBC226B89DE001F64F1 /* FetchableRecordTests.swift */, @@ -856,6 +866,8 @@ 564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */, 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, + 56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */, + 56C8123024279549004FBBFF /* ValueObservationRecorderTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */, @@ -1162,6 +1174,7 @@ 564A2064226B89E1001F64F1 /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, 564A1FFA226B89E1001F64F1 /* FTS5WrapperTokenizerTests.swift in Sources */, 564A2056226B89E1001F64F1 /* TableRecordTests.swift in Sources */, + 56C8123524279549004FBBFF /* ValueObservationRecorderTests.swift in Sources */, 56915790231C0D5100E1D237 /* PoolTests.swift in Sources */, 564A2042226B89E1001F64F1 /* FTS5TableBuilderTests.swift in Sources */, 564A2089226B89E1001F64F1 /* DatabaseValueConversionErrorTests.swift in Sources */, @@ -1202,6 +1215,7 @@ 5656A805229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 564A2066226B89E1001F64F1 /* DatabaseTimestampTests.swift in Sources */, 564A204B226B89E1001F64F1 /* FoundationNSDataTests.swift in Sources */, + 56C8123324279549004FBBFF /* ValueObservationRecorder.swift in Sources */, 564A2009226B89E1001F64F1 /* AssociationHasOneThroughSQLTests.swift in Sources */, 564A2090226B89E1001F64F1 /* FTS3TokenizerTests.swift in Sources */, 564A2076226B89E1001F64F1 /* DatabaseReaderTests.swift in Sources */, @@ -1224,6 +1238,7 @@ 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C6B2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, + 56C8123124279549004FBBFF /* FailableTestCase.swift in Sources */, 564A1FEB226B89E1001F64F1 /* FoundationNSUUIDTests.swift in Sources */, 564A1FFE226B89E1001F64F1 /* FilterCursorTests.swift in Sources */, 564A208A226B89E1001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, @@ -1365,6 +1380,7 @@ 564A20E8226B8E18001F64F1 /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, 564A20E9226B8E18001F64F1 /* FTS5WrapperTokenizerTests.swift in Sources */, 564A20EA226B8E18001F64F1 /* TableRecordTests.swift in Sources */, + 56C8123624279549004FBBFF /* ValueObservationRecorderTests.swift in Sources */, 56915791231C0D5100E1D237 /* PoolTests.swift in Sources */, 564A20EB226B8E18001F64F1 /* FTS5TableBuilderTests.swift in Sources */, 564A20EC226B8E18001F64F1 /* DatabaseValueConversionErrorTests.swift in Sources */, @@ -1405,6 +1421,7 @@ 5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 564A2110226B8E18001F64F1 /* DatabaseTimestampTests.swift in Sources */, 564A2111226B8E18001F64F1 /* FoundationNSDataTests.swift in Sources */, + 56C8123424279549004FBBFF /* ValueObservationRecorder.swift in Sources */, 564A2112226B8E18001F64F1 /* AssociationHasOneThroughSQLTests.swift in Sources */, 564A2113226B8E18001F64F1 /* FTS3TokenizerTests.swift in Sources */, 564A2114226B8E18001F64F1 /* DatabaseReaderTests.swift in Sources */, @@ -1427,6 +1444,7 @@ 564A2123226B8E18001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2124226B8E18001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C6C2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, + 56C8123224279549004FBBFF /* FailableTestCase.swift in Sources */, 564A2125226B8E18001F64F1 /* FoundationNSUUIDTests.swift in Sources */, 564A2126226B8E18001F64F1 /* FilterCursorTests.swift in Sources */, 564A2127226B8E18001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, From 0c464def7ff06c7a1d6f74e895537f6a3e5ebaec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 23 Mar 2020 18:00:45 +0100 Subject: [PATCH 28/44] Fix documentation --- GRDB/ValueObservation/ValueReducer/ValueReducer.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index f0f8fe98a..b8456f9e3 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -11,7 +11,7 @@ public protocol _ValueReducer { /// Feches database values upon changes in an observed database region. /// /// _ValueReducer semantics require that this method does not depend on - /// the state of the reducer: it must not use *self*. + /// the state of the reducer. func fetch(_ db: Database) throws -> Fetched /// Transforms a fetched value into an eventual observed value. Returns nil From f6da8621457567ae033a924efd71b075e0e575e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 08:51:37 +0100 Subject: [PATCH 29/44] Rewrite ValueObservation documentation --- README.md | 363 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 310 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 5aac07a1b..eb637d530 100644 --- a/README.md +++ b/README.md @@ -5410,7 +5410,8 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: - [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. -- [ValueObservation and DatabaseRegionObservation]: Automated tracking of database requests. +- [ValueObservation]: Track changes of database values. +- [DatabaseRegionObservation]: Tracking transactions that impact a database region. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [GRDBCombine]: Automated tracking of database changes, with [Combine](https://developer.apple.com/documentation/combine). - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). @@ -5477,61 +5478,313 @@ try dbQueue.write { db in ``` -## ValueObservation and DatabaseRegionObservation - -**ValueObservation and DatabaseRegionObservation** are two database observations tools that track changes in database [requests](#requests). - -```swift -// Let's observe all players! -let request = Player.all() -``` - -[ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): - -```swift -let observation = ValueObservation.tracking { db in - try request.fetchAll(db) -} -let observer = observation.start( - in: dbQueue, - onError: { error in - print("fresh players could not be fetched") - }, - onChange: { (players: [Player]) in - let names = players.map { $0.name }.joined(separator: ", ") - print("Fresh players: \(names)") - }) - -try dbQueue.write { db in - try Player(name: "Arthur").insert(db) -} -// Prints "Fresh players: Arthur, ..." -``` - -[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for more advanced use cases :nerd_face:): - -```swift -let observation = DatabaseRegionObservation(tracking: request) -let observer = try observation.start(in: dbQueue) { (db: Database) in - print("Players have changed.") -} - -try dbQueue.write { db in - try Player(name: "Barbara").insert(db) -} -// Prints "Players have changed." -``` - -- [ValueObservation] -- [DatabaseRegionObservation] - - ## ValueObservation -**ValueObservation tracks changes in database [requests](#requests), and notifies fresh values whenever the database changes.** +**ValueObservation tracks changes in database values**. It automatically notifies your application with fresh values whenever changes are committed in the database. -Changes are notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). +Tracked changes include changes performed by the [query interface](#the-query-interface) as well as [raw SQL](#sqlite-api), including indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). +- **[ValueObservation Usage](#valueobservation-usage)** +- [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... + + +### ValueObservation Usage + +1. Make sure that a unique [database connection](#database-connections) is kept open during the whole duration of the observation. + + ValueObservation does not notify changes performed by external connections. + +2. Define a ValueObservation which tracks the values you are interested in. + + ```swift + // An observation of [Player] which tracks all players: + let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) + } + + // The same observation, with short-hand notation: + let observation = ValueObservation.tracking(value: Player.fetchAll) + ``` + + The observation can perform multiple requests, from multiple database tables, and even use raw SQL: + +
+ Example of a more complex ValueObservation + + ```swift + struct HallOfFame { + var totalPlayerCount: Int + var bestPlayers: [Player] + } + + // An observation of HallOfFame + let observation = ValueObservation.tracking { db -> HallOfFame in + let totalPlayerCount = try Player.fetchCount(db) + let bestPlayers = try Player + .order(Column("score").desc) + .limit(10) + .fetchAll(db) + return HallOfFame( + totalPlayerCount: totalPlayerCount, + bestPlayers: bestPlayers) + } + ``` + +
+ +3. Start the observation in order to be notified of changes: + + ```swift + // Start observing the database + let observer = observation.start( + in: dbQueue, // or dbPool + onError: { error in print("players could not be fetched") }, + onChange: { (players: [Player]) in print("fresh players", players) }) + ``` + +4. Stop the observation by deallocating the observer returned by the `start` method above. + +**As a convenience**, the two companion libraries [GRDBCombine] and [RxGRDB] bring Combine and RxSwift support to ValueObservation: + +
+ GRDBCombine example + +```swift +import Combine +import GRDB +import GRDBCombine + +let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) +} + +let cancellable = observation.publisher(in: dbQueue).sink( + receiveCompletion: { completion in ... }, + receiveValue: { (players: [Player]) in + print("fresh players", players) + }) +``` + +
+ +
+ RxGRDB example + +```swift +import GRDB +import RxGRDB +import RxSwift + +let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) +} + +let disposable = observation.rx.changes(in: dbQueue).subscribe( + onNext: { (players: [Player]) in + print("fresh players", players) + }, + onError: { error in ... }) +``` + +
+ +**Generally speaking**: + +- ValueObservation notifies an initial value before the eventual changes. This initial value is notified immediately by default (when the `start` method is called). It can be notified [asynchronously](#valueobservationscheduling). +- ValueObservation schedules changes notifications on the main dispatch queue by default. This can be [configured](#valueobservationscheduling). +- ValueObservation may coalesce subsequent changes into a single notification. This helps GRDB optimize database access. +- ValueObservation may notify consecutive identical values. This happens as rarely as possible, and you can filter undesired duplicates out with the [removeDuplicates()](#valueobservationremoveduplicates) method when needed. + +**ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Application](#demo-application) for a sample code. + +Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation], and the low-level [TransactionObserver Protocol](#transactionobserver-protocol). + + +### ValueObservation Operators + +**Operators** are methods that transform and configure value observations so that they better fit the needs of your application. + +- [ValueObservation.map](#valueobservationmap) +- [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) +- [ValueObservation.combine](#valueobservationcombine) +- [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values. +- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database. + + +#### ValueObservation.map + +The `map` operator transforms the values notified by a ValueObservation. + +For example: + +```swift +// Turn an observation of Player? into an observation of UIImage? +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } + .map { player in player?.image } +``` + +The transformation function does not block any database access. This makes the `map` operator a tool which helps reducing database contention. + + +#### ValueObservation.removeDuplicates + +The `removeDuplicates` operator filters out consecutive equal values. The observed values must adopt the standard Equatable protocol. + +For example: + +```swift +// An observation of distinct Player? +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } + .removeDuplicates() +``` + + +#### ValueObservation.combine + +The `ValueObservation.combine` static method builds a single observation from several (up to eight): + +```swift +// An observation of Int +let playerCountObservation = ValueObservation.tracking { db in + try Player.fetchCount(db) +} +// An observation of [Player] +let bestPlayersObservation = ValueObservation.tracking { db in + try Player + .limit(10) + .order(Column("score").desc) + .fetchAll(db) +} + +// The combined observation of (Int, [Player]) +let observation = ValueObservation.combine( + playerCountObservation, + bestPlayersObservation) +``` + +Combining observations together provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). + +`combine` also exists as an instance method: + +```swift +struct HallOfFame { + var totalPlayerCount: Int + var bestPlayers: [Player] +} + +// An observation of HallOfFame +let observation = playerCountObservation.combine(bestPlayersObservation) { + HallOfFame(totalPlayerCount: $0, bestPlayers: $1) +} +``` + + +> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the ValueObservation `combine` method. This is partially exact, because the reactive operator is unable to guarantee data consistency. If you use a Reactive layer such as [GRDBCombine] or [RxGRDB], make sure you compose observations with `ValueObservation.combine`, and never with the CombineLatest operator. + + +#### ValueObservation.scheduling + +The `scheduling` property lets you control how fresh values are notified: + +- `.mainQueue` (the default): all values are notified on the main queue. + + If the observation starts on the main queue, the initial value is notified right upon subscription, synchronously: + + ```swift + // On main queue + let observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { value in + // On main queue + print("fresh value: \(value)") + }) + // <- Here "fresh value" is already printed. + ``` + + If the observation does not start on the main queue, the initial value is also notified on the main queue, but asynchronously: + + ```swift + // Not on the main queue + let observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { value in + // On main queue + print("fresh value: \(value)") + }) + ``` + + After the initial value has been notified, all subsequent values are notified asynchronously: + + ```swift + try dbQueue.write { db in ... } + // <- Eventually prints "fresh value" on the main queue + ``` + +- `.async(onQueue:)`: all values, including the initial value, are asynchronously notified on the specified queue. + + For example: + + ```swift + // On main queue + var observation = ... + observation.scheduling = .async(onQueue: .main) + let observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { value in + // On main queue + print("fresh value: \(value)") + }) + // <- Eventually prints "fresh value" + ``` + + +#### ValueObservation.requiresWriteAccess + +The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): + +```swift +var observation = ValueObservation.tracking { db in + // write access allowed + ... +} +observation.requiresWriteAccess = true +``` + +When you use a [database pool](#database-pools), this flag has a performance hit. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +--- - **[ValueObservation Usage](#valueobservation-usage)** - [ValueObservation.tracking(value:)](#valueobservationtrackingvalue) @@ -8138,6 +8391,11 @@ This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support). This chapter has been superseded by [App Group Containers]. +#### ValueObservation and DatabaseRegionObservation + +This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation]. + + [Associations]: Documentation/AssociationsBasics.md [Beyond FetchableRecord]: #beyond-fetchablerecord [Codable Records]: #codable-records @@ -8161,7 +8419,6 @@ This chapter has been superseded by [App Group Containers]. [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [GRDBCombine]: http://github.com/groue/GRDBCombine [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol -[ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation [DatabaseRegion]: #databaseregion [SQL Interpolation]: Documentation/SQLInterpolation.md [custom SQLite build]: Documentation/CustomSQLiteBuilds.md From 89058f4447f39305db1e124608d0c873a1ec16e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 11:39:21 +0100 Subject: [PATCH 30/44] Rewrite ValueObservation documentation --- README.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index eb637d530..bb257eddb 100644 --- a/README.md +++ b/README.md @@ -5506,7 +5506,7 @@ Tracked changes include changes performed by the [query interface](#the-query-in let observation = ValueObservation.tracking(value: Player.fetchAll) ``` - The observation can perform multiple requests, from multiple database tables, and even use raw SQL: + The observation can perform multiple requests, from multiple database tables, and even use raw SQL.
Example of a more complex ValueObservation @@ -5554,9 +5554,7 @@ import Combine import GRDB import GRDBCombine -let observation = ValueObservation.tracking { db in - try Player.fetchAll(db) -} +let observation = ValueObservation.tracking(value: Player.fetchAll) let cancellable = observation.publisher(in: dbQueue).sink( receiveCompletion: { completion in ... }, @@ -5575,9 +5573,7 @@ import GRDB import RxGRDB import RxSwift -let observation = ValueObservation.tracking { db in - try Player.fetchAll(db) -} +let observation = ValueObservation.tracking(value: Player.fetchAll) let disposable = observation.rx.changes(in: dbQueue).subscribe( onNext: { (players: [Player]) in From 1325a3a6a2979d1cae3a8ac0535e8faafb6c1f3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 11:47:55 +0100 Subject: [PATCH 31/44] Rewrite ValueObservation documentation --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bb257eddb..843a89fc1 100644 --- a/README.md +++ b/README.md @@ -5586,10 +5586,10 @@ let disposable = observation.rx.changes(in: dbQueue).subscribe( **Generally speaking**: -- ValueObservation notifies an initial value before the eventual changes. This initial value is notified immediately by default (when the `start` method is called). It can be notified [asynchronously](#valueobservationscheduling). -- ValueObservation schedules changes notifications on the main dispatch queue by default. This can be [configured](#valueobservationscheduling). -- ValueObservation may coalesce subsequent changes into a single notification. This helps GRDB optimize database access. -- ValueObservation may notify consecutive identical values. This happens as rarely as possible, and you can filter undesired duplicates out with the [removeDuplicates()](#valueobservationremoveduplicates) method when needed. +- ValueObservation notifies an initial value before the eventual changes. This initial value is notified immediately by default (when the `start` method is called). It can be notified [asynchronously](#valueobservationscheduling) if preferred. +- ValueObservation schedules changes notifications on the main thread by default. This can be [configured](#valueobservationscheduling). +- ValueObservation may coalesce subsequent changes into a single notification. +- ValueObservation may notify consecutive identical values. You can filter out the undesired duplicates with the [removeDuplicates()](#valueobservationremoveduplicates) method. **ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Application](#demo-application) for a sample code. From 9562e8eac491cdd5cc4a60c764440afab192622c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 13:01:58 +0100 Subject: [PATCH 32/44] Rewrite ValueObservation documentation --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 843a89fc1..e6bbfc608 100644 --- a/README.md +++ b/README.md @@ -5486,7 +5486,7 @@ Tracked changes include changes performed by the [query interface](#the-query-in - **[ValueObservation Usage](#valueobservation-usage)** - [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... - +- [ValueObservation Performance](#valueobservation-performance) ### ValueObservation Usage @@ -5754,19 +5754,64 @@ observation.requiresWriteAccess = true When you use a [database pool](#database-pools), this flag has a performance hit. +### ValueObservation Performance +This chapter describes some characteristics of ValueObservation, and provides some optimization hints for demanding applications. +**ValueObservation is triggered by database transactions that may modify the tracked value.** +For example, if you track the maximum score of players, transactions that impact the score column of the players database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed: +```swift +let maxScoreRequest = Player.select(max(Column("score")), as: Int.self) +let observation = ValueObservation.tracking(maxScoreRequest.fetchOne) +let observer = observation.start(in: dbQueue, ...) +// triggers the observation +try dbQueue.write(Player(name: "Arthur", score: 1000).insert) +// triggers the observation as well +try dbQueue.write(Player(name: "Barbara", score: 100).insert) +``` +**ValueObservation can create database contention.** In other words, active observations take a toll on the constrained database resources. When triggered by impactful transactions, observations fetch fresh values, and can delay read and write database accesses of other application components. +When needed, you can help GRDB optimize observations and reduce database contention: +1. Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses. +2. Declare upfront the tracked database region, when possible: + + ```swift + // Plain observation + let observation = ValueObservation.tracking(value: Player.fetchAll) + + // Optimized observation + let observation = ValueObservation.tracking(Player.all(), fetch: Player.fetchAll) + ``` + + The `ValueObservation.tracking(_:fetch:)` method is an alternative way to create an observation. Its first argument is one or several requests that define a [database region](#databaseregion). Its second argument is a regular function which fetches the observed value. + + Such an observation is only triggered by transactions that impact the tracked database region. + + It helps reducing database contention because it can refresh the observed value without blocking concurrent database writes. +3. When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: - + ```swift + // Plain observation + let observation = ValueObservation.tracking { db -> MyValue in + let players = try Player.fetchAll(db) + return computeMyValue(players) + } + + // Optimized observation + let observation = ValueObservation + .tracking { db try Player.fetchAll(db) } + .map { players in computeMyValue(players) } + ``` + + The `map` operator helps reducing database contention because it performs its job without blocking concurrent database reads. From 06f6b313680231f23b2085db25aab3ab9449cb86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 13:04:25 +0100 Subject: [PATCH 33/44] Rewrite ValueObservation documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e6bbfc608..a53e5d9d8 100644 --- a/README.md +++ b/README.md @@ -5620,7 +5620,7 @@ let observation = ValueObservation .map { player in player?.image } ``` -The transformation function does not block any database access. This makes the `map` operator a tool which helps reducing database contention. +The transformation function does not block any database access. This makes the `map` operator a tool which helps reducing [database contention](#valueobservation-performance). #### ValueObservation.removeDuplicates From 8d6708a12e56d387c692e9c5526728015afadc5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 13:49:09 +0100 Subject: [PATCH 34/44] Rewrite ValueObservation documentation --- README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a53e5d9d8..a1b232f10 100644 --- a/README.md +++ b/README.md @@ -5778,9 +5778,65 @@ try dbQueue.write(Player(name: "Barbara", score: 100).insert) When needed, you can help GRDB optimize observations and reduce database contention: -1. Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses. +1. Stop observations when possible. + + For example, if a UIViewController needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`, as in the sample code below: + + +
+ UIViewController example + + ```swift + class PlayersViewController: UIViewController { + private var observer: TransactionObserver? + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + // Start observing the database + let observation = ValueObservation.tracking(value: Player.fetchAll) + observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { [weak self] (players: [Player]) in + guard let self = self else { return } + self.updateView(players) + }) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + + // Stop observing the database + observer = nil + } + + private func updateView(_ players: [Player]) { ... } + } + ``` + +
+ +2. Share observations when possible. + + Each call to the `start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing a single observer. + + For example, with RxSwift and RxGRDB, you can use the `share(replay:scope:)` operator: + + ```swift + import GRDB + import RxGRDB + import RxSwift + + let observation = ValueObservation.tracking(value: Player.fetchAll) + let observable = observation.rx + .changes(in: dbQueue) + .share(replay: 1, scope: .whileConnected) + ``` -2. Declare upfront the tracked database region, when possible: +3. Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses. + +4. Declare upfront the tracked database region, when possible: ```swift // Plain observation @@ -5796,7 +5852,7 @@ When needed, you can help GRDB optimize observations and reduce database content It helps reducing database contention because it can refresh the observed value without blocking concurrent database writes. -3. When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: +5. When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: ```swift // Plain observation @@ -5824,7 +5880,6 @@ When needed, you can help GRDB optimize observations and reduce database content - --- - **[ValueObservation Usage](#valueobservation-usage)** From b3fb61858a3b7deaaad12e9a8d66b01909d2d312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 13:52:43 +0100 Subject: [PATCH 35/44] Rewrite ValueObservation documentation --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a1b232f10..29400eb51 100644 --- a/README.md +++ b/README.md @@ -5778,7 +5778,7 @@ try dbQueue.write(Player(name: "Barbara", score: 100).insert) When needed, you can help GRDB optimize observations and reduce database contention: -1. Stop observations when possible. +1. :bulb: **Tip**: Stop observations when possible. For example, if a UIViewController needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`, as in the sample code below: @@ -5817,7 +5817,7 @@ When needed, you can help GRDB optimize observations and reduce database content
-2. Share observations when possible. +2. :bulb: **Tip**: Share observations when possible. Each call to the `start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing a single observer. @@ -5834,9 +5834,9 @@ When needed, you can help GRDB optimize observations and reduce database content .share(replay: 1, scope: .whileConnected) ``` -3. Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses. +3. :bulb: **Tip**: Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses. -4. Declare upfront the tracked database region, when possible: +4. :bulb: **Tip**: Declare upfront the tracked database region, when possible: ```swift // Plain observation @@ -5852,7 +5852,7 @@ When needed, you can help GRDB optimize observations and reduce database content It helps reducing database contention because it can refresh the observed value without blocking concurrent database writes. -5. When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: +5. :bulb: **Tip**: When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: ```swift // Plain observation From cf1360701c5e6f899136a89d786d1cfb6a48c8a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 14:09:45 +0100 Subject: [PATCH 36/44] Rewrite ValueObservation documentation --- README.md | 449 ------------------------------------------------------ 1 file changed, 449 deletions(-) diff --git a/README.md b/README.md index 29400eb51..3140d161c 100644 --- a/README.md +++ b/README.md @@ -5870,455 +5870,6 @@ When needed, you can help GRDB optimize observations and reduce database content The `map` operator helps reducing database contention because it performs its job without blocking concurrent database reads. - - - - - - - - - - ---- - -- **[ValueObservation Usage](#valueobservation-usage)** -- [ValueObservation.tracking(value:)](#valueobservationtrackingvalue) -- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) -- [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) -- [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... -- [ValueObservation Error Handling](#valueobservation-error-handling) -- [ValueObservation Options](#valueobservation-options) - - -### ValueObservation Usage - -Here is a typical UIViewController which observes the database in order to keep its view up-to-date: - -```swift -class PlayerViewController: UIViewController { - @IBOutlet weak var nameLabel: UILabel! - private var observer: TransactionObserver? - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - - // Define a ValueObservation which tracks a player - let observation = ValueObservation.tracking { db in - try Player.fetchOne(db, key: 42) - } - - // Start observing the database - observer = observation.start( - in: dbQueue, - onError: { error in - print("player could not be fetched") - }, - onChange: { [weak self] (player: Player?) in - // Player has been refreshed: update view - guard let self = self else { return } - self.nameLabel.text = player?.name - }) - } - - override func viewWillDisappear(_ animated: Bool) { - super.viewWillDisappear(animated) - - // Stop observing the database - observer = nil - } -} -``` - -By default, all values and errors are notified on the main queue. Views can be updated right from the `onChange` callback. - -An initial fetch is performed as soon as the observation starts: the view is set up and ready when the `viewWillAppear` method returns. - -The observer returned by the `start` method is stored in a property of the view controller. This allows the view controller to control the duration of the observation. When the observer is deallocated, the observation stops. Meanwhile, all transactions that modify the observed player are notified, and the `nameLabel` is kept up-to-date. - -> :bulb: **Tip**: see the [Demo Application] for a sample app that uses ValueObservation. -> -> :bulb: **Tip**: When fetching values is slow, and should never ever block the main queue, opt in for async notifications: -> -> ```swift -> override func viewWillAppear(_ animated: Bool) { -> super.viewWillAppear(animated) -> -> // Define a ValueObservation which tracks a player -> let observation = ValueObservation.tracking { db in -> try Player.fetchOne(db, key: 42) -> } -> -> // Observation is asynchronous -> observation.scheduling = .async(onQueue: .main) -> -> // Start observing the database -> observer = observation.start( -> in: dbQueue, -> onError: { error in -> print("player could not be fetched") -> }, -> onChange: { [weak self] (player: Player?) in -> // Player has been refreshed: update view -> guard let self = self else { return } -> self.activityIndicator.stopAnimating() -> self.nameLabel.text = player?.name -> }) -> -> // Wait for player -> activityIndicator.startAnimating() -> nameLabel.text = nil -> } -> ``` -> -> See [ValueObservation.scheduling](#valueobservationscheduling) for more information. - - -### ValueObservation.tracking(value:) - -In order to observe database values, you will generally define a **ValueObservation** which tracks the value you are interested in, and then start the observation. - -For example: - -```swift -// Track changes in a single player -let observation = ValueObservation.tracking { db in - try Player.fetchOne(db, key: 42) -} - -observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (player: Player?) in - print("Fresh player: \(player)") - }) -``` - -**You can observe several requests and several tables if you need**: all writes that have an impact on the fetched values will trigger the observation, and call the `onChange` function. - -**The observation may notify identical consecutive values.** This is because it will fetch a fresh value whenever a change *could* happen. For example, the observation for the maximum player score will notify a fresh value every time a score is changed, inserted, or deleted, even if the maximum score is unchanged: - -```swift -// Track changes in the maximum player score -// This observation may notify duplicate values -let observation = ValueObservation.tracking { db in - try Player.select(max(Column("score")), as: Int.self).fetchOne(db) -} -``` - -You can filter out those duplicates with the [removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: - -```swift -let observation = ValueObservation - .tracking { db in - try Player.select(max(Column("score")), as: Int.self).fetchOne(db) - } - .removeDuplicates() -``` - - -We will see below other ways to define observations. They all add a little convenience, or optimization. - - -### ValueObservation.tracking(_:fetch:) - -The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue) method seen above. - -The returned observation outputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied. - -It accepts two arguments: - -1. A list of observed requests. -2. A closure that fetches a fresh value whenever one of the observed requests are modified. - -Changes that happen outside of the observed requests are ignored, so make sure you fully cover the database region you want to observe. This is the price you pay for the optimization. - -Let's give a practical example, and observe the "Hall of Fame": - -```swift -struct HallOfFame { - var totalPlayerCount: Int - var bestPlayers: [Player] -} - -extension HallOfFame { - /// Fetch the HallOfFame - static fetch(_ db: Database) throws -> HallOfFame { - let totalPlayerCount = try Player.fetchCount(db) - let bestPlayers = try Player - .order(Column("score").desc) - .limit(10) - .fetchAll(db) - return HallOfFame( - totalPlayerCount: totalPlayerCount, - bestPlayers: bestPlayers) - } -} -``` - -In order to track changes in the Hall of Fame in an optimized way, we see that any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: - -```swift -let observation = ValueObservation.tracking(Player.all(), fetch: { db in - try HallOfFame.fetch(db) -}) -``` - -> :point_up: **Note**: the initial parameter of `ValueObservation.tracking(_:fetch:)` can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. - - -### observationForCount, observationForAll, observationForFirst - -Given a [request](#requests), even a [custom request](#custom-requests), you can observe its number of results, all results, or the first one: - -```swift -request.observationForCount() -request.observationForAll() -request.observationForFirst() -``` - -Those observations are equivalent to the following ones, defined with [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue): - -```swift -ValueObservation.tracking { db in try request.fetchCount(db) } -ValueObservation.tracking { db in try request.fetchAll(db) } -ValueObservation.tracking { db in try request.fetchOne(db) } -``` - -Yet they are **optimized**: - -- They perform a filtering of consecutive identical values, based on raw database values, so that you are not notified of database changes that do not impact the result of the request. -- They can perform better when you use a [database pool](#database-pools), and the fetch is slow. - - -### ValueObservation Transformations - -- [ValueObservation.map](#valueobservationmap) -- [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) -- [ValueObservation.combine(...)](#valueobservationcombine) - - -#### ValueObservation.map - -The `map` method lets you transform the values notified by a ValueObservation. - -For example: - -```swift -// Observe a player's profile image -let observation = ValueObservation - .tracking { db in try Player.fetchOne(db, key: 42) } - .map { player in player?.image } - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (image: UIImage?) in - print("Player picture has changed") - }) -``` - -The transformation closure does not run on the main queue, and does not block any database access. - - -#### ValueObservation.removeDuplicates - -The `removeDuplicates` method filters out the consecutive equal values notified by a ValueObservation. The observed values must adopt the standard Equatable protocol. - -For example: - -```swift -let observation = ValueObservation - .tracking { db in try Player.fetchOne(db, key: 42) } - .removeDuplicates() - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (player: Player) in - print("Player: \(player)") - }) -``` - -> :point_up: **Note**: the observations returned by the [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) methods already perform a similar filtering, based on raw database values. - - -#### ValueObservation.combine(...) - -The `ValueObservation.combine(...)` method builds a single observation from several: - -```swift -// Two base observations -let playerCountObservation = ValueObservation.tracking { db in - try Player.fetchCount(db) -} -let bestPlayersObservation = ValueObservation.tracking { db in - try Player - .limit(10) - .order(Column("score").desc) - .fetchAll(db) -} - -// The combined observation -let observation = ValueObservation.combine( - playerCountObservation, - bestPlayersObservation) - -// Start tracking the hall of fame -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (totalPlayerCount, bestPlayers) in - print(""" - Best players out of \(totalPlayerCount): - \(bestPlayers) - """) - }) -``` - -`combine` also exists as an instance method: - -```swift -struct HallOfFame { - var totalPlayerCount: Int - var bestPlayers: [Player] -} - -let observation = playerCountObservation.combine(bestPlayersObservation) { - HallOfFame(totalPlayerCount: $0, bestPlayers: $1) -} -``` - -You can combine up to eight observations together. They can feed from as many database tables as needed. - -Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). - -> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the ValueObservation `combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [GRDBCombine] or [RxGRDB], make sure you compose observations with `ValueObservation.combine`, not with the CombineLatest operator. - - -### ValueObservation Error Handling - -When you start an observation, the `onError` callback is called whenever fresh values could not be fetched. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)): - -```swift -let observer = observation.start( - in: dbQueue, - onError: { error in - print("fresh value could not be fetched") - }, - onChange: { value in - print("fresh value: \(value)") - }) -``` - -An error does not stop the observation. After an error has been received, subsequent transactions may succeed in notifying fresh values. You may witness such temporary errors when the database becomes temporarily unreachable, for example due to [data protection](#data-protection). - -Depending on the way your application wants to deal with such errors, you may want to tighten your control on the scheduling of database accesses with [DatabaseRegionObservation]. See also the reactive companion libraries [GRDBCombine] and [RxGRDB], which stop observation whenever a ValueObservation error happens. - - -### ValueObservation Options - -Some behaviors of value observations can be configured: - -- [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values. -- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database. - - -#### ValueObservation.scheduling - -The `scheduling` property lets you control how fresh values are notified: - -- `.mainQueue` (the default): all values are notified on the main queue. - - If the observation starts on the main queue, the initial value is notified right upon subscription, synchronously: - - ```swift - // On main queue - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - // On main queue - print("fresh value: \(value)") - }) - // <- Here "fresh value" is already printed. - ``` - - If the observation does not start on the main queue, the initial value is also notified on the main queue, but asynchronously: - - ```swift - // Not on the main queue - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - // On main queue - print("fresh value: \(value)") - }) - ``` - - After the initial value has been notified, all subsequent values are notified asynchronously: - - ```swift - try dbQueue.write { db in ... } - // <- Eventually prints "fresh value" on the main queue - ``` - -- `.async(onQueue:)`: all values, including the initial value, are asynchronously notified on the specified queue. - - For example: - - ```swift - // On main queue - var observation = ... - observation.scheduling = .async(onQueue: .main) - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - // On main queue - print("fresh value: \(value)") - }) - // <- Eventually prints "fresh value" - ``` - -- `unsafe`: values are not all notified on the same dispatch queue. - - The initial value is notified right upon subscription, synchronously, on the dispatch queue which starts the observation. - - ```swift - // On any queue - var observation = ... - observation.scheduling = .unsafe - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - print("fresh value: \(value)") - }) - // <- Here "fresh value" is already printed. - ``` - - After the initial value has been notified, all subsequent values are notified on unspecified queues. - - > :point_up: **Note**: this unsafe mode is intended for third-party libraries that provide their own scheduling engine. - - -#### ValueObservation.requiresWriteAccess - -The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): - -```swift -var observation = ValueObservation.tracking { db in - // write access allowed - ... -} -observation.requiresWriteAccess = true -``` - -When you use a [database pool](#database-pools), don't use this flag unless you really need it. Observations with write access are less efficient because they block all writes for the whole duration of a fetch. - - ## DatabaseRegionObservation **DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** From 78dc7aee15114b981e955f3f02c966798e430576 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 14:35:43 +0100 Subject: [PATCH 37/44] Rewrite ValueObservation documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3140d161c..335ba0cdd 100644 --- a/README.md +++ b/README.md @@ -5484,6 +5484,8 @@ try dbQueue.write { db in Tracked changes include changes performed by the [query interface](#the-query-interface) as well as [raw SQL](#sqlite-api), including indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). +**ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Application](#demo-application) for a sample code. + - **[ValueObservation Usage](#valueobservation-usage)** - [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... - [ValueObservation Performance](#valueobservation-performance) @@ -5591,8 +5593,6 @@ let disposable = observation.rx.changes(in: dbQueue).subscribe( - ValueObservation may coalesce subsequent changes into a single notification. - ValueObservation may notify consecutive identical values. You can filter out the undesired duplicates with the [removeDuplicates()](#valueobservationremoveduplicates) method. -**ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Application](#demo-application) for a sample code. - Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation], and the low-level [TransactionObserver Protocol](#transactionobserver-protocol). From 5210ae83852cc05b26a7cbb40ecb33c8ac75e7ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 14:36:29 +0100 Subject: [PATCH 38/44] Rewrite ValueObservation documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 335ba0cdd..4bfa00c4d 100644 --- a/README.md +++ b/README.md @@ -5486,7 +5486,7 @@ Tracked changes include changes performed by the [query interface](#the-query-in **ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Application](#demo-application) for a sample code. -- **[ValueObservation Usage](#valueobservation-usage)** +- [ValueObservation Usage](#valueobservation-usage) - [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... - [ValueObservation Performance](#valueobservation-performance) From 0963b162e78c70a7d020f38bda4717c1c1bbec86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 14:57:23 +0100 Subject: [PATCH 39/44] Rewrite ValueObservation documentation --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 4bfa00c4d..b3b305f3f 100644 --- a/README.md +++ b/README.md @@ -6233,8 +6233,6 @@ protocol DatabaseRegionConvertible { All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. -Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from optimized observation APIs. See [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) for more information. - ### Support for SQLite Pre-Update Hooks From e8fefc82a1fe2d0e7656dd98890db2bec29f8ee1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 16:29:56 +0100 Subject: [PATCH 40/44] Drop obsolete warning against DatabaseRegionObservation --- README.md | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/README.md b/README.md index b3b305f3f..5527d1ad0 100644 --- a/README.md +++ b/README.md @@ -5918,23 +5918,6 @@ let observer = try observation.start(in: dbQueue) { (db: Database) in ``` -### DatabaseRegionObservation Use Cases - -**There are very few use cases for DatabaseRegionObservation**. - -For example: - -- One needs to write in the database after an impactful transaction. - -- One needs to synchronize the content of the database file with some external resources, like other files, or system sensors like CLRegion monitoring. - -- On iOS, one needs to process a database transaction before the operating system had any opportunity to put the application in the suspended state. - -- One wants to build a [database snapshot](#database-snapshots) with a guaranteed snapshot content. - -Outside of those use cases, it is much likely *wrong* to use a DatabaseRegionObservation. Please check other [Database Observation](#database-changes-observation) options. - - ### DatabaseRegionObservation.extent The `extent` property lets you specify the duration of the observation. See [Observation Extent](#observation-extent) for more details: From 97a7117564bdd7197d488b096d5867c80d30c796 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 16:58:59 +0100 Subject: [PATCH 41/44] Rewrite ValueObservation documentation --- README.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 5527d1ad0..f4b560be0 100644 --- a/README.md +++ b/README.md @@ -5756,23 +5756,15 @@ When you use a [database pool](#database-pools), this flag has a performance hit ### ValueObservation Performance -This chapter describes some characteristics of ValueObservation, and provides some optimization hints for demanding applications. +This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications. + **ValueObservation is triggered by database transactions that may modify the tracked value.** -For example, if you track the maximum score of players, transactions that impact the score column of the players database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed: +For example, if you track the maximum score of players, all transactions that impact the `score` column of the `player` database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed. -```swift -let maxScoreRequest = Player.select(max(Column("score")), as: Int.self) -let observation = ValueObservation.tracking(maxScoreRequest.fetchOne) -let observer = observation.start(in: dbQueue, ...) +You can filter out undesired duplicate notifications with the [removeDuplicates()](#valueobservationremoveduplicates) method. -// triggers the observation -try dbQueue.write(Player(name: "Arthur", score: 1000).insert) - -// triggers the observation as well -try dbQueue.write(Player(name: "Barbara", score: 100).insert) -``` **ValueObservation can create database contention.** In other words, active observations take a toll on the constrained database resources. When triggered by impactful transactions, observations fetch fresh values, and can delay read and write database accesses of other application components. From 6b33e656bedb23b5f749d0491688f445b54fcd4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 17:01:14 +0100 Subject: [PATCH 42/44] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a919c6d58..4a291f1a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#729](https://github.com/groue/GRDB.swift/pull/729): ValueObservation always emits an initial value - [#731](https://github.com/groue/GRDB.swift/pull/731): Hide ValueObservation implementation details - [#732](https://github.com/groue/GRDB.swift/pull/732): Remove ValueObservation.compactMap +- [#736](https://github.com/groue/GRDB.swift/pull/736): Relax ValueObservation Guarantees ## 4.12.0 From 327f07422f251cc587b10f8c4926cba712c4a048 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 22:35:32 +0100 Subject: [PATCH 43/44] Add missing FailableTestCase.swift to custom SQLite tests --- GRDBCustom.xcodeproj/project.pbxproj | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 5f6c9d238..357493f16 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -323,6 +323,8 @@ 567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; + 567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */; }; + 567E420A242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */; }; 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -914,6 +916,7 @@ 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; + 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; @@ -1224,11 +1227,12 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( - 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, + 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */, 5698AC3E1DA2BEBB0056AF8C /* FTS */, 56176CA01EACEE2A000F3F2B /* GRDBCipher */, + 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 56A238231B9C74A90082EB20 /* Migrations */, 569978D31B539038005EBEED /* Private */, 56300B5C1C53C38F005A543B /* QueryInterface */, @@ -2363,6 +2367,7 @@ F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */, F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */, 56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */, + 567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */, 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 5615B286222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, @@ -2703,6 +2708,7 @@ 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */, 56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */, + 567E420A242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */, 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 5615B285222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */, From dfd5dd24781b80e4f22cc9dbd5206c240b659033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Mar 2020 22:55:18 +0100 Subject: [PATCH 44/44] Add missing import for SPM --- GRDB/Core/DatabaseReader.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 683c78399..34436f2bd 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -1,3 +1,4 @@ +import Dispatch #if SWIFT_PACKAGE import CSQLite #elseif GRDBCIPHER