From 1e72731c076071a839d0cf2d05ec7da2d044264c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 07:04:40 +0100 Subject: [PATCH 01/15] Distinguish distinctUntilChanged from distinctUntilDatabaseChanged --- .../ValueObservation+DatabaseValueConvertible.swift | 8 ++++---- .../ValueObservation+FetchableRecord.swift | 4 ++-- GRDB/ValueObservation/ValueObservation+Row.swift | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 63577d900..de4b240d6 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -124,7 +124,7 @@ public struct DatabaseValuesReducer: 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: 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: 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: 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 diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index a9eb2431a..2a3ac9d7c 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -91,7 +91,7 @@ public struct FetchableRecordsReducer: 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: 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 diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index 011fa3aa5..e3c1f55ba 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -120,7 +120,7 @@ public struct RowReducer: 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 From 6ec4556c2ce38611fb83945ea524e1586e038050 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 07:49:41 +0100 Subject: [PATCH 02/15] DatabaseRegionObservation --- GRDB.xcodeproj/project.pbxproj | 8 +++ GRDB/Core/DatabaseRegionObservation.swift | 69 +++++++++++++++++++++++ GRDBCipher.xcodeproj/project.pbxproj | 6 ++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ 4 files changed, 89 insertions(+) create mode 100644 GRDB/Core/DatabaseRegionObservation.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index eefda912e..9b13eb1d4 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -217,6 +217,9 @@ 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 */; }; 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 +985,7 @@ 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1821,6 +1825,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */, + 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2477,6 +2482,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 +2720,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 */, @@ -3142,6 +3149,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 */, diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift new file mode 100644 index 000000000..23d756d48 --- /dev/null +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -0,0 +1,69 @@ +public final class DatabaseRegionObservation { + /// A closure that is evaluated when the observation starts, and returns + /// the observed database region. + var observedRegion: (Database) throws -> DatabaseRegion + + public 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) + } + } + + public convenience init(tracking regions: DatabaseRegionConvertible...) { + self.init(tracking: regions) + } + + public convenience init(tracking regions: [DatabaseRegionConvertible]) { + self.init(tracking: DatabaseRegion.union(regions)) + } +} + +extension DatabaseWriter { + public func add(observation: DatabaseRegionObservation, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + return try writeWithoutTransaction { db -> TransactionObserver in + let region = try observation.observedRegion(db) + let observer = DatabaseRegionObserver(region: region, onChange: onChange) + add(transactionObserver: observer) + 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 + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index c26665b2c..d43baa2b1 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -276,6 +276,8 @@ 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 */; }; 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 +1095,7 @@ 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1887,6 +1890,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */, + 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2409,6 +2413,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 */, @@ -2894,6 +2899,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 */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 564602505..7b92d899d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -107,6 +107,8 @@ 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 */; }; 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 +732,7 @@ 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1497,6 +1500,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */, + 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2048,6 +2052,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 */, @@ -2354,6 +2359,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 */, From e3681fdde5fa17790a38e56f85d5dab2e8c24008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 08:28:43 +0100 Subject: [PATCH 03/15] DatabaseRegionObservationTests --- GRDB.xcodeproj/project.pbxproj | 6 + GRDB/Core/DatabaseRegionObservation.swift | 20 +- GRDBCipher.xcodeproj/project.pbxproj | 10 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../DatabaseRegionObservationTests.swift | 195 ++++++++++++++++++ 5 files changed, 229 insertions(+), 8 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseRegionObservationTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9b13eb1d4..1782e4008 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -220,6 +220,8 @@ 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 */; }; @@ -986,6 +988,7 @@ 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1728,6 +1731,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -2879,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 */, @@ -3058,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 */, diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 23d756d48..b34afe430 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -1,4 +1,6 @@ -public final class DatabaseRegionObservation { +public struct DatabaseRegionObservation { + 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 @@ -15,21 +17,23 @@ public final class DatabaseRegionObservation { } } - public convenience init(tracking regions: DatabaseRegionConvertible...) { + public init(tracking regions: DatabaseRegionConvertible...) { self.init(tracking: regions) } - public convenience init(tracking regions: [DatabaseRegionConvertible]) { + public init(tracking regions: [DatabaseRegionConvertible]) { self.init(tracking: DatabaseRegion.union(regions)) } } -extension DatabaseWriter { - public func add(observation: DatabaseRegionObservation, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { - return try writeWithoutTransaction { db -> TransactionObserver in - let region = try observation.observedRegion(db) +extension DatabaseRegionObservation { + 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) - add(transactionObserver: observer) + db.add(transactionObserver: observer, extent: extent) return observer } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index d43baa2b1..3f14b05e5 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -278,6 +278,10 @@ 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 */; }; @@ -1096,6 +1100,7 @@ 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1793,6 +1798,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -2569,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 */, @@ -2748,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 */, @@ -3055,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 */, @@ -3234,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 */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7b92d899d..91458697c 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -109,6 +109,8 @@ 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 */; }; @@ -733,6 +735,7 @@ 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1403,6 +1406,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -2208,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 */, @@ -2515,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 */, diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift new file mode 100644 index 000000000..92e51526c --- /dev/null +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -0,0 +1,195 @@ +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 testDatabaseRegionObservation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + let request = SQLRequest("SELECT * FROM t ORDER BY id") + let observation = DatabaseRegionObservation(tracking: { db in + try request.databaseRegion(db) + }) + let observer = try observation.start(in: dbQueue) { db in + let rows = try! request.fetchAll(db) + results.append(rows) + notificationExpectation.fulfill() + } + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 + try db.execute("UPDATE t SET name = 'foo' WHERE id = 1") // = + try db.inTransaction { // +1 + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute("DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute("DELETE FROM t WHERE id = 1") // -1 + } + + waitForExpectations(timeout: 1, handler: nil) + } + + XCTAssertEqual(results, [ + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"], ["id":2, "name":"bar"]], + [["id":2, "name":"bar"]]]) + } + + 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("SELECT * FROM t1 ORDER BY id") + let request2 = SQLRequest("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("SELECT * FROM t1 ORDER BY id") + let request2 = SQLRequest("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("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("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')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 1) + } +} From 78bb086f69f4a801706a9003f06630c46b700c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 08:43:44 +0100 Subject: [PATCH 04/15] Documentation --- GRDB/Core/DatabaseRegionObservation.swift | 62 ++++++++++++++++++- GRDB/ValueObservation/ValueObservation.swift | 3 +- .../DatabaseRegionObservationTests.swift | 1 + 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index b34afe430..a55fd2b3f 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -1,11 +1,26 @@ +/// 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 - public init(tracking region: @escaping (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. // @@ -17,16 +32,61 @@ public struct DatabaseRegionObservation { } } + /// 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. diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 8c752dda3..b142571df 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -164,7 +164,8 @@ public struct ValueObservation { } } - // 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) diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index 92e51526c..aa9a99f87 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -185,6 +185,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { 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')") } From 1472385242505c50b257f6624d6f6d614087bac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 08:55:31 +0100 Subject: [PATCH 05/15] Documentation --- README.md | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4025a86a5..3aee35ba5 100644 --- a/README.md +++ b/README.md @@ -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](#databaseregion), [DatabaseRegionObservation], and [ValueObservation]. The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): @@ -5848,6 +5848,7 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas - [After Commit Hook](#after-commit-hook): The simplest way to handle successful transactions. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. +- [DatabaseRegionObservation]: Focused tracking of database transactions. - [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). @@ -6038,7 +6039,7 @@ do { > :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. -[ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. +[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. @@ -6254,6 +6255,23 @@ protocol TransactionObserverType : class { ``` +## DatabaseRegionObservation + +**ValueObservation tracks changes in the results of database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** + +Transactions are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + + +### DatabaseRegionObservation Usage + +```swift +let observation = DatabaseRegionObservation(tracking: Player.all()) +let observer = observation.start(in: dbQueue) { db: Database in + print("Players were changed") +} +``` + + ## ValueObservation **ValueObservation tracks changes in the results of database [requests](#requests), and notifies fresh values whenever the database changes.** @@ -7957,6 +7975,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 +8538,6 @@ 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 \ No newline at end of file From 194624212eb7119195c41e944e94aee24751005f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:33:17 +0100 Subject: [PATCH 06/15] Move db observation documentations around --- README.md | 753 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 429 insertions(+), 324 deletions(-) diff --git a/README.md b/README.md index 3aee35ba5..db21aacb1 100644 --- a/README.md +++ b/README.md @@ -5846,11 +5846,12 @@ 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](#valueobservation-and-databaseregionobservation): Automated tracking of database requests. + - [DatabaseRegionObservation] + - [ValueObservation] +- [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. -- [DatabaseRegionObservation]: Focused tracking of database transactions. -- [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. @@ -5915,362 +5916,125 @@ 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: ```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 -``` - -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 + try Player(name: "Arthur").insert(db) } +// Prints "Players have 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: +[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been 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 +let observer = regionObservation.start(in: dbQueue) { db: Database in + print("Player have changed.") } -``` - -**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](#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 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("SELECT * FROM player").databaseRegion(db) - let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db) + try Player(name: "Barbara").insert(db) +} +// Prints "Players have changed." ``` -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 -} -``` +Both observations are based on the low-level [TransactionObserver Protocol](#transactionobserver-protocol). ## DatabaseRegionObservation -**ValueObservation tracks changes in the results of database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** +**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** -Transactions are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). +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") } ``` +And enjoy the changes notifications: + +```swift +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. + + +### 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 +// This observation lasts until the database connection is closed +var observation = DatabaseRegionObservation... +observation.extent = .databaseLifetime +_ = observation.start(in: dbQueue) { db in ... } +``` + +The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deallocated. + +Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method: + +```swift +// Start +let observer = observation.start(in: dbQueue) { db in ... } + +// Stop +dbQueue.remove(transactionObserver: observer) +``` + ## ValueObservation @@ -6821,6 +6585,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.** @@ -7161,6 +6926,346 @@ 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](#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](#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 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("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 +} +``` + + Encryption ========== From fd79a53a96e1ef5291bc61814651c7fac83ec16d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:34:02 +0100 Subject: [PATCH 07/15] Documentation --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index db21aacb1..89b4c0d10 100644 --- a/README.md +++ b/README.md @@ -5848,8 +5848,6 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas - [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. - [ValueObservation and DatabaseRegionObservation](#valueobservation-and-databaseregionobservation): Automated tracking of database requests. - - [DatabaseRegionObservation] - - [ValueObservation] - [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). From bc5899543f78fcc5ea7c6a3b9c19bb2e13b231b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:55:08 +0100 Subject: [PATCH 08/15] Documentation --- README.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 89b4c0d10..03c5a6538 100644 --- a/README.md +++ b/README.md @@ -5925,7 +5925,7 @@ let valueObservation = ValueObservation.trackingAll(request) let regionObservation = DatabaseRegionObservation(tracking: request) ``` -[ValueObservation] notifies your application with **fresh values**. This is what most applications need: +[ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): ```swift let observer = valueObservation.start(in: dbQueue) { players: [Player] in @@ -5939,7 +5939,7 @@ try dbQueue.write { db in ``` -[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed: +[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for advanced use cases :nerd_face:): ```swift let observer = regionObservation.start(in: dbQueue) { db: Database in @@ -5952,8 +5952,6 @@ try dbQueue.write { db in // Prints "Players have changed." ``` -Both observations are based on the low-level [TransactionObserver Protocol](#transactionobserver-protocol). - ## DatabaseRegionObservation @@ -6044,11 +6042,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) From 9a3e6f0b975399d21834e24468d26225934f8fb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:58:47 +0100 Subject: [PATCH 09/15] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c4ca1807..b25f96591 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 From 73935dfa9d7f416027fd02f79da3741524b24162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 14:02:10 +0100 Subject: [PATCH 10/15] CHANGELOG --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b25f96591..f0795c51a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -121,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 ++} ``` From 862563fdaad93053d5ba1c4eece6056461e6a0a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 16:42:20 +0100 Subject: [PATCH 11/15] Remove obsolete test --- .../DatabaseRegionObservationTests.swift | 41 ------------------- 1 file changed, 41 deletions(-) diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index aa9a99f87..dff415cc5 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -13,47 +13,6 @@ import XCTest #endif class DatabaseRegionObservationTests: GRDBTestCase { - func testDatabaseRegionObservation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let request = SQLRequest("SELECT * FROM t ORDER BY id") - let observation = DatabaseRegionObservation(tracking: { db in - try request.databaseRegion(db) - }) - let observer = try observation.start(in: dbQueue) { db in - let rows = try! request.fetchAll(db) - results.append(rows) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute("UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute("DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute("DELETE FROM t WHERE id = 1") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - } - - XCTAssertEqual(results, [ - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) - } - func testDatabaseRegionObservationVariadic() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { From 03934041c27d937d371a6d0b2664827e5ed07077 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:41:43 +0100 Subject: [PATCH 12/15] Fix DatabaseRegion doc layout --- GRDB/Core/DatabaseRegion.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 737cfd8fc..042bf335a 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -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 From 97936c3fad53adc3aae381d22002c64c17b9f440 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:46:57 +0100 Subject: [PATCH 13/15] Documentation --- README.md | 116 ++++++++++++++++++------------------------------------ 1 file changed, 39 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 03c5a6538..fa064eb49 100644 --- a/README.md +++ b/README.md @@ -5847,7 +5847,7 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: - [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. -- [ValueObservation and DatabaseRegionObservation](#valueobservation-and-databaseregionobservation): Automated tracking of database requests. +- [ValueObservation and DatabaseRegionObservation]: Automated tracking of database requests. - [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). @@ -5990,6 +5990,16 @@ try dbQueue.write { db in 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") +} +``` + ### DatabaseRegionObservation Use Cases @@ -6233,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 { @@ -6286,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 @@ -7169,74 +7171,32 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan **[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. +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. -You start by building regions: +DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservation]. -```swift -try dbQueue.write { db in - let teamRegion = try Team.filter(key: 1).databaseRegion(db) - let playersRegion = try SQLRequest("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. +**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. +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 @@ -8637,4 +8597,6 @@ This chapter has been renamed [Beyond FetchableRecord]. [ValueObservation]: #valueobservation [DatabaseRegionObservation]: #databaseregionobservation [FetchedRecordsController]: #fetchedrecordscontroller -[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB \ No newline at end of file +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol +[ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation From 21d243fc33374eee6ee933d9043046cb780a6655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:51:45 +0100 Subject: [PATCH 14/15] Documentation --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index fa064eb49..4228d1fde 100644 --- a/README.md +++ b/README.md @@ -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), [DatabaseRegionObservation], 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): @@ -6955,7 +6955,7 @@ protocol TransactionObserver : class { - [Database Changes And Transactions](#database-changes-and-transactions) - [Filtering Database Events](#filtering-database-events) - [Observation Extent](#observation-extent) -- [DatabaseRegion](#databaseregion) +- [DatabaseRegion] - [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) @@ -7103,7 +7103,7 @@ class PureTransactionObserver: TransactionObserver { } ``` -For more information about event filtering, see [DatabaseRegion](#databaseregion). +For more information about event filtering, see [DatabaseRegion]. ### Observation Extent @@ -8600,3 +8600,4 @@ This chapter has been renamed [Beyond FetchableRecord]. [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol [ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation +[DatabaseRegion]: #databaseregion \ No newline at end of file From 9fd802b3eae9593f304ea3f370689ec4175abe9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:54:09 +0100 Subject: [PATCH 15/15] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4228d1fde..76faafeaa 100644 --- a/README.md +++ b/README.md @@ -6052,7 +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): ([map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ...) +- [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)