mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge pull request #455 from groue/feature/DatabaseRegionObserver
DatabaseRegionObservation
This commit is contained in:
12 files changed
+762
-342
No files matched your search
@@ -57,6 +57,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/).
|
||||
- [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap
|
||||
- [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer
|
||||
- [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged
|
||||
- [#455](https://github.com/groue/GRDB.swift/pull/455): DatabaseRegionObservation
|
||||
- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue
|
||||
- ValueObservation methods which used to accept a variadic list of observed regions now also accept an array.
|
||||
- ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired.
|
||||
@@ -66,6 +67,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/).
|
||||
|
||||
- [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method.
|
||||
- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine`, `ValueObservation.compactMap`, and `Value.distinctUntilChanged` methods.
|
||||
- [DatabaseRegionObservation](README.md#databaseregionobservation): this chapter describes the new `DatabaseRegionObservation` type.
|
||||
|
||||
|
||||
### API diff
|
||||
@@ -119,6 +121,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/).
|
||||
+ var qos: DispatchQoS
|
||||
+ var targetQueue: DispatchQueue?
|
||||
}
|
||||
|
||||
+struct DatabaseRegionObservation {
|
||||
+ var extent: Database.TransactionObservationExtent
|
||||
+ init(tracking regions: DatabaseRegionConvertible...)
|
||||
+ init(tracking regions: [DatabaseRegionConvertible])
|
||||
+ func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver
|
||||
+}
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -217,6 +217,11 @@
|
||||
564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
|
||||
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
@@ -982,6 +987,8 @@
|
||||
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
|
||||
564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
|
||||
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
|
||||
@@ -1724,6 +1731,7 @@
|
||||
560A37A91C90084600949E71 /* DatabasePool */,
|
||||
563363BB1C93FD32000BE133 /* DatabaseQueue */,
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1821,6 +1829,7 @@
|
||||
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
|
||||
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
|
||||
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
@@ -2477,6 +2486,7 @@
|
||||
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
565490CE1D5AE252005622CB /* NSNull.swift in Sources */,
|
||||
565490E41D5AE252005622CB /* TableRecord.swift in Sources */,
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
|
||||
566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
@@ -2714,6 +2724,7 @@
|
||||
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */,
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
@@ -2872,6 +2883,7 @@
|
||||
56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */,
|
||||
@@ -3051,6 +3063,7 @@
|
||||
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
@@ -3142,6 +3155,7 @@
|
||||
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
|
||||
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
|
||||
56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
|
||||
@@ -18,15 +18,15 @@
|
||||
///
|
||||
/// - `SelectStatement.databaseRegion`:
|
||||
///
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
|
||||
/// print(statement.databaseRegion)
|
||||
/// // prints "player(name,score)"
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
|
||||
/// print(statement.databaseRegion)
|
||||
/// // prints "player(name,score)"
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try print(request.databaseRegion(db))
|
||||
/// // prints "player(*)[1]"
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try print(request.databaseRegion(db))
|
||||
/// // prints "player(*)[1]"
|
||||
///
|
||||
/// Database regions returned by requests can be more precise than regions
|
||||
/// returned by select statements. Especially, regions returned by statements
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/// DatabaseRegionObservation tracks changes in the results of database
|
||||
/// requests, and notifies each database transaction whenever the
|
||||
/// database changes.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all)
|
||||
/// let observer = try observation.start(in: dbQueue) { db: Database in
|
||||
/// print("Players have changed.")
|
||||
/// }
|
||||
public struct DatabaseRegionObservation {
|
||||
/// The extent of the database observation. The default is
|
||||
/// `.observerLifetime`: the observation lasts until the
|
||||
/// observer returned by the `start(in:onChange:)` method
|
||||
/// is deallocated.
|
||||
public var extent = Database.TransactionObservationExtent.observerLifetime
|
||||
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
var observedRegion: (Database) throws -> DatabaseRegion
|
||||
|
||||
// Not public because we foster DatabaseRegionConvertible.
|
||||
init(tracking region: @escaping (Database) throws -> DatabaseRegion) {
|
||||
self.observedRegion = { db in
|
||||
// Remove views from the observed region.
|
||||
//
|
||||
// We can do it because we are only interested in modifications in
|
||||
// actual tables. And we want to do it because we have a fast path
|
||||
// for simple regions that span a single table.
|
||||
let views = try db.schema().names(ofType: .view)
|
||||
return try region(db).ignoring(views)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the observer returned by `start` is
|
||||
/// deallocated. See the `extent` property for more information.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: DatabaseRegionConvertible...) {
|
||||
self.init(tracking: regions)
|
||||
}
|
||||
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the observer returned by `start` is
|
||||
/// deallocated. See the `extent` property for more information.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: [DatabaseRegionConvertible]) {
|
||||
self.init(tracking: DatabaseRegion.union(regions))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// Starts the observation in the provided database writer (such as
|
||||
/// a database queue or database pool), and returns a transaction observer.
|
||||
///
|
||||
/// - parameter reader: A DatabaseWriter.
|
||||
/// - parameter onChange: A closure that is provided a database connection
|
||||
/// with write access each time the observed region has been modified.
|
||||
/// - returns: a TransactionObserver
|
||||
public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver {
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
|
||||
let region = try observedRegion(db)
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
|
||||
db.add(transactionObserver: observer, extent: extent)
|
||||
return observer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseRegionObserver: TransactionObserver {
|
||||
let region: DatabaseRegion
|
||||
let onChange: (Database) -> Void
|
||||
var isChanged = false
|
||||
|
||||
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
|
||||
self.region = region
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if region.isModified(by: event) {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
guard isChanged else { return }
|
||||
isChanged = false
|
||||
|
||||
onChange(db)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
isChanged = false
|
||||
}
|
||||
}
|
||||
@@ -124,7 +124,7 @@ public struct DatabaseValuesReducer<Request: FetchRequest>: ValueReducer
|
||||
public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder]? {
|
||||
if let previousDbValues = previousDbValues, previousDbValues == dbValues {
|
||||
// Don't notify consecutive identical dbValue arrays
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
}
|
||||
self.previousDbValues = dbValues
|
||||
@@ -158,7 +158,7 @@ public struct DatabaseValueReducer<Request: FetchRequest>: ValueReducer
|
||||
public mutating func value(_ dbValue: DatabaseValue?) -> Request.RowDecoder?? {
|
||||
if let previousDbValue = previousDbValue, previousDbValue == dbValue {
|
||||
// Don't notify consecutive identical dbValue
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
}
|
||||
self.previousDbValue = dbValue
|
||||
@@ -169,7 +169,7 @@ public struct DatabaseValueReducer<Request: FetchRequest>: ValueReducer
|
||||
return .some(value)
|
||||
} else if previousValueWasNil {
|
||||
// Don't notify consecutive nil values
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
} else {
|
||||
previousValueWasNil = true
|
||||
@@ -203,7 +203,7 @@ public struct OptionalDatabaseValuesReducer<Request: FetchRequest>: ValueReducer
|
||||
public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder._Wrapped?]? {
|
||||
if let previousDbValues = previousDbValues, previousDbValues == dbValues {
|
||||
// Don't notify consecutive identical dbValue arrays
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
}
|
||||
self.previousDbValues = dbValues
|
||||
|
||||
@@ -91,7 +91,7 @@ public struct FetchableRecordsReducer<Request: FetchRequest>: ValueReducer
|
||||
public mutating func value(_ rows: [Row]) -> [Request.RowDecoder]? {
|
||||
if let previousRows = previousRows, previousRows == rows {
|
||||
// Don't notify consecutive identical row arrays
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
}
|
||||
self.previousRows = rows
|
||||
@@ -122,7 +122,7 @@ public struct FetchableRecordReducer<Request: FetchRequest>: ValueReducer
|
||||
public mutating func value(_ row: Row?) -> Request.RowDecoder?? {
|
||||
if let previousRow = previousRow, previousRow == row {
|
||||
// Don't notify consecutive identical rows
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
}
|
||||
self.previousRow = row
|
||||
|
||||
@@ -120,7 +120,7 @@ public struct RowReducer<Request: FetchRequest>: ValueReducer
|
||||
public mutating func value(_ row: Row?) -> Row?? {
|
||||
if let previousRow = previousRow, previousRow == row {
|
||||
// Don't notify consecutive identical rows
|
||||
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
|
||||
// TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4
|
||||
return nil
|
||||
}
|
||||
self.previousRow = row
|
||||
|
||||
@@ -164,7 +164,8 @@ public struct ValueObservation<Reducer> {
|
||||
}
|
||||
}
|
||||
|
||||
// Not public. See ValueObservation.tracking(_:reducer:)
|
||||
// Not public because we foster DatabaseRegionConvertible.
|
||||
// See ValueObservation.tracking(_:reducer:)
|
||||
init(
|
||||
tracking region: @escaping (Database) throws -> DatabaseRegion,
|
||||
reducer: @escaping (Database) throws -> Reducer)
|
||||
|
||||
@@ -276,6 +276,12 @@
|
||||
564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; };
|
||||
564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5C121B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564CE5C221B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564CE5C321B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564CE5C421B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
|
||||
564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
|
||||
564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
|
||||
@@ -1093,6 +1099,8 @@
|
||||
564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
|
||||
564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
|
||||
564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
|
||||
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
|
||||
@@ -1790,6 +1798,7 @@
|
||||
560A37A91C90084600949E71 /* DatabasePool */,
|
||||
563363BB1C93FD32000BE133 /* DatabaseQueue */,
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1887,6 +1896,7 @@
|
||||
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
|
||||
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
|
||||
569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
@@ -2409,6 +2419,7 @@
|
||||
566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */,
|
||||
5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */,
|
||||
5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */,
|
||||
569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */,
|
||||
@@ -2564,6 +2575,7 @@
|
||||
565EFAEF1D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
|
||||
560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C121B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */,
|
||||
564CE4EC21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
|
||||
@@ -2743,6 +2755,7 @@
|
||||
561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */,
|
||||
565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
|
||||
5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C221B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
564CE4ED21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */,
|
||||
@@ -2894,6 +2907,7 @@
|
||||
566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */,
|
||||
5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */,
|
||||
5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */,
|
||||
569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */,
|
||||
@@ -3049,6 +3063,7 @@
|
||||
56AFCA631CB1AA9900F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
|
||||
5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C321B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
564CE4EE21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
@@ -3228,6 +3243,7 @@
|
||||
56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
|
||||
5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C421B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564CE4EF21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */,
|
||||
|
||||
@@ -107,6 +107,10 @@
|
||||
564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; };
|
||||
564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
|
||||
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; };
|
||||
564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; };
|
||||
564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
@@ -730,6 +734,8 @@
|
||||
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
|
||||
564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
|
||||
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
|
||||
@@ -1400,6 +1406,7 @@
|
||||
560A37A91C90084600949E71 /* DatabasePool */,
|
||||
563363BB1C93FD32000BE133 /* DatabaseQueue */,
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1497,6 +1504,7 @@
|
||||
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
|
||||
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
|
||||
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
@@ -2048,6 +2056,7 @@
|
||||
566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */,
|
||||
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */,
|
||||
5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */,
|
||||
569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */,
|
||||
@@ -2203,6 +2212,7 @@
|
||||
F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */,
|
||||
564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
@@ -2354,6 +2364,7 @@
|
||||
566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */,
|
||||
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */,
|
||||
5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */,
|
||||
569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */,
|
||||
@@ -2509,6 +2520,7 @@
|
||||
F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */,
|
||||
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
|
||||
564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */,
|
||||
5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
|
||||
@@ -2061,7 +2061,7 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
|
||||
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.5/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.5/Classes/Database.html)
|
||||
- `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections)
|
||||
- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [ValueObservation], [FetchedRecordsController]
|
||||
- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController]
|
||||
- `sqlite3_config`: see [Error Log](#error-log)
|
||||
- `sqlite3_create_collation_v2`: see [String Comparison](#string-comparison)
|
||||
- `sqlite3_db_release_memory`: see [Memory Management](#memory-management)
|
||||
@@ -4571,7 +4571,7 @@ The `prepare` method returns a prepared statement and an optional row adapter. T
|
||||
|
||||
The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation.
|
||||
|
||||
The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion](#databaseregion), and [ValueObservation].
|
||||
The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion], [DatabaseRegionObservation], and [ValueObservation].
|
||||
|
||||
The FetchRequest protocol is adopted, for example, by [query interface requests](#requests):
|
||||
|
||||
@@ -5846,10 +5846,10 @@ 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): The simplest way to handle successful transactions.
|
||||
- [After Commit Hook](#after-commit-hook): Handle successful transactions one by one.
|
||||
- [ValueObservation and DatabaseRegionObservation]: Automated tracking of database requests.
|
||||
- [FetchedRecordsController]: Animate table views according to database changes.
|
||||
- [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation.
|
||||
- [ValueObservation]: Automated tracking of database changes.
|
||||
- [FetchedRecordsController]: Automated tracking of database changes, with table view animations.
|
||||
- [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift).
|
||||
|
||||
Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage.
|
||||
@@ -5914,343 +5914,131 @@ try dbQueue.write { db in
|
||||
```
|
||||
|
||||
|
||||
## TransactionObserver Protocol
|
||||
## ValueObservation and DatabaseRegionObservation
|
||||
|
||||
The `TransactionObserver` protocol lets you **observe database changes and transactions**:
|
||||
**ValueObservation and DatabaseRegionObservation** are two database observations tools that track changes in database [requests](#requests):
|
||||
|
||||
```swift
|
||||
protocol TransactionObserver : class {
|
||||
/// Notifies a database change:
|
||||
/// - event.kind (insert, update, or delete)
|
||||
/// - event.tableName
|
||||
/// - event.rowID
|
||||
///
|
||||
/// For performance reasons, the event is only valid for the duration of
|
||||
/// this method call. If you need to keep it longer, store a copy:
|
||||
/// event.copy().
|
||||
func databaseDidChange(with event: DatabaseEvent)
|
||||
|
||||
/// Filters the database changes that should be notified to the
|
||||
/// `databaseDidChange(with:)` method.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// An opportunity to rollback pending changes by throwing an error.
|
||||
func databaseWillCommit() throws
|
||||
|
||||
/// Database changes have been committed.
|
||||
func databaseDidCommit(_ db: Database)
|
||||
|
||||
/// Database changes have been rollbacked.
|
||||
func databaseDidRollback(_ db: Database)
|
||||
}
|
||||
// Two observations that track the players:
|
||||
let request = Player.all()
|
||||
let valueObservation = ValueObservation.trackingAll(request)
|
||||
let regionObservation = DatabaseRegionObservation(tracking: request)
|
||||
```
|
||||
|
||||
- [Activate a Transaction Observer](#activate-a-transaction-observer)
|
||||
- [Database Changes And Transactions](#database-changes-and-transactions)
|
||||
- [Filtering Database Events](#filtering-database-events)
|
||||
- [Observation Extent](#observation-extent)
|
||||
- [DatabaseRegion](#databaseregion)
|
||||
- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
|
||||
|
||||
|
||||
### Activate a Transaction Observer
|
||||
|
||||
**To activate a transaction observer, add it to the database queue or pool:**
|
||||
[ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:):
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
```
|
||||
|
||||
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See [Observation Extent](#observation-extent) for more options.
|
||||
|
||||
|
||||
### Database Changes And Transactions
|
||||
|
||||
**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
> :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
|
||||
Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
try db.execute("UPDATE ...") // 2. didChange
|
||||
} // 3. willCommit, 4. didCommit
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
try db.execute("UPDATE ...") // 2. didChange
|
||||
return .rollback // 3. didRollback
|
||||
let observer = valueObservation.start(in: dbQueue) { players: [Player] in
|
||||
print("Player have changed: \(players)")
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
throw SomeError()
|
||||
} // 2. didRollback
|
||||
try Player(name: "Arthur").insert(db)
|
||||
}
|
||||
// Prints "Players have changed: ..."
|
||||
|
||||
```
|
||||
|
||||
Database statements that are executed outside of any transaction do not drop off the radar:
|
||||
[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for advanced use cases :nerd_face:):
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
let observer = regionObservation.start(in: dbQueue) { db: Database in
|
||||
print("Player have changed.")
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try Player(name: "Barbara").insert(db)
|
||||
}
|
||||
// Prints "Players have changed."
|
||||
```
|
||||
|
||||
|
||||
## DatabaseRegionObservation
|
||||
|
||||
**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).**
|
||||
|
||||
No insertion, update, or deletion in the 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).
|
||||
|
||||
DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation.
|
||||
|
||||
|
||||
### DatabaseRegionObservation Usage
|
||||
|
||||
Define an observation by providing one or several requests to track:
|
||||
|
||||
```swift
|
||||
// Track all players
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
```
|
||||
|
||||
Then start the observation from a [database queue](#database-queues) or [pool](#database-pools):
|
||||
|
||||
```swift
|
||||
let observer = observation.start(in: dbQueue) { db: Database in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed:
|
||||
And enjoy the changes notifications:
|
||||
|
||||
```swift
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
|
||||
try db.execute("SAVEPOINT foo")
|
||||
try db.execute("UPDATE ...") // delayed
|
||||
try db.execute("UPDATE ...") // delayed
|
||||
try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
|
||||
try db.execute("SAVEPOINT foo")
|
||||
try db.execute("UPDATE ...") // not notified
|
||||
try db.execute("ROLLBACK TO SAVEPOINT foo")
|
||||
|
||||
return .commit // 4. willCommit, 5. didCommit
|
||||
try dbQueue.write { db in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
}
|
||||
// Prints "Players were changed"
|
||||
```
|
||||
|
||||
By default, the observation lasts until the observer returned by the `start` method is deallocated. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details.
|
||||
|
||||
You can also feed DatabaseRegionObservation with [DatabaseRegion], or any type which conforms to the [DatabaseRegionConvertible] protocol. For example:
|
||||
|
||||
```swift
|
||||
// Observe the full database
|
||||
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
|
||||
let observer = observation.start(in: dbQueue) { db: Database in
|
||||
print("Database was changed")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code:
|
||||
### 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 want 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:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbQueue.inTransaction { db in
|
||||
...
|
||||
return .commit // 1. willCommit (throws), 2. didRollback
|
||||
}
|
||||
} catch {
|
||||
// 3. The error thrown by the transaction observer.
|
||||
}
|
||||
// This observation lasts until the database connection is closed
|
||||
var observation = DatabaseRegionObservation...
|
||||
observation.extent = .databaseLifetime
|
||||
_ = observation.start(in: dbQueue) { db in ... }
|
||||
```
|
||||
|
||||
> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates.
|
||||
>
|
||||
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
|
||||
The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deallocated.
|
||||
|
||||
|
||||
[ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol.
|
||||
|
||||
See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.
|
||||
|
||||
|
||||
### Filtering Database Events
|
||||
|
||||
**Transaction observers can avoid being notified of database changes they are not interested in.**
|
||||
|
||||
The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table:
|
||||
Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Only observe changes to the "player" table.
|
||||
return eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
// This method is only called for changes that happen to
|
||||
// the "player" table.
|
||||
}
|
||||
}
|
||||
```
|
||||
// Start
|
||||
let observer = observation.start(in: dbQueue) { db in ... }
|
||||
|
||||
Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed:
|
||||
|
||||
```swift
|
||||
class PlayerScoreObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Only observe changes to the "score" column of the "player" table.
|
||||
switch eventKind {
|
||||
case .insert(let tableName):
|
||||
return tableName == "player"
|
||||
case .delete(let tableName):
|
||||
return tableName == "player"
|
||||
case .update(let tableName, let columnNames):
|
||||
return tableName == "player" && columnNames.contains("score")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks:
|
||||
|
||||
```swift
|
||||
class PureTransactionObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Ignore all individual changes
|
||||
return false
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) { /* Never called */ }
|
||||
func databaseWillCommit() throws { /* Called before commit */ }
|
||||
func databaseDidRollback(_ db: Database) { /* Called on rollback */ }
|
||||
func databaseDidCommit(_ db: Database) { /* Called on commit */ }
|
||||
}
|
||||
```
|
||||
|
||||
For more information about event filtering, see [DatabaseRegion](#databaseregion).
|
||||
|
||||
|
||||
### Observation Extent
|
||||
|
||||
**You can specify how long an observer is notified of database changes and transactions.**
|
||||
|
||||
The `remove(transactionObserver:)` method explicitly stops notifications, at any time:
|
||||
|
||||
```swift
|
||||
// From a database queue or pool:
|
||||
// Stop
|
||||
dbQueue.remove(transactionObserver: observer)
|
||||
|
||||
// From a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.remove(transactionObserver: observer)
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method:
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
|
||||
// On a database queue or pool:
|
||||
dbQueue.add(transactionObserver: observer) // default extent
|
||||
dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
// On a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.add(transactionObserver: ...)
|
||||
}
|
||||
```
|
||||
|
||||
- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions.
|
||||
|
||||
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification.
|
||||
|
||||
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
|
||||
|
||||
Finally, an observer may ignore all database changes until the end of the current transaction:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
var playerTableWasModified = false
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
playerTableWasModified = true
|
||||
|
||||
// It is pointless to keep on tracking further changes:
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.
|
||||
|
||||
|
||||
### DatabaseRegion
|
||||
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
|
||||
|
||||
A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region.
|
||||
|
||||
You start by building regions:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let teamRegion = try Team.filter(key: 1).databaseRegion(db)
|
||||
let playersRegion = try SQLRequest<Player>("SELECT * FROM player").databaseRegion(db)
|
||||
let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db)
|
||||
```
|
||||
|
||||
You can group regions:
|
||||
|
||||
```swift
|
||||
let region = teamRegion.union(playersRegion).union(maxScoreRegion)
|
||||
}
|
||||
```
|
||||
|
||||
There are two special regions: `DatabaseRegion()` (the empty region), and `DatabaseRegion.fullDatabase` (the region that spans the whole database).
|
||||
|
||||
Regions feed the `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods of transaction observers. For example:
|
||||
|
||||
```swift
|
||||
// A transaction observer which notifies all changes to a database region.
|
||||
class DatabaseRegionObserver: TransactionObserver {
|
||||
let region: DatabaseRegion
|
||||
var regionIsModified = false
|
||||
|
||||
init(region: DatabaseRegion) {
|
||||
self.region = region
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if region.isModified(by: event) {
|
||||
regionIsModified = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
regionIsModified = false
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
if regionIsModified == false { return }
|
||||
regionIsModified = false
|
||||
|
||||
// You'll customize your handling of changes here:
|
||||
print("Region has been modified.")
|
||||
}
|
||||
}
|
||||
|
||||
// Observe a region
|
||||
try dbQueue.write { db in
|
||||
observer = DatabaseRegionObserver(region: region)
|
||||
db.add(transactionObserver: observer)
|
||||
}
|
||||
```
|
||||
|
||||
A region notifies *potential* changes, not *actual* changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row.
|
||||
|
||||
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
|
||||
|
||||
Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key *is* the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42.
|
||||
|
||||
|
||||
### Support for SQLite Pre-Update Hooks
|
||||
|
||||
A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
|
||||
|
||||
```swift
|
||||
protocol TransactionObserverType : class {
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Notifies before a database change (insert, update, or delete)
|
||||
/// with change information (initial / final values for the row's
|
||||
/// columns).
|
||||
///
|
||||
/// The event is only valid for the duration of this method call. If you
|
||||
/// need to keep it longer, store a copy: event.copy().
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -6264,11 +6052,7 @@ Changes are only notified after they have been committed in the database. No ins
|
||||
- **[ValueObservation Usage](#valueobservation-usage)**
|
||||
- [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall)
|
||||
- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch)
|
||||
- [ValueObservation Transformations](#valueobservation-transformations)
|
||||
- [ValueObservation.map](#valueobservationmap)
|
||||
- [ValueObservation.compactMap](#valueobservationcompactmap)
|
||||
- [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged)
|
||||
- [ValueObservation.combine(...)](#valueobservationcombine)
|
||||
- [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ...
|
||||
- [ValueObservation Error Handling](#valueobservation-error-handling)
|
||||
- [ValueObservation Options](#valueobservation-options)
|
||||
- [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer)
|
||||
@@ -6459,19 +6243,11 @@ let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in
|
||||
```
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
#### DatabaseRegionConvertible Observation
|
||||
|
||||
The initial parameter of the `ValueObservation.tracking(_:fetch:)` and `ValueObservation.tracking(_:fetchDistinct:)` methods can be fed with requests, and generally speaking, values that adopt the **DatabaseRegionConvertible** protocol.
|
||||
The initial parameter of the `ValueObservation.tracking(_:fetch:)` method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol.
|
||||
|
||||
```swift
|
||||
protocol DatabaseRegionConvertible {
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
[DatabaseRegion](#databaseregion) is a type that helps observing the database.
|
||||
|
||||
Use this protocol when you want to encapsulate your complex requests in a dedicated type. In the sample code below, `TeamInfoRequest` is not only able to fetch a team and its players, but also to be observed.
|
||||
Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed.
|
||||
|
||||
```swift
|
||||
struct TeamInfo {
|
||||
@@ -6512,7 +6288,7 @@ let request = TeamInfoRequest(teamId: 1)
|
||||
// Simple fetch
|
||||
let teamInfo: TeamInfo? = try dbQueue.read(request.fetch)
|
||||
|
||||
// Observatin
|
||||
// Observation
|
||||
let observer = ValueObservation
|
||||
.tracking(request, fetch: request.fetch)
|
||||
.start(in: dbQueue) { teamInfo: TeamInfo? in
|
||||
@@ -6803,6 +6579,7 @@ try dbQueue.write { db in
|
||||
```
|
||||
|
||||
|
||||
|
||||
## FetchedRecordsController
|
||||
|
||||
**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.**
|
||||
@@ -7143,6 +6920,304 @@ try controller.performFetch()
|
||||
> ```
|
||||
|
||||
|
||||
## TransactionObserver Protocol
|
||||
|
||||
The `TransactionObserver` protocol lets you **observe individual database changes and transactions**:
|
||||
|
||||
```swift
|
||||
protocol TransactionObserver : class {
|
||||
/// Notifies a database change:
|
||||
/// - event.kind (insert, update, or delete)
|
||||
/// - event.tableName
|
||||
/// - event.rowID
|
||||
///
|
||||
/// For performance reasons, the event is only valid for the duration of
|
||||
/// this method call. If you need to keep it longer, store a copy:
|
||||
/// event.copy().
|
||||
func databaseDidChange(with event: DatabaseEvent)
|
||||
|
||||
/// Filters the database changes that should be notified to the
|
||||
/// `databaseDidChange(with:)` method.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// An opportunity to rollback pending changes by throwing an error.
|
||||
func databaseWillCommit() throws
|
||||
|
||||
/// Database changes have been committed.
|
||||
func databaseDidCommit(_ db: Database)
|
||||
|
||||
/// Database changes have been rollbacked.
|
||||
func databaseDidRollback(_ db: Database)
|
||||
}
|
||||
```
|
||||
|
||||
- [Activate a Transaction Observer](#activate-a-transaction-observer)
|
||||
- [Database Changes And Transactions](#database-changes-and-transactions)
|
||||
- [Filtering Database Events](#filtering-database-events)
|
||||
- [Observation Extent](#observation-extent)
|
||||
- [DatabaseRegion]
|
||||
- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
|
||||
|
||||
|
||||
### Activate a Transaction Observer
|
||||
|
||||
**To activate a transaction observer, add it to the database queue or pool:**
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
```
|
||||
|
||||
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See [Observation Extent](#observation-extent) for more options.
|
||||
|
||||
|
||||
### Database Changes And Transactions
|
||||
|
||||
**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
> :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
|
||||
Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
try db.execute("UPDATE ...") // 2. didChange
|
||||
} // 3. willCommit, 4. didCommit
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
try db.execute("UPDATE ...") // 2. didChange
|
||||
return .rollback // 3. didRollback
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
throw SomeError()
|
||||
} // 2. didRollback
|
||||
```
|
||||
|
||||
Database statements that are executed outside of any transaction do not drop off the radar:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
}
|
||||
```
|
||||
|
||||
Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed:
|
||||
|
||||
```swift
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("INSERT ...") // 1. didChange
|
||||
|
||||
try db.execute("SAVEPOINT foo")
|
||||
try db.execute("UPDATE ...") // delayed
|
||||
try db.execute("UPDATE ...") // delayed
|
||||
try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
|
||||
try db.execute("SAVEPOINT foo")
|
||||
try db.execute("UPDATE ...") // not notified
|
||||
try db.execute("ROLLBACK TO SAVEPOINT foo")
|
||||
|
||||
return .commit // 4. willCommit, 5. didCommit
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbQueue.inTransaction { db in
|
||||
...
|
||||
return .commit // 1. willCommit (throws), 2. didRollback
|
||||
}
|
||||
} catch {
|
||||
// 3. The error thrown by the transaction observer.
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates.
|
||||
>
|
||||
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
|
||||
|
||||
|
||||
[DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol.
|
||||
|
||||
See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.
|
||||
|
||||
|
||||
### Filtering Database Events
|
||||
|
||||
**Transaction observers can avoid being notified of database changes they are not interested in.**
|
||||
|
||||
The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Only observe changes to the "player" table.
|
||||
return eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
// This method is only called for changes that happen to
|
||||
// the "player" table.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed:
|
||||
|
||||
```swift
|
||||
class PlayerScoreObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Only observe changes to the "score" column of the "player" table.
|
||||
switch eventKind {
|
||||
case .insert(let tableName):
|
||||
return tableName == "player"
|
||||
case .delete(let tableName):
|
||||
return tableName == "player"
|
||||
case .update(let tableName, let columnNames):
|
||||
return tableName == "player" && columnNames.contains("score")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks:
|
||||
|
||||
```swift
|
||||
class PureTransactionObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Ignore all individual changes
|
||||
return false
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) { /* Never called */ }
|
||||
func databaseWillCommit() throws { /* Called before commit */ }
|
||||
func databaseDidRollback(_ db: Database) { /* Called on rollback */ }
|
||||
func databaseDidCommit(_ db: Database) { /* Called on commit */ }
|
||||
}
|
||||
```
|
||||
|
||||
For more information about event filtering, see [DatabaseRegion].
|
||||
|
||||
|
||||
### Observation Extent
|
||||
|
||||
**You can specify how long an observer is notified of database changes and transactions.**
|
||||
|
||||
The `remove(transactionObserver:)` method explicitly stops notifications, at any time:
|
||||
|
||||
```swift
|
||||
// From a database queue or pool:
|
||||
dbQueue.remove(transactionObserver: observer)
|
||||
|
||||
// From a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.remove(transactionObserver: observer)
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method:
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
|
||||
// On a database queue or pool:
|
||||
dbQueue.add(transactionObserver: observer) // default extent
|
||||
dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
// On a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.add(transactionObserver: ...)
|
||||
}
|
||||
```
|
||||
|
||||
- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions.
|
||||
|
||||
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification.
|
||||
|
||||
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
|
||||
|
||||
Finally, an observer may ignore all database changes until the end of the current transaction:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
var playerTableWasModified = false
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
playerTableWasModified = true
|
||||
|
||||
// It is pointless to keep on tracking further changes:
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.
|
||||
|
||||
|
||||
### DatabaseRegion
|
||||
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
|
||||
|
||||
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
|
||||
|
||||
DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservation].
|
||||
|
||||
**A region notifies *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row.
|
||||
|
||||
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
|
||||
|
||||
Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key is the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42.
|
||||
|
||||
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
|
||||
**DatabaseRegionConvertible** is a protocol for all types that can turn into a [DatabaseRegion]:
|
||||
|
||||
```swift
|
||||
protocol DatabaseRegionConvertible {
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
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 observation APIs. See [DatabaseRegionConvertible Observation](#databaseregionconvertible-observation) for more information.
|
||||
|
||||
|
||||
### Support for SQLite Pre-Update Hooks
|
||||
|
||||
A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
|
||||
|
||||
```swift
|
||||
protocol TransactionObserverType : class {
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Notifies before a database change (insert, update, or delete)
|
||||
/// with change information (initial / final values for the row's
|
||||
/// columns).
|
||||
///
|
||||
/// The event is only valid for the duration of this method call. If you
|
||||
/// need to keep it longer, store a copy: event.copy().
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Encryption
|
||||
==========
|
||||
|
||||
@@ -7957,6 +8032,7 @@ Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.gith
|
||||
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
|
||||
|
||||
- [Migrations](#migrations)
|
||||
- [DatabaseRegionObservation]
|
||||
- [ValueObservation]
|
||||
- [FetchedRecordsController]
|
||||
- [RxGRDB]
|
||||
@@ -8519,5 +8595,9 @@ This chapter has been renamed [Beyond FetchableRecord].
|
||||
[Record Customization Options]: #record-customization-options
|
||||
[TableRecord]: #tablerecord-protocol
|
||||
[ValueObservation]: #valueobservation
|
||||
[DatabaseRegionObservation]: #databaseregionobservation
|
||||
[FetchedRecordsController]: #fetchedrecordscontroller
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol
|
||||
[ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation
|
||||
[DatabaseRegion]: #databaseregion
|
||||
@@ -0,0 +1,155 @@
|
||||
import XCTest
|
||||
#if GRDBCIPHER
|
||||
import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
import GRDBCustomSQLite
|
||||
#else
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#else
|
||||
import SQLite3
|
||||
#endif
|
||||
import GRDB
|
||||
#endif
|
||||
|
||||
class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
func testDatabaseRegionObservationVariadic() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write {
|
||||
try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
|
||||
try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
|
||||
}
|
||||
|
||||
let notificationExpectation = expectation(description: "notification")
|
||||
notificationExpectation.assertForOverFulfill = true
|
||||
notificationExpectation.expectedFulfillmentCount = 3
|
||||
|
||||
let request1 = SQLRequest<Row>("SELECT * FROM t1 ORDER BY id")
|
||||
let request2 = SQLRequest<Row>("SELECT * FROM t2 ORDER BY id")
|
||||
|
||||
var observation = DatabaseRegionObservation(tracking: request1, request2)
|
||||
observation.extent = .databaseLifetime
|
||||
|
||||
var count = 0
|
||||
_ = try observation.start(in: dbQueue) { db in
|
||||
count += 1
|
||||
notificationExpectation.fulfill()
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')")
|
||||
}
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')")
|
||||
}
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')")
|
||||
try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')")
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
|
||||
XCTAssertEqual(count, 3)
|
||||
}
|
||||
|
||||
func testDatabaseRegionObservationArray() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write {
|
||||
try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
|
||||
try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
|
||||
}
|
||||
|
||||
let notificationExpectation = expectation(description: "notification")
|
||||
notificationExpectation.assertForOverFulfill = true
|
||||
notificationExpectation.expectedFulfillmentCount = 3
|
||||
|
||||
let request1 = SQLRequest<Row>("SELECT * FROM t1 ORDER BY id")
|
||||
let request2 = SQLRequest<Row>("SELECT * FROM t2 ORDER BY id")
|
||||
|
||||
var observation = DatabaseRegionObservation(tracking: [request1, request2])
|
||||
observation.extent = .databaseLifetime
|
||||
|
||||
var count = 0
|
||||
_ = try observation.start(in: dbQueue) { db in
|
||||
count += 1
|
||||
notificationExpectation.fulfill()
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')")
|
||||
}
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')")
|
||||
}
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')")
|
||||
try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')")
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
|
||||
XCTAssertEqual(count, 3)
|
||||
}
|
||||
|
||||
func testDatabaseRegionDefaultExtent() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
|
||||
|
||||
let notificationExpectation = expectation(description: "notification")
|
||||
notificationExpectation.assertForOverFulfill = true
|
||||
notificationExpectation.expectedFulfillmentCount = 2
|
||||
|
||||
let observation = DatabaseRegionObservation(tracking: SQLRequest<Row>("SELECT * FROM t ORDER BY id"))
|
||||
|
||||
var count = 0
|
||||
do {
|
||||
let observer = try observation.start(in: dbQueue) { db in
|
||||
count += 1
|
||||
notificationExpectation.fulfill()
|
||||
}
|
||||
|
||||
try withExtendedLifetime(observer) {
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')")
|
||||
}
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')")
|
||||
}
|
||||
}
|
||||
}
|
||||
// not notified
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')")
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
|
||||
func testDatabaseRegionExtentNextTransaction() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
|
||||
|
||||
let notificationExpectation = expectation(description: "notification")
|
||||
notificationExpectation.assertForOverFulfill = true
|
||||
notificationExpectation.expectedFulfillmentCount = 1
|
||||
|
||||
var observation = DatabaseRegionObservation(tracking: SQLRequest<Row>("SELECT * FROM t ORDER BY id"))
|
||||
observation.extent = .nextTransaction
|
||||
|
||||
var count = 0
|
||||
_ = try observation.start(in: dbQueue) { db in
|
||||
count += 1
|
||||
notificationExpectation.fulfill()
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')")
|
||||
}
|
||||
// not notified
|
||||
try dbQueue.write { db in
|
||||
try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')")
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user