Merge pull request #798 from groue/dev/ValueObservation-debug

Debugging operators for ValueObservation
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-06-22 18:43:13 +02:00
commit 115f293e26
18 files changed
+1079 -88

No files matched your search

+7 -4
View File
@@ -5,9 +5,7 @@ All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
<!--
[Next Release](#next-release)
-->
#### 5.x Releases
@@ -70,9 +68,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
<!--
## Next Release
-->
- **New**: [#798](https://github.com/groue/GRDB.swift/pull/798): Debugging operators for ValueObservation
### Documentation Diff
[ValueObservation Operators](README.md#valueobservation-operators) was extended with the documentation for the two new operators `handleEvents` and `print`.
## 5.0.0-beta.5
+18
View File
@@ -166,6 +166,13 @@
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B8F92249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
563B8F95249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
@@ -1245,6 +1252,8 @@
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
@@ -1815,6 +1824,7 @@
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */,
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */,
563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */,
5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */,
563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */,
56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */,
@@ -2209,6 +2219,7 @@
56AACAA722ACED7100A40F2A /* Fetch.swift */,
5613ED3421A95A5C00DC7A68 /* Map.swift */,
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */,
563B8F91249E6171007A48C9 /* Trace.swift */,
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */,
);
path = ValueReducer;
@@ -2809,6 +2820,7 @@
5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */,
56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
563B8F94249E6171007A48C9 /* Trace.swift in Sources */,
568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */,
565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */,
5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2976,6 +2988,7 @@
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
@@ -3139,6 +3152,7 @@
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
@@ -3347,6 +3361,7 @@
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
@@ -3522,6 +3537,7 @@
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */,
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */,
@@ -3685,6 +3701,7 @@
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */,
AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
AAA4DD8A230F262000C74B15 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */,
AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */,
@@ -3860,6 +3877,7 @@
5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
563B8F92249E6171007A48C9 /* Trace.swift in Sources */,
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
+10 -14
View File
@@ -809,7 +809,6 @@ extension DatabasePool: DatabaseReader {
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
@@ -817,7 +816,6 @@ extension DatabasePool: DatabaseReader {
return _addReadOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
@@ -825,7 +823,6 @@ extension DatabasePool: DatabaseReader {
let observer = _addWriteOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
return AnyDatabaseCancellable(cancel: observer.cancel)
}
@@ -833,7 +830,6 @@ extension DatabasePool: DatabaseReader {
let observer = _addConcurrent(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
return AnyDatabaseCancellable(cancel: observer.cancel)
}
@@ -843,7 +839,6 @@ extension DatabasePool: DatabaseReader {
private func _addConcurrent<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> ValueObserver<Reducer> // For testability
{
@@ -853,13 +848,11 @@ extension DatabasePool: DatabaseReader {
let reduceQueueLabel = configuration.identifier(
defaultLabel: "GRDB",
purpose: "ValueObservation")
let observer = ValueObserver<Reducer>(
requiresWriteAccess: observation.requiresWriteAccess,
let observer = ValueObserver(
observation: observation,
writer: self,
reducer: observation.makeReducer(),
scheduling: scheduler,
scheduler: scheduler,
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
onError: onError,
onChange: onChange)
// Starting a concurrent observation means that we'll fetch the initial
@@ -904,8 +897,8 @@ extension DatabasePool: DatabaseReader {
onChange(initialValue)
add(observer: observer, from: initialSnapshot)
} catch {
observer.cancel()
onError(error)
observer.complete()
observation.events.didFail?(error)
}
} else {
let label = configuration.identifier(
@@ -963,8 +956,11 @@ extension DatabasePool: DatabaseReader {
}
}
if fetchNeeded, let value = try observer.fetchValue(db) {
observer.notifyChange(value)
if fetchNeeded {
observer.events.databaseDidChange?()
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
}
return .commit
}
-3
View File
@@ -476,7 +476,6 @@ extension DatabaseQueue {
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
@@ -484,14 +483,12 @@ extension DatabaseQueue {
return _addReadOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
let observer = _addWriteOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
return AnyDatabaseCancellable(cancel: observer.cancel)
}
+4 -10
View File
@@ -246,16 +246,12 @@ public protocol DatabaseReader: AnyObject {
/// method instead.
///
/// - parameter observation: the stared observation
/// - parameter onError: a closure that is provided by eventual errors that happen
/// during observation
/// - parameter onChange: a closure that is provided fresh values
/// - returns: a TransactionObserver
///
/// :nodoc:
func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
}
@@ -301,15 +297,15 @@ extension DatabaseReader {
func _addReadOnly<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
if scheduler.immediateInitialValue() {
do {
try onChange(unsafeReentrantRead(observation.fetchValue))
let value = try unsafeReentrantRead(observation.fetchValue)
onChange(value)
} catch {
onError(error)
observation.events.didFail?(error)
}
return AnyDatabaseCancellable(cancel: { })
} else {
@@ -329,7 +325,7 @@ extension DatabaseReader {
do {
try onChange(result.get())
} catch {
onError(error)
observation.events.didFail?(error)
}
}
}
@@ -419,14 +415,12 @@ public final class AnyDatabaseReader: DatabaseReader {
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
base._add(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
-2
View File
@@ -132,14 +132,12 @@ extension DatabaseSnapshot {
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
_addReadOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
+5 -10
View File
@@ -312,7 +312,6 @@ extension DatabaseWriter {
func _addWriteOnly<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> ValueObserver<Reducer> // For testability
{
@@ -321,13 +320,11 @@ extension DatabaseWriter {
let reduceQueueLabel = configuration.identifier(
defaultLabel: "GRDB",
purpose: "ValueObservation")
let observer = ValueObserver<Reducer>(
requiresWriteAccess: observation.requiresWriteAccess,
let observer = ValueObserver(
observation: observation,
writer: self,
reducer: observation.makeReducer(),
scheduling: scheduler,
scheduler: scheduler,
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
onError: onError,
onChange: onChange)
if scheduler.immediateInitialValue() {
@@ -339,8 +336,8 @@ extension DatabaseWriter {
}
onChange(initialValue)
} catch {
observer.cancel()
onError(error)
observer.complete()
observation.events.didFail?(error)
}
} else {
_weakAsyncWriteWithoutTransaction { db in
@@ -530,14 +527,12 @@ public final class AnyDatabaseWriter: DatabaseWriter {
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
base._add(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
+36
View File
@@ -134,3 +134,39 @@ func throwingFirstError<T>(execute: () throws -> T, finally: () throws -> Void)
}
return result!
}
struct PrintOutputStream: TextOutputStream {
func write(_ string: String) {
Swift.print(string)
}
}
/// Concatenates two functions
func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
case let (nil, lhs):
return lhs
case let (rhs?, lhs?):
return {
rhs()
lhs()
}
}
}
/// Concatenates two functions
func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
case let (nil, lhs):
return lhs
case let (rhs?, lhs?):
return {
rhs($0)
lhs($0)
}
}
}
+92 -2
View File
@@ -16,6 +16,8 @@ import Dispatch
/// print("Players have changed.")
/// })
public struct ValueObservation<Reducer: _ValueReducer> {
var events = ValueObservationEvents()
/// The reducer is created when observation starts, and is triggered upon
/// each database change.
var makeReducer: () -> Reducer
@@ -32,12 +34,21 @@ public struct ValueObservation<Reducer: _ValueReducer> {
func mapReducer<R>(_ transform: @escaping (Reducer) -> R) -> ValueObservation<R> {
let makeReducer = self.makeReducer
return ValueObservation<R>(
events: events,
makeReducer: { transform(makeReducer()) },
requiresWriteAccess: requiresWriteAccess)
}
}
extension ValueObservation {
struct ValueObservationEvents: Refinable {
var willStart: (() -> Void)?
var willTrackRegion: ((DatabaseRegion) -> Void)?
var databaseDidChange: (() -> Void)?
var didFail: ((Error) -> Void)?
var didCancel: (() -> Void)?
}
extension ValueObservation: Refinable {
// MARK: - Starting Observation
@@ -88,7 +99,86 @@ extension ValueObservation {
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable
{
reader._add(observation: self, scheduling: scheduler, onError: onError, onChange: onChange)
let observation = map(\.events) { events in
events.map(\.didFail) { concat($0, onError) }
}
observation.events.willStart?()
return reader._add(
observation: observation,
scheduling: scheduler,
onChange: onChange)
}
// MARK: - Debugging
/// Performs the specified closures when ValueObservation events occur.
///
/// - parameters:
/// - willStart: A closure that executes when the observation starts.
/// Defaults to `nil`.
/// - willFetch: A closure that executes when the observed value is
/// about to be fetched. Defaults to `nil`.
/// - willTrackRegion: A closure that executes when the observation
/// starts tracking a database region. Defaults to `nil`.
/// - databaseDidChange: A closure that executes after the observation
/// was impacted by a database change. Defaults to `nil`.
/// - didReceiveValue: A closure that executes on fresh values. Defaults
/// to `nil`.
///
/// NOTE: This closure runs on an unspecified DispatchQueue.
/// - didFail: A closure that executes when the observation fails.
/// Defaults to `nil`.
/// - didCancel: A closure that executes when the observation is
/// cancelled. Defaults to `nil`.
/// - returns: A `ValueObservation` that performs the specified closures
/// when ValueObservation events occur.
public func handleEvents(
willStart: (() -> Void)? = nil,
willFetch: (() -> Void)? = nil,
willTrackRegion: ((DatabaseRegion) -> Void)? = nil,
databaseDidChange: (() -> Void)? = nil,
didReceiveValue: ((Reducer.Value) -> Void)? = nil,
didFail: ((Error) -> Void)? = nil,
didCancel: (() -> Void)? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
self
.mapReducer({ reducer in
ValueReducers.Trace(
base: reducer,
// Adding the willFetch handler to the reducer is handy: we
// are sure not to miss any fetch.
willFetch: willFetch ?? { },
// Adding the didReceiveValue handler to the reducer is necessary:
// the type of the value may change with the `map` operator.
didReceiveValue: didReceiveValue ?? { _ in })
})
.map(\.events, { events in
events
.map(\.willStart) { concat($0, willStart) }
.map(\.willTrackRegion) { concat($0, willTrackRegion) }
.map(\.databaseDidChange) { concat($0, databaseDidChange) }
.map(\.didFail) { concat($0, didFail) }
.map(\.didCancel) { concat($0, didCancel) }
})
}
/// Prints log messages for all ValueObservation events.
public func print(
_ prefix: String = "",
to stream: TextOutputStream? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
let prefix = prefix.isEmpty ? "" : "\(prefix): "
var stream = stream ?? PrintOutputStream()
return handleEvents(
willStart: { stream.write("\(prefix)will start") },
willFetch: { stream.write("\(prefix)will fetch") },
willTrackRegion: { stream.write("\(prefix)will track region: \($0)") },
databaseDidChange: { stream.write("\(prefix)database did change") },
didReceiveValue: { stream.write("\(prefix)did receive value: \($0)") },
didFail: { stream.write("\(prefix)did fail: \($0)") },
didCancel: { stream.write("\(prefix)did cancel") })
}
// MARK: - Fetching Values
+48 -12
View File
@@ -3,36 +3,63 @@ import Foundation
/// Support for ValueObservation.
/// See DatabaseWriter.add(observation:onError:onChange:)
final class ValueObserver<Reducer: _ValueReducer> {
private(set) var observedRegion: DatabaseRegion? // internal for testability
var isCompleted: Bool { synchronized { _isCompleted } }
let events: ValueObservationEvents
private var observedRegion: DatabaseRegion? {
didSet {
if
let willTrackRegion = events.willTrackRegion,
let region = observedRegion,
region != oldValue
{
willTrackRegion(region)
}
}
}
private var _isCompleted = false
private var reducer: Reducer
private let requiresWriteAccess: Bool
private weak var writer: DatabaseWriter?
private let scheduler: ValueObservationScheduler
private let reduceQueue: DispatchQueue
private let onError: (Error) -> Void
private let onChange: (Reducer.Value) -> Void
private var isChanged = false
private let onChange: (Reducer.Value) -> Void
private var lock = NSRecursiveLock() // protects _isCompleted
init(
events: ValueObservationEvents,
reducer: Reducer,
requiresWriteAccess: Bool,
writer: DatabaseWriter,
reducer: Reducer,
scheduling scheduler: ValueObservationScheduler,
scheduler: ValueObservationScheduler,
reduceQueue: DispatchQueue,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
{
self.writer = writer
self.events = events
self.reducer = reducer
self.requiresWriteAccess = requiresWriteAccess
self.writer = writer
self.scheduler = scheduler
self.reduceQueue = reduceQueue
self.onError = onError
self.onChange = onChange
}
convenience init(
observation: ValueObservation<Reducer>,
writer: DatabaseWriter,
scheduler: ValueObservationScheduler,
reduceQueue: DispatchQueue,
onChange: @escaping (Reducer.Value) -> Void)
{
self.init(
events: observation.events,
reducer: observation.makeReducer(),
requiresWriteAccess: observation.requiresWriteAccess,
writer: writer,
scheduler: scheduler,
reduceQueue: reduceQueue,
onChange: onChange)
}
}
// MARK: - TransactionObserver
@@ -60,6 +87,8 @@ extension ValueObserver: TransactionObserver {
isChanged = false
if isCompleted { return }
events.databaseDidChange?()
// 1. Fetch
let fetchedValue: DatabaseFuture<Reducer.Fetched>
if requiresWriteAccess || needsRecordingSelectedRegion {
@@ -119,14 +148,21 @@ extension ValueObserver {
}
}
func cancel() {
func complete() {
synchronized {
// no harm if already completed
_isCompleted = true
writer?.remove(transactionObserver: self)
}
}
func cancel() {
synchronized {
if _isCompleted { return }
complete()
events.didCancel?()
}
}
func notifyChange(_ value: Reducer.Value) {
if isCompleted { return }
scheduler.schedule {
@@ -142,12 +178,12 @@ extension ValueObserver {
if self._isCompleted {
return false
} else {
self._isCompleted = true
self.complete()
return true
}
}
if shouldNotify {
self.onError(error)
self.events.didFail?(error)
}
}
}
@@ -0,0 +1,24 @@
extension ValueReducers {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public struct Trace<Base: _ValueReducer>: _ValueReducer {
var base: Base
let willFetch: () -> Void
let didReceiveValue: (Base.Value) -> Void
public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic }
public func fetch(_ db: Database) throws -> Base.Fetched {
willFetch()
return try base.fetch(db)
}
public mutating func value(_ fetched: Base.Fetched) -> Base.Value? {
guard let value = base.value(fetched) else {
return nil
}
didReceiveValue(value)
return value
}
}
}
+12
View File
@@ -87,6 +87,10 @@
563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; };
563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; };
563B8F9F249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; };
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
@@ -782,6 +786,8 @@
563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
@@ -1323,6 +1329,7 @@
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */,
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */,
563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */,
5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */,
563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */,
56677C24241E6EA20050755D /* ValueObservationRecorder.swift */,
@@ -1711,6 +1718,7 @@
56C0538A22ACEECD0029D27D /* Fetch.swift */,
56C0538E22ACEECD0029D27D /* Map.swift */,
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */,
563B8F99249E74E5007A48C9 /* Trace.swift */,
56C0538C22ACEECD0029D27D /* ValueReducer.swift */,
);
path = ValueReducer;
@@ -2247,6 +2255,7 @@
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */,
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
@@ -2410,6 +2419,7 @@
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
563B8F9F249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */,
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
@@ -2585,6 +2595,7 @@
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */,
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
@@ -2748,6 +2759,7 @@
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */,
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
+53
View File
@@ -5494,6 +5494,11 @@ let cancellable = observation.start(
- [ValueObservation.removeDuplicates](#valueobservationremoveduplicates)
- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess)
**Debugging Operators**
- [ValueObservation.handleEvents](#valueobservationhandleevents)
- [ValueObservation.print](#valueobservationprint)
#### ValueObservation.map
@@ -5567,6 +5572,54 @@ observation.requiresWriteAccess = true
When you use a [database pool](#database-pools), this flag has a performance hit.
#### ValueObservation.handleEvents
The `handleEvents` operator lets your application observe the lifetime of a ValueObservation:
```swift
let observation = ValueObservation
.tracking { db in ... }
.handleEvents(
willStart: {
// The observation starts.
},
willFetch: {
// The observation will perform a database fetch.
},
willTrackRegion: { databaseRegion in
// The observation starts tracking a database region.
},
databaseDidChange: {
// The observation was impacted by a database change.
},
didReceiveValue: { value in
// A fresh value was observed.
// NOTE: This closure runs on an unspecified DispatchQueue.
},
didFail: { error in
// The observation completes with an error.
},
didCancel: {
// The observation was cancelled.
})
```
See also [ValueObservation.print](#valueobservationprint).
#### ValueObservation.print
The `print` operator logs messages for all ValueObservation events.
```swift
let observation = ValueObservation
.tracking { db in ... }
.print()
```
See also [ValueObservation.handleEvents](#valueobservationhandleevents).
### ValueObservation Performance
This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications.
@@ -23,6 +23,8 @@
561CFAAF2376EFBE000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561CFAB02376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561CFAB12376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; };
563B8FA8249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FA9249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */; };
563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
@@ -417,6 +419,7 @@
561CFA8223735091000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -661,6 +664,8 @@
564A1F1F226B876D001F64F1 /* GRDBTests */ = {
isa = PBXGroup;
children = (
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */,
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
564A1F90226B89D9001F64F1 /* AnyCursorTests.swift */,
564A1F60226B89D4001F64F1 /* AssociationAggregateTests.swift */,
564A1F35226B89CF001F64F1 /* AssociationBelongsToDecodableRecordTests.swift */,
@@ -693,7 +698,6 @@
560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */,
564A1F3E226B89D0001F64F1 /* AssociationRowScopeSearchTests.swift */,
564A1FCF226B89E0001F64F1 /* AssociationTableAliasTestsSQLTests.swift */,
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */,
564A1F61226B89D4001F64F1 /* ColumnExpressionTests.swift */,
564A1FAC226B89DC001F64F1 /* ColumnInfoTests.swift */,
@@ -786,7 +790,6 @@
564A1FC4226B89DE001F64F1 /* FTS5TokenizerTests.swift */,
564A1F43226B89D0001F64F1 /* FTS5WrapperTokenizerTests.swift */,
564A1FD5226B89E0001F64F1 /* GRDBTestCase.swift */,
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */,
564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */,
564A1FCD226B89DF001F64F1 /* JoinSupportTests.swift */,
564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */,
@@ -851,6 +854,7 @@
564A1F6C226B89D5001F64F1 /* ValueObservationDatabaseValueConvertibleTests.swift */,
564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */,
564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */,
563B8FA7249E8B14007A48C9 /* ValueObservationPrintTests.swift */,
5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */,
564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */,
56C8123924279584004FBBFF /* ValueObservationRecorder.swift */,
@@ -1227,6 +1231,7 @@
564A208A226B89E1001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */,
564A2092226B89E1001F64F1 /* DatabasePoolConcurrencyTests.swift in Sources */,
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */,
563B8FA8249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */,
564A2007226B89E1001F64F1 /* FoundationDataTests.swift in Sources */,
564A201A226B89E1001F64F1 /* FTS4TableBuilderTests.swift in Sources */,
564A2059226B89E1001F64F1 /* DatabaseValueConversionTests.swift in Sources */,
@@ -1430,6 +1435,7 @@
564A2127226B8E18001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */,
564A2128226B8E18001F64F1 /* DatabasePoolConcurrencyTests.swift in Sources */,
564A2129226B8E18001F64F1 /* RowCopiedFromStatementTests.swift in Sources */,
563B8FA9249E8B14007A48C9 /* ValueObservationPrintTests.swift in Sources */,
564A212A226B8E18001F64F1 /* FoundationDataTests.swift in Sources */,
564A212B226B8E18001F64F1 /* FTS4TableBuilderTests.swift in Sources */,
564A212C226B8E18001F64F1 /* DatabaseValueConversionTests.swift in Sources */,
@@ -23,6 +23,8 @@
561CFAA92376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561CFAAA2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561CFAAB2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */; };
563B8FA5249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FA6249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */; };
563DE4FE231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4FF231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; };
563F4CB7242F80030052E96C /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB6242F80030052E96C /* ValueObservationTests.swift */; };
@@ -421,6 +423,7 @@
561CFA7F2373507D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563F4CB6242F80030052E96C /* ValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = "<group>"; };
564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -666,6 +669,9 @@
564A1F1F226B876D001F64F1 /* GRDBTests */ = {
isa = PBXGroup;
children = (
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */,
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
564A2158226C8F24001F64F1 /* db.SQLCipher3 */,
564A1F90226B89D9001F64F1 /* AnyCursorTests.swift */,
564A1F60226B89D4001F64F1 /* AssociationAggregateTests.swift */,
564A1F35226B89CF001F64F1 /* AssociationBelongsToDecodableRecordTests.swift */,
@@ -698,7 +704,6 @@
560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */,
564A1F3E226B89D0001F64F1 /* AssociationRowScopeSearchTests.swift */,
564A1FCF226B89E0001F64F1 /* AssociationTableAliasTestsSQLTests.swift */,
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */,
564A1F61226B89D4001F64F1 /* ColumnExpressionTests.swift */,
564A1FAC226B89DC001F64F1 /* ColumnInfoTests.swift */,
@@ -751,7 +756,6 @@
564A1F45226B89D0001F64F1 /* DatabaseValueTests.swift */,
564A1FC0226B89DE001F64F1 /* DatabaseWriterTests.swift */,
564A1FCC226B89DF001F64F1 /* DataMemoryTests.swift */,
564A2158226C8F24001F64F1 /* db.SQLCipher3 */,
564A1F4B226B89D1001F64F1 /* DerivableRequestTests.swift */,
564A1FBB226B89DD001F64F1 /* DropFirstCursorTests.swift */,
564A1F6D226B89D5001F64F1 /* DropWhileCursorTests.swift */,
@@ -792,7 +796,6 @@
564A1FC4226B89DE001F64F1 /* FTS5TokenizerTests.swift */,
564A1F43226B89D0001F64F1 /* FTS5WrapperTokenizerTests.swift */,
564A1FD5226B89E0001F64F1 /* GRDBTestCase.swift */,
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */,
564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */,
564A1FCD226B89DF001F64F1 /* JoinSupportTests.swift */,
564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */,
@@ -857,6 +860,7 @@
564A1F6C226B89D5001F64F1 /* ValueObservationDatabaseValueConvertibleTests.swift */,
564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */,
564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */,
563B8FA4249E8AF6007A48C9 /* ValueObservationPrintTests.swift */,
5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */,
564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */,
56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */,
@@ -1092,6 +1096,7 @@
564A2049226B89E1001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */,
564A1FF0226B89E1001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564A1FEA226B89E1001F64F1 /* AssociationChainRowScopesTests.swift in Sources */,
563B8FA5249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */,
564A207D226B89E1001F64F1 /* ValueObservationFetchTests.swift in Sources */,
564A203C226B89E1001F64F1 /* ValueObservationReadonlyTests.swift in Sources */,
564A203B226B89E1001F64F1 /* ValueObservationCountTests.swift in Sources */,
@@ -1296,6 +1301,7 @@
564A20A4226B8E18001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */,
564A20A5226B8E18001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564A20A6226B8E18001F64F1 /* AssociationChainRowScopesTests.swift in Sources */,
563B8FA6249E8AF6007A48C9 /* ValueObservationPrintTests.swift in Sources */,
564A20A8226B8E18001F64F1 /* ValueObservationFetchTests.swift in Sources */,
564A20A9226B8E18001F64F1 /* ValueObservationReadonlyTests.swift in Sources */,
564A20AA226B8E18001F64F1 /* ValueObservationCountTests.swift in Sources */,
@@ -0,0 +1,712 @@
import XCTest
import Dispatch
@testable import GRDB
class ValueObservationPrintTests: GRDBTestCase {
class TestStream: TextOutputStream {
@LockedBox var strings: [String] = []
func write(_ string: String) {
strings.append(string)
}
}
/// Helps dealing with various SQLite versions
private func region(sql: String, in dbReader: DatabaseReader) throws -> String {
try dbReader.read { db in
try db
.makeSelectStatement(sql: sql)
.databaseRegion
.description
}
}
// MARK: - Readonly
func test_readonly_success_asynchronousScheduling() throws {
let dbPool = try makeDatabasePool(filename: "test")
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
func test(_ dbReader: DatabaseReader) throws {
let logger = TestStream()
let observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbReader,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did receive value: nil"])
}
}
var config = dbConfiguration!
config.readonly = true
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
}
func test_readonly_success_immediateScheduling() throws {
let dbPool = try makeDatabasePool(filename: "test")
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
func test(_ dbReader: DatabaseReader) throws {
let logger = TestStream()
let observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbReader,
scheduling: .immediate,
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did receive value: nil"])
}
}
var config = dbConfiguration!
config.readonly = true
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
}
func test_readonly_failure_asynchronousScheduling() throws {
_ = try makeDatabasePool(filename: "test")
func test(_ dbReader: DatabaseReader) throws {
struct TestError: Error { }
let logger = TestStream()
let observation = ValueObservation
.tracking { _ in throw TestError() }
.print(to: logger)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbReader,
scheduling: .async(onQueue: .main),
onError: { _ in expectation.fulfill() },
onChange: { _ in })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did fail: TestError()"])
}
}
var config = dbConfiguration!
config.readonly = true
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
}
func test_readonly_failure_immediateScheduling() throws {
_ = try makeDatabasePool(filename: "test")
func test(_ dbReader: DatabaseReader) throws {
struct TestError: Error { }
let logger = TestStream()
let observation = ValueObservation
.tracking { _ in throw TestError() }
.print(to: logger)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbReader,
scheduling: .immediate,
onError: { _ in expectation.fulfill() },
onChange: { _ in })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did fail: TestError()"])
}
}
var config = dbConfiguration!
config.readonly = true
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
}
// MARK: - Writeonly
func test_writeonly_success_asynchronousScheduling() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger = TestStream()
var observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
observation.requiresWriteAccess = true
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter)
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbWriter,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in
try! dbWriter.write { db in
try db.execute(sql: "INSERT INTO player DEFAULT VALUES")
}
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings.prefix(7), [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegion)",
"database did change",
"will fetch",
"did receive value: Optional(1)"])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func test_writeonly_success_immediateScheduling() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger = TestStream()
var observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
observation.requiresWriteAccess = true
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter)
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { _ in },
onChange: { _ in
try! dbWriter.write { db in
try db.execute(sql: "INSERT INTO player DEFAULT VALUES")
}
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings.prefix(7), [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegion)",
"database did change",
"will fetch",
"did receive value: Optional(1)"])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func test_writeonly_immediateFailure_asynchronousScheduling() throws {
func test(_ dbWriter: DatabaseWriter) throws {
let logger = TestStream()
var observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
observation.requiresWriteAccess = true
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbWriter,
scheduling: .async(onQueue: .main),
onError: { _ in expectation.fulfill() },
onChange: { _ in })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func test_writeonly_immediateFailure_immediateScheduling() throws {
func test(_ dbWriter: DatabaseWriter) throws {
let logger = TestStream()
var observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
observation.requiresWriteAccess = true
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { _ in expectation.fulfill() },
onChange: { _ in })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func test_writeonly_lateFailure_asynchronousScheduling() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger = TestStream()
var observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
observation.requiresWriteAccess = true
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbWriter,
scheduling: .async(onQueue: .main),
onError: { _ in expectation.fulfill() },
onChange: { _ in
try! dbWriter.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
DROP TABLE player;
""")
}
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegion)",
"database did change",
"will fetch",
"did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func test_writeonly_lateFailure_immediateScheduling() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger = TestStream()
var observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger)
observation.requiresWriteAccess = true
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbWriter)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { _ in expectation.fulfill() },
onChange: { _ in
try! dbWriter.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
DROP TABLE player;
""")
}
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegion)",
"database did change",
"will fetch",
"did fail: SQLite error 1 with statement `SELECT MAX(id) FROM player`: no such table: player"])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
// MARK: - Concurrent
func test_concurrent_success_asynchronousScheduling() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger = TestStream()
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
let observation = ValueObservation
.tracking({ db -> Int? in
if needsChange {
needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
DELETE FROM player;
""")
}
}
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player")
})
.print(to: logger)
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool)
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegion)",
"database did change",
"will fetch",
"did receive value: nil"])
}
}
func test_concurrent_success_immediateScheduling() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger = TestStream()
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
let observation = ValueObservation
.tracking({ db -> Int? in
if needsChange {
needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
DELETE FROM player;
""")
}
}
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player")
})
.print(to: logger)
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool)
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegion)",
"database did change",
"will fetch",
"did receive value: nil"])
}
}
// MARK: - Varying Database Region
func test_varyingRegion() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: """
CREATE TABLE a(id INTEGER PRIMARY KEY);
CREATE TABLE b(id INTEGER PRIMARY KEY);
CREATE TABLE choice(t TEXT);
INSERT INTO choice (t) VALUES ('a');
""")
}
let logger = TestStream()
let observation = ValueObservation
.trackingVaryingRegion({ db -> Int? in
let table = try String.fetchOne(db, sql: "SELECT t FROM choice")!
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM \(table)")
})
.print(to: logger)
let expectedRegionA = try region(sql: "SELECT MAX(id) FROM a", in: dbQueue)
let expectedRegionB = try region(sql: "SELECT MAX(id) FROM b", in: dbQueue)
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 3
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in
try! dbQueue.write { db in
try db.execute(sql: """
UPDATE choice SET t = 'b';
INSERT INTO a DEFAULT VALUES;
INSERT INTO b DEFAULT VALUES;
""")
}
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings.prefix(11), [
"will start",
"will fetch",
"did receive value: nil",
"will track region: \(expectedRegionA),choice(t)",
"database did change",
"will fetch",
"will track region: \(expectedRegionB),choice(t)",
"did receive value: Optional(1)",
"database did change",
"will fetch",
"did receive value: Optional(2)"])
}
}
// MARK: - Variations
func test_prefix() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger1 = TestStream()
let logger2 = TestStream()
let observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print("", to: logger1)
.print("log", to: logger2)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger1.strings.prefix(3), [
"will start",
"will fetch",
"did receive value: nil"])
XCTAssertEqual(logger2.strings.prefix(3), [
"log: will start",
"log: will fetch",
"log: did receive value: nil"])
}
}
func test_chain() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let logger1 = TestStream()
let logger2 = TestStream()
let observation = ValueObservation
.tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") }
.print(to: logger1)
.removeDuplicates()
.map { _ in "foo" }
.print(to: logger2)
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger1.strings.prefix(3), [
"will start",
"will fetch",
"did receive value: nil"])
XCTAssertEqual(logger2.strings.prefix(3), [
"will start",
"will fetch",
"did receive value: foo"])
}
}
func test_handleEvents() throws {
func waitFor<R: _ValueReducer>(_ observation: ValueObservation<R>) throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in
try! dbQueue.write { db in
try db.execute(sql: "INSERT INTO player DEFAULT VALUES")
}
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
}
func waitForError<R: _ValueReducer>(_ observation: ValueObservation<R>) throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { _ in expectation.fulfill() },
onChange: { _ in
try! dbQueue.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
DROP TABLE player;
""")
}
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
}
func waitForCancel<R: _ValueReducer>(_ observation: ValueObservation<R>) throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
}
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { _ in },
onChange: { _ in
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
cancellable.cancel()
}
}
let observation = ValueObservation.tracking {
try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player")
}
do {
let logger = TestStream()
try waitFor(observation.handleEvents(willStart: { logger.write("start") }))
XCTAssertEqual(logger.strings, ["start"])
}
do {
let logger = TestStream()
try waitFor(observation.handleEvents(willTrackRegion: { _ in logger.write("region") }))
XCTAssertEqual(logger.strings, ["region"])
}
do {
let logger = TestStream()
try waitFor(observation.handleEvents(databaseDidChange: { logger.write("change") }))
XCTAssertEqual(logger.strings.prefix(1), ["change"])
}
do {
let logger = TestStream()
try waitFor(observation.handleEvents(willFetch: { logger.write("fetch") }))
XCTAssertEqual(logger.strings.prefix(2), ["fetch", "fetch"])
}
do {
let logger = TestStream()
try waitFor(observation.handleEvents(didReceiveValue: { _ in logger.write("value") }))
XCTAssertEqual(logger.strings.prefix(2), ["value", "value"])
}
do {
let logger = TestStream()
try waitForError(observation.handleEvents(didFail: { _ in logger.write("error") }))
XCTAssertEqual(logger.strings, ["error"])
}
do {
let logger = TestStream()
try waitForCancel(observation.handleEvents(didCancel: { logger.write("cancel") }))
XCTAssertEqual(logger.strings, ["cancel"])
}
}
}
@@ -135,20 +135,21 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingVaryingRegion { db -> Int in
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
}
var regions: [DatabaseRegion] = []
let observation = ValueObservation
.trackingVaryingRegion({ db -> Int in
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
})
.handleEvents(willTrackRegion: { regions.append($0) })
let observer = dbQueue._addWriteOnly(
observation: observation,
scheduling: .immediate,
let observer = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
results.append(count)
notificationExpectation.fulfill()
})
XCTAssertEqual(observer.observedRegion!.description, "a(value),source(name)")
results.append(count)
notificationExpectation.fulfill()
})
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
@@ -163,7 +164,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [0, 1, 2, 3])
XCTAssertEqual(observer.observedRegion!.description, "b(value),source(name)")
XCTAssertEqual(regions.map(\.description), [
"a(value),source(name)",
"b(value),source(name)"])
}
}
@@ -183,13 +186,16 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingVaryingRegion { db -> Int in
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
}
var regions: [DatabaseRegion] = []
let observation = ValueObservation
.trackingVaryingRegion({ db -> Int in
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
})
.handleEvents(willTrackRegion: { regions.append($0) })
let observer = dbQueue._addWriteOnly(
observation: observation,
let observer = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
@@ -197,8 +203,6 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
notificationExpectation.fulfill()
})
// Can't test observedRegion because it is defined asynchronously
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO a VALUES (1)") // 1
@@ -212,7 +216,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [0, 1, 2, 3])
XCTAssertEqual(observer.observedRegion!.description, "b(value),source(name)")
XCTAssertEqual(regions.map(\.description), [
"a(value),source(name)",
"b(value),source(name)"])
}
}
}
+14 -5
View File
@@ -90,13 +90,22 @@ class ValueObservationTests: GRDBTestCase {
// Test that view v is not included in the observed region.
// This optimization helps observation of views that feed from a
// single table.
let observation = ValueObservation.tracking(request.fetchAll)
let observer = dbQueue._addWriteOnly(
observation: observation,
scheduling: .immediate, // So that we can test the observedRegion
var region: DatabaseRegion?
let expectation = self.expectation(description: "")
let observation = ValueObservation
.tracking(request.fetchAll)
.handleEvents(willTrackRegion: {
region = $0
expectation.fulfill()
})
let observer = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { _ in })
XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked
withExtendedLifetime(observer) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(region!.description, "t(id,name)") // view is NOT tracked
}
}
// MARK: - Snapshot Optimization