Merge pull request #736 from groue/dev/relax-ValueObservation

Relax ValueObservation Guarantees
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-03-24 22:56:16 +01:00
commit ce6afd680d
37 files changed
+2968 -1914

No files matched your search

+1
View File
@@ -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
+24
View File
@@ -378,6 +378,15 @@
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 */; };
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 +1334,9 @@
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = "<group>"; };
56677C14241D14450050755D /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = "<group>"; };
566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
@@ -1695,6 +1707,7 @@
children = (
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
56677C14241D14450050755D /* FailableTestCase.swift */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
@@ -1822,6 +1835,8 @@
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */,
5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */,
563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */,
56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */,
56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */,
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */,
563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */,
5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */,
@@ -3081,6 +3096,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 +3171,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 +3217,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 */,
@@ -3287,6 +3305,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 +3380,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 +3426,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 */,
@@ -3625,6 +3646,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 +3721,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 +3767,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 */,
+22 -6
View File
@@ -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<T, Error>? = 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 {
@@ -771,6 +771,22 @@ extension DatabasePool: DatabaseReader {
forEachConnection { $0.remove(collation: collation) }
}
// MARK: - Database Observation
public func add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
{
add(
observation: observation,
// DatabasePool supports concurrent reads
prependingConcurrentFetch: !observation.requiresWriteAccess,
onError: onError,
onChange: onChange)
}
// MARK: - Custom FTS5 Tokenizers
#if SQLITE_ENABLE_FTS5
+18 -2
View File
@@ -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
@@ -446,4 +446,20 @@ extension DatabaseQueue {
public func remove(collation: DatabaseCollation) {
writer.sync { $0.remove(collation: collation) }
}
// MARK: - Database Observation
public func add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
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)
}
}
+65 -2
View File
@@ -1,3 +1,4 @@
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
@@ -121,9 +122,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)
@@ -294,6 +295,68 @@ extension DatabaseReader {
}
}
extension DatabaseReader {
// MARK: - Value Observation Support
func addReadOnly<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
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
+4 -53
View File
@@ -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
@@ -114,7 +114,7 @@ extension DatabaseSnapshot {
serializedDatabase.sync { $0.remove(collation: collation) }
}
// MARK: - Value Observation
// MARK: - Database Observation
public func add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
@@ -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) { }
}
+5 -5
View File
@@ -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<RowDecoder._Wrapped> {
try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder.Wrapped> {
try Optional<RowDecoder.Wrapped>.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<RowDecoder._Wrapped>.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
}
}
+50 -24
View File
@@ -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 {
@@ -300,19 +300,23 @@ extension DatabaseWriter {
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
// MARK: - Value Observation
/// Default implementation for the DatabaseReader requirement.
/// :nodoc:
public func add<Reducer: _ValueReducer>(
// MARK: - Database Observation
func add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
prependingConcurrentFetch: Bool,
onError: @escaping (Error) -> Void,
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
// This flag supersedes prependingConcurrentFetch.
let initialFetchSync: Bool
// The queue for other values. Nil for any queue.
let notificationQueue: DispatchQueue?
@@ -323,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:
@@ -351,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
}
@@ -367,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)
@@ -379,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)
}
}
}
@@ -572,4 +586,16 @@ public final class AnyDatabaseWriter: DatabaseWriter {
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
// MARK: - Database Observation
/// :nodoc:
public func add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
{
base.add(observation: observation, onError: onError, onChange: onChange)
}
}
+5 -5
View File
@@ -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<RowDecoder._Wrapped> {
try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder.Wrapped> {
try Optional<RowDecoder.Wrapped>.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<RowDecoder._Wrapped>.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
}
}
+2 -2
View File
@@ -177,9 +177,9 @@ extension ValueObservation where Reducer == Never {
@available(*, unavailable, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.AllOptionalValues<Request.RowDecoder._Wrapped>>
-> ValueObservation<ValueReducers.AllOptionalValues<Request.RowDecoder.Wrapped>>
where Request.RowDecoder: _OptionalProtocol,
Request.RowDecoder._Wrapped: DatabaseValueConvertible
Request.RowDecoder.Wrapped: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForAll() instead")
+13 -6
View File
@@ -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
@@ -97,6 +93,17 @@ extension DispatchQueue {
}
}
extension Result {
func tryMap<T>(_ transform: (Success) throws -> T) -> Result<T, Error> {
switch self {
case let .success(value):
return Result<T, Error> { try transform(value) }
case let .failure(error):
return .failure(error)
}
}
}
extension Sequence {
@inlinable
func count(where predicate: (Element) throws -> Bool) rethrows -> Int {
@@ -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<ValueReducers.AllOptionalValues<RowDecoder._Wrapped>> {
public func observationForAll() -> ValueObservation<ValueReducers.AllOptionalValues<RowDecoder.Wrapped>> {
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<ValueReducers.OneValue<RowDecoder._Wrapped>> {
public func observationForFirst() -> ValueObservation<ValueReducers.OneValue<RowDecoder.Wrapped>> {
ValueObservation(
baseRegion: databaseRegion,
makeReducer: { ValueReducers.OneValue { try DatabaseValue.fetchOne($0, self) } })
+1 -2
View File
@@ -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
+90 -99
View File
@@ -2,24 +2,24 @@ import Foundation
/// Support for ValueObservation.
/// See DatabaseWriter.add(observation:onError:onChange:)
class ValueObserver<Reducer: _ValueReducer>: TransactionObserver {
final class ValueObserver<Reducer: _ValueReducer> {
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
private unowned let writer: DatabaseWriter
private weak var writer: DatabaseWriter?
private let notificationQueue: DispatchQueue?
private let reduceQueue: DispatchQueue
private let onError: (Error) -> Void
private let onChange: (Reducer.Value) -> Void
private var isChanged = false
private var isCancelled = false
init(
requiresWriteAccess: Bool,
@@ -40,32 +40,59 @@ class ValueObserver<Reducer: _ValueReducer>: TransactionObserver {
self.onError = onError
self.onChange = onChange
}
// 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.
}
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 fetchedValue: Reducer.Fetched
if observesSelectedRegion {
(fetchedValue, selectedRegion) = try db.recordingSelectedRegion {
try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
guard let value = reducer.value(fetchedValue) else {
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)
}
}
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 {
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 {
if self.isCancelled { return }
onError(error)
}
} else {
onError(error)
}
}
}
extension ValueObserver: TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
if isCancelled { return false }
return observedRegion.isModified(byEventsOfKind: eventKind)
@@ -80,96 +107,38 @@ class ValueObserver<Reducer: _ValueReducer>: TransactionObserver {
}
func databaseDidCommit(_ db: Database) {
guard let writer = writer else { return }
if isCancelled { return }
guard isChanged else { return }
isChanged = false
// Grab future fetched value
let future: DatabaseFuture<Reducer.Fetched>
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 fetchedValue: DatabaseFuture<Reducer.Fetched>
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)
}
// Concurrent 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.
reduceQueue.async { [weak self] in
guard let self = self else { return }
// any database dispatch queue.
reduceQueue.async {
if self.isCancelled { return }
self.reduce(future: future)
}
}
private func reduce(future: DatabaseFuture<Reducer.Fetched>) {
do {
if let value = try reducer.value(future.wait()) {
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)
self.reduce(fetchedValue: fetchedValue) { result in
do {
try self.send(result.get())
} catch {
self.send(error)
}
}
} catch {
if let queue = notificationQueue {
queue.async { [weak self] in
guard let self = self else { return }
if self.isCancelled { return }
self.onError(error)
}
} else {
onError(error)
}
}
}
@@ -178,6 +147,31 @@ class ValueObserver<Reducer: _ValueReducer>: TransactionObserver {
}
}
extension ValueObserver {
private func reduce(
fetchedValue: DatabaseFuture<Reducer.Fetched>,
completion: @escaping (Result<Reducer.Value, Error>) -> Void)
{
do {
if let value = try reducer.value(fetchedValue.wait()) {
completion(.success(value))
}
} catch {
completion(.failure(error))
}
}
private func recordingSelectedRegionIfNeeded<T>(_ db: Database, _ block: () throws -> T) rethrows -> T {
if observesSelectedRegion {
let result: T
(result, selectedRegion) = try db.recordingSelectedRegion(block)
return result
} else {
return try block()
}
}
}
class ValueObserverToken<Reducer: _ValueReducer>: TransactionObserver {
// Useless junk
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
@@ -193,10 +187,7 @@ class ValueObserverToken<Reducer: _ValueReducer>: TransactionObserver {
self.observer = observer
}
// The most ugly stuff ever
deinit {
observer.cancel()
// TODO: have it not wait for the writer queue
writer?.remove(transactionObserver: observer)
}
}
@@ -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.
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.
+19 -1
View File
@@ -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 */; };
@@ -319,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 */; };
@@ -876,6 +882,8 @@
5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
56677C23241E6EA10050755D /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = "<group>"; };
56677C24241E6EA20050755D /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = "<group>"; };
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
@@ -908,6 +916,7 @@
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
@@ -1218,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 */,
@@ -1331,6 +1341,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 +2355,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 */,
@@ -2354,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 */,
@@ -2416,6 +2430,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 +2696,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 */,
@@ -2692,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 */,
@@ -2754,6 +2771,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 */,
+223 -346
View File
@@ -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,224 +5478,49 @@ 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 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.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](#valueobservation-usage)
- [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ...
- [ValueObservation Performance](#valueobservation-performance)
### 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?
1. Make sure that a unique [database connection](#database-connections) is kept open during the whole duration of the observation.
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
})
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)
}
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:
// The same observation, with short-hand notation:
let observation = ValueObservation.tracking(value: Player.fetchAll)
```
```swift
let observation = ValueObservation
.tracking { db in
try Player.select(max(Column("score")), as: Int.self).fetchOne(db)
The observation can perform multiple requests, from multiple database tables, and even use raw SQL.
<details>
<summary>Example of a more complex ValueObservation</summary>
```swift
struct HallOfFame {
var totalPlayerCount: Int
var bestPlayers: [Player]
}
.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 {
// 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)
@@ -5704,105 +5530,123 @@ extension HallOfFame {
totalPlayerCount: totalPlayerCount,
bestPlayers: bestPlayers)
}
}
```
```
</details>
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) })
```
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:
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:
<details>
<summary>GRDBCombine example</summary>
```swift
let observation = ValueObservation.tracking(Player.all(), fetch: { db in
try HallOfFame.fetch(db)
})
import Combine
import GRDB
import GRDBCombine
let observation = ValueObservation.tracking(value: Player.fetchAll)
let cancellable = observation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in
print("fresh players", players)
})
```
> :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:
</details>
<details>
<summary>RxGRDB example</summary>
```swift
request.observationForCount()
request.observationForAll()
request.observationForFirst()
import GRDB
import RxGRDB
import RxSwift
let observation = ValueObservation.tracking(value: Player.fetchAll)
let disposable = observation.rx.changes(in: dbQueue).subscribe(
onNext: { (players: [Player]) in
print("fresh players", players)
},
onError: { error in ... })
```
Those observations are equivalent to the following ones, defined with [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue):
</details>
```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) }
```
**Generally speaking**:
Yet they are **optimized**:
- 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.
- 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.
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 Transformations
### 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.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` method lets you transform the values notified by a ValueObservation.
The `map` operator transforms the values notified by a ValueObservation.
For example:
```swift
// Observe a player's profile image
// 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 }
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.
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
The `removeDuplicates` method filters out the consecutive equal values notified by a ValueObservation. The observed values must adopt the standard Equatable protocol.
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()
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
#### ValueObservation.combine(...)
The `ValueObservation.combine(...)` method builds a single observation from several:
The `ValueObservation.combine` static method builds a single observation from several (up to eight):
```swift
// Two base observations
// 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)
@@ -5810,23 +5654,14 @@ let bestPlayersObservation = ValueObservation.tracking { db in
.fetchAll(db)
}
// The combined observation
// The combined observation of (Int, [Player])
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)
""")
})
```
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
@@ -5835,44 +5670,14 @@ struct HallOfFame {
var bestPlayers: [Player]
}
// An observation of HallOfFame
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.
> :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
@@ -5933,27 +5738,6 @@ The `scheduling` property lets you control how fresh values are notified:
// <- 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
@@ -5967,7 +5751,115 @@ var observation = ValueObservation.tracking { db in
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.
When you use a [database pool](#database-pools), this flag has a performance hit.
### ValueObservation Performance
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, 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.
You can filter out undesired duplicate notifications with the [removeDuplicates()](#valueobservationremoveduplicates) method.
**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. :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:
<details>
<summary>UIViewController example</summary>
```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]) { ... }
}
```
</details>
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.
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)
```
3. :bulb: **Tip**: Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses.
4. :bulb: **Tip**: 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.
5. :bulb: **Tip**: 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.
## DatabaseRegionObservation
@@ -6018,23 +5910,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:
@@ -6333,8 +6208,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
@@ -7470,9 +7343,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<Database, Error>) in
reader.asyncRead { (dbResult: Result<Database, Error>) in
try {
let db = try result.get()
let db = try dbResult.get()
let players = try Player.fetchAll(db)
} catch {
// handle error
@@ -7568,11 +7441,11 @@ try writer.asyncWriteWithoutTransaction { db in
// <- not in a transaction here
// Count players concurrently
writer.asyncConcurrentRead { (result: Result<Database, Error>) in
writer.asyncConcurrentRead { (dbResult: Result<Database, Error>) 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
}
@@ -8138,6 +8011,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 +8039,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
@@ -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 = "<group>"; };
56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = "<group>"; };
56C8123724279584004FBBFF /* FailableTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
56C8123824279584004FBBFF /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = "<group>"; };
56C8123924279584004FBBFF /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = "<group>"; };
56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = "<group>"; };
56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = "<group>"; };
56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = "<group>"; };
@@ -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 */,
@@ -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 = "<group>"; };
5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = "<group>"; };
56C8122E24279549004FBBFF /* FailableTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = "<group>"; };
56C8123024279549004FBBFF /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = "<group>"; };
56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = "<group>"; };
56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = "<group>"; };
56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = "<group>"; };
@@ -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 */,
@@ -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"]),
@@ -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"]),
@@ -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
+4 -4
View File
@@ -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)
+184
View File
@@ -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")
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -12,76 +12,30 @@ 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
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
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1, 2, 3, 2])
}
}
func testTableRecordStaticCount() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let observations = [
T.all().observationForCount(),
T.observationForCount()]
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
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.execute(sql: "DELETE FROM t WHERE id = 1")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1, 2, 3, 2])
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")
})
}
}
}
@@ -1,18 +1,18 @@
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 {
private struct Name: DatabaseValueConvertible, Equatable {
var rawValue: String
var databaseValue: DatabaseValue { rawValue.databaseValue }
@@ -27,63 +27,44 @@ 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<Name>(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
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<Name>(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
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map(\.rawValue)}, [
[],
["foo"],
["foo", "bar"],
["bar"]])
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
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<Name>(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
try assertValueObservation(
SQLRequest<Name>(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 {
@@ -98,78 +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'")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map(\.rawValue)}, [
nil,
"foo",
"bar",
nil,
"baz",
nil,
"qux"])
}
})
}
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<Name?>(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
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<Name?>(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
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0?.rawValue }}, [
[],
["foo"],
["foo", nil],
[nil]])
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
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<Name?>(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
try assertValueObservation(
SQLRequest<Name?>(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 {
@@ -184,18 +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'")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map(\.rawValue)}, [
nil,
"foo",
"bar",
nil,
"baz",
nil,
"qux"])
}
})
}
func testViewOptimization() throws {
@@ -21,72 +21,34 @@ 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)") }
var counts: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try assertValueObservation(
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 test(makeDatabaseQueue())
try test(makeDatabasePool())
}),
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")
})
}
func testRemoveDuplicated() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.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 observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try assertValueObservation(
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 test(makeDatabaseQueue())
try test(makeDatabasePool())
}).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")
})
}
}
+14 -37
View File
@@ -12,45 +12,22 @@ import XCTest
class ValueObservationMapTests: GRDBTestCase {
func testMap() throws {
func test(_ dbWriter: DatabaseWriter) throws {
// We need something to change
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
// 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()
let valueObservation = ValueObservation
.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
})
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"])
}
}
.map { "\($0)" }
try test(makeDatabaseQueue())
try test(makeDatabasePool())
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")
})
}
func testMapPreservesConfiguration() {
@@ -28,189 +28,126 @@ 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()
var results: [Row?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
try dbQueue.write(setup)
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
try dbQueue.write(setup)
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
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
try assertValueObservation(
request.observationForFirst(),
records: [
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: []),
])
}
],
setup: setup,
recordedUpdates: { db in
try db.execute(sql: "DELETE FROM child")
})
}
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
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
try assertValueObservation(
request.observationForAll(),
records: [
[
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 +157,10 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
parent: Parent(id: 2, name: "bar"),
children: []),
],
])
}
],
setup: setup,
recordedUpdates: { db in
try db.execute(sql: "DELETE FROM child")
})
}
}
@@ -1,76 +1,49 @@
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")!
try assertValueObservation(
ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
}),
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")
})
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 {
try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1])
}
}
func testWriteObservationFailsByDefaultWithErrorHandling() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
return 0
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")
},
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
})
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")
}
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")
@@ -79,29 +52,19 @@ class ValueObservationReadonlyTests: GRDBTestCase {
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 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")
})
try withExtendedLifetime(observer) {
try dbQueue.write {
try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1])
}
}
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")
@@ -109,17 +72,14 @@ class ValueObservationReadonlyTests: GRDBTestCase {
})
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
}
let count = try dbQueue.read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }
XCTAssertEqual(count, 0)
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)
},
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
})
}
}
+54 -100
View File
@@ -10,134 +10,88 @@ 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<Player>(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
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<Player>(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
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map(\.row)}, [
[],
[["id":1, "name":"foo"]],
[["id":1, "name":"foo"], ["id":2, "name":"bar"]],
[["id":2, "name":"bar"]]])
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
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
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(
Player.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
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map(\.row)}, [
[],
[["id":1, "name":"foo"]],
[["id":1, "name":"foo"], ["id":2, "name":"bar"]],
[["id":2, "name":"bar"]]])
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
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<Player>(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
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<Player>(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(),
records: [
nil,
Player(id: 1, name: "foo"),
Player(id: 2, name: "bar"),
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") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map(\.row)}, [
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil])
}
try db.execute(sql: "DELETE FROM t")
})
}
}
@@ -0,0 +1,626 @@
// Inspired by https://github.com/groue/CombineExpectations
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
// MARK: - ValueObservationRecorder
public class ValueObservationRecorder<Value> {
private struct RecorderExpectation {
var expectation: XCTestExpectation
var remainingCount: Int? // nil for error expectation
}
/// The recorder state
private struct State {
var values: [Value]
var error: Error?
var recorderExpectation: RecorderExpectation?
var observer: TransactionObserver?
}
private let lock = NSLock()
private var state = State(values: [], recorderExpectation: nil, observer: nil)
private var consumedCount = 0
/// Internal for testability. Use ValueObservation.record(in:) instead.
init() { }
private func synchronized<T>(_ execute: () throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try execute()
}
// 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
func fulfillOnValue(_ expectation: XCTestExpectation, includingConsumed: Bool) {
synchronized {
preconditionCanFulfillExpectation()
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
if state.error != nil {
expectation.fulfill(count: expectedFulfillmentCount)
return
}
let values = state.values
let maxFulfillmentCount = includingConsumed
? 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
}
}
}
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.
///
/// - parameter value: A function which returns the value, given the
/// 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<T>(_ value: (
_ values: [Value],
_ error: Error?,
_ remainingValues: ArraySlice<Value>,
_ consume: (_ count: Int) -> ()) throws -> T)
rethrows -> T
{
try synchronized {
let values = state.values
let remainingValues = values[consumedCount...]
return try value(values, state.error, remainingValues, { count in
precondition(count >= 0)
precondition(count <= remainingValues.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("ValueObservationRecorder is already observing")
}
state.observer = observer
}
}
}
// MARK: - ValueObservationRecorder + Expectations
extension ValueObservationRecorder {
public func failure() -> ValueObservationExpectations.Failure<Value> {
ValueObservationExpectations.Failure(recorder: self)
}
public func next() -> ValueObservationExpectations.NextOne<Value> {
ValueObservationExpectations.NextOne(recorder: self)
}
public func next(_ count: Int) -> ValueObservationExpectations.Next<Value> {
ValueObservationExpectations.Next(recorder: self, count: count)
}
public func prefix(_ maxLength: Int) -> ValueObservationExpectations.Prefix<Value> {
ValueObservationExpectations.Prefix(recorder: self, maxLength: maxLength)
}
}
// MARK: - ValueObservation + ValueObservationRecorder
extension ValueObservation {
public func record(in reader: DatabaseReader) -> ValueObservationRecorder<Reducer.Value> {
let recorder = ValueObservationRecorder<Reducer.Value>()
let observer = start(
in: reader,
onError: recorder.onError,
onChange: recorder.onChange)
recorder.receive(observer)
return recorder
}
}
// 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<E: ValueObservationExpectation>(
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()
}
/// 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<Value>(
recorded recordedValues: [Value],
expected expectedValues: [Value],
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line)
where Value: Equatable
{
assertValueObservationRecordingMatch(
recorded: recordedValues,
expected: expectedValues,
// Last value can't be missed
allowMissingLastValue: false,
message(), file: file, line: line)
}
private func assertValueObservationRecordingMatch<R, E>(
recorded recordedValues: R,
expected expectedValues: E,
allowMissingLastValue: Bool,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line)
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 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)
}
}
let remainingRecordedValues = recordedValues.prefix(recordedValues.count - recordedSuffix.count)
let remainingExpectedValues = expectedValues.prefix(expectedValues.count - expectedSuffix.count)
assertValueObservationRecordingMatch(
recorded: remainingRecordedValues,
expected: remainingExpectedValues,
// Other values can be missed
allowMissingLastValue: true,
message(), file: file, line: line)
}
}
// MARK: - GRDBTestCase + ValueObservationExpectation
extension GRDBTestCase {
func assertValueObservation<Reducer: _ValueReducer>(
_ valueObservation: ValueObservation<Reducer>,
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<Reducer>) 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<Reducer>) 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<Reducer: _ValueReducer, Failure: Error>(
_ valueObservation: ValueObservation<Reducer>,
fails testFailure: (Failure, DatabaseWriter) throws -> Void,
setup: (Database) throws -> Void,
file: StaticString = #file,
line: UInt = #line)
throws
{
func test(writer: DatabaseWriter, observation: ValueObservation<Reducer>) 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 { }
extension ValueObservationExpectations {
// MARK: Inverted
public struct Inverted<Base: ValueObservationExpectation>: 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<Value>: ValueObservationExpectation {
let recorder: ValueObservationRecorder<Value>
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<Value> {
return NextOneInverted(recorder: recorder)
}
}
// MARK: NextOneInverted
public struct NextOneInverted<Value>: ValueObservationExpectation {
let recorder: ValueObservationRecorder<Value>
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<Value>: ValueObservationExpectation {
let recorder: ValueObservationRecorder<Value>
let count: Int
init(recorder: ValueObservationRecorder<Value>, 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<Value>: ValueObservationExpectation {
let recorder: ValueObservationRecorder<Value>
let maxLength: Int
init(recorder: ValueObservationRecorder<Value>, 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<Self> {
return Inverted(base: self)
}
}
// MARK: Failure
public struct Failure<Value>: ValueObservationExpectation {
let recorder: ValueObservationRecorder<Value>
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 {
fileprivate func fulfill(count: Int) {
for _ in 0..<count {
fulfill()
}
}
}
@@ -0,0 +1,706 @@
import Dispatch
import XCTest
class ValueObservationRecorderTests: FailureTestCase {
// MARK: - NextOne
func testNextOneSuccess() throws {
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
try XCTAssertEqual(recorder.next().get(), "foo")
recorder.onChange("bar")
try XCTAssertEqual(recorder.next().get(), "bar")
}
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
recorder.onChange("bar")
try XCTAssertEqual(recorder.next().get(), "foo")
try XCTAssertEqual(recorder.next().get(), "bar")
}
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
recorder.onError(CustomError())
_ = try recorder.next().get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
recorder.onError(CustomError())
_ = try wait(for: recorder.next(), timeout: 0.1)
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
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<String>()
_ = try wait(for: recorder.next(), timeout: 0.1)
XCTFail("Expected error")
} catch ValueRecordingError.notEnoughValues { }
}
try assertFailure("Asynchronous wait failed") {
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
_ = try recorder.next().get()
XCTFail("Expected error")
} catch ValueRecordingError.notEnoughValues { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
try recorder.next().inverted.get()
}
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
_ = try recorder.next().get()
try recorder.next().inverted.get()
}
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
recorder.onError(CustomError())
try recorder.next().inverted.get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
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<String>()
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<String>()
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<String>()
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<String>()
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<String>()
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<String>()
recorder.onError(CustomError())
_ = try recorder.next(2).get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
recorder.onError(CustomError())
_ = try recorder.next(2).get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
_ = try wait(for: recorder.next(2), timeout: 0.1)
XCTFail("Expected error")
} catch ValueRecordingError.notEnoughValues { }
}
try assertFailure("Asynchronous wait failed") {
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
_ = try recorder.next(2).get()
XCTFail("Expected error")
} catch ValueRecordingError.notEnoughValues { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
recorder.onError(CustomError())
try XCTAssertEqual(recorder.prefix(0).get(), [])
}
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
recorder.onError(CustomError())
try XCTAssertEqual(recorder.prefix(1).get(), ["foo"])
}
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
recorder.onError(CustomError())
_ = try recorder.next(2).get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
recorder.onError(CustomError())
_ = try recorder.next(2).get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
_ = try wait(for: recorder.next(2), timeout: 0.1)
XCTFail("Expected error")
} catch ValueRecordingError.notEnoughValues { }
}
try assertFailure("Asynchronous wait failed") {
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
try XCTAssertEqual(recorder.prefix(1).inverted.get(), [])
}
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
try XCTAssertEqual(recorder.prefix(2).inverted.get(), ["foo"])
}
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
recorder.onError(CustomError())
_ = try recorder.prefix(1).inverted.get()
XCTFail("Expected error")
} catch is CustomError { }
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
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<String>()
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<String>()
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<String>()
recorder.onError(CustomError())
let (elements, error) = try recorder.failure().get()
XCTAssertEqual(elements, [])
XCTAssert(error is CustomError)
}
do {
let recorder = ValueObservationRecorder<String>()
recorder.onError(CustomError())
let (elements, error) = try wait(for: recorder.failure(), timeout: 0.1)
XCTAssertEqual(elements, [])
XCTAssert(error is CustomError)
}
}
func testFailureTimeout() throws {
try assertFailure("Asynchronous wait failed") {
do {
let recorder = ValueObservationRecorder<String>()
_ = try wait(for: recorder.failure(), timeout: 0.1)
XCTFail("Expected error")
} catch ValueRecordingError.notFailed { }
}
try assertFailure("Asynchronous wait failed") {
do {
let recorder = ValueObservationRecorder<String>()
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<String>()
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<String>()
_ = try recorder.failure().get()
XCTFail("Expected error")
} catch ValueRecordingError.notFailed { }
do {
let recorder = ValueObservationRecorder<String>()
recorder.onChange("foo")
_ = try recorder.failure().get()
XCTFail("Expected error")
} catch ValueRecordingError.notFailed { }
}
// MARK: - assertValueObservationRecordingMatch
func testAssertValueObservationRecordingMatch() {
do {
let expected = [3]
assertValueObservationRecordingMatch(recorded: [3], expected: expected)
assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected)
assertFailure("failed - missing expected value 3") {
assertValueObservationRecordingMatch(recorded: [], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [2]", "failed - missing expected value 3") {
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [2]") {
assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected)
}
}
do {
let expected = [2, 3]
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)
}
assertFailure("failed - missing expected value 3") {
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
}
assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") {
assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [1]") {
assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [1]") {
assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected)
}
}
do {
let expected = [3, 3]
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)
}
assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [2]") {
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [2]") {
assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [2, 2]") {
assertValueObservationRecordingMatch(recorded: [2, 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]
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)
}
assertFailure("failed - missing expected value 3") {
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
}
assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") {
assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [2]") {
assertValueObservationRecordingMatch(recorded: [2, 1, 3], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [0]") {
assertValueObservationRecordingMatch(recorded: [0, 3], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [0]") {
assertValueObservationRecordingMatch(recorded: [0, 1, 2, 3], expected: expected)
}
}
do {
let expected = [1, 2, 1]
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)
}
assertFailure("failed - missing expected value 1") {
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
}
assertFailure("failed - missing expected value 1") {
assertValueObservationRecordingMatch(recorded: [1, 2], expected: expected)
}
assertFailure("failed - unexpected recorded prefix [0]") {
assertValueObservationRecordingMatch(recorded: [0, 1], expected: expected)
}
}
}
}
@@ -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)") }
+85 -162
View File
@@ -12,190 +12,113 @@ 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<Row>(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
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
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
try assertValueObservation(
SQLRequest<Row>(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"]]])
}
}
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<Row>(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
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
}
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil])
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
func testOne() throws {
try assertValueObservation(
SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(),
records: [
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
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 {
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<Row>(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)")
try assertValueObservation(
SQLRequest<Row>(sql: "SELECT * FROM ft_documents").observationForAll(),
records: [
[],
[["content":"foo"]]],
setup: { db in
try db.create(virtualTable: "ft_documents", using: FTS4())
},
onChange: {
rows.append($0)
notificationExpectation.fulfill()
})
try withExtendedLifetime(observer) {
try dbQueue.write { db in
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"])
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(rows, [[], [["content":"foo"]]])
}
})
}
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)
}
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<Row>(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)")
try assertValueObservation(
SQLRequest<Row>(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)
}
try db.create(virtualTable: "ft_documents", using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
},
onChange: {
rows.append($0)
notificationExpectation.fulfill()
})
try withExtendedLifetime(observer) {
try dbQueue.write { db in
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(rows, [[], [["content":"foo"]]])
}
})
}
func testJoinedFTS4Observation() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.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")
}
}
var rows: [[Row]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = SQLRequest<Row>(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)")
try assertValueObservation(
SQLRequest<Row>(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")
}
},
onChange: {
rows.append($0)
notificationExpectation.fulfill()
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
}
})
try withExtendedLifetime(observer) {
try dbQueue.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]]])
}
}
}
@@ -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])
}
}