diff --git a/CHANGELOG.md b/CHANGELOG.md index 59a06bc31..e6649d63c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#736](https://github.com/groue/GRDB.swift/pull/736): Relax ValueObservation Guarantees - [#737](https://github.com/groue/GRDB.swift/pull/737): Force implicit database region for ValueObservation - [#738](https://github.com/groue/GRDB.swift/pull/738): Remove all observationForCount/All/First methods +- [#742](https://github.com/groue/GRDB.swift/pull/742): ValueObservation scheduling is no longer an attribute of the observation ## 4.12.0 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index afb8fb877..e19937f58 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -153,12 +153,8 @@ 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; 563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; - 563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; }; - 563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; }; - 563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; }; - 563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; }; - 563B06C52185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; }; - 563B06C62185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */; }; + 563B06BE2185CCD300B38F35 /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */; }; 563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; }; 563B06C82185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; }; 563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */; }; @@ -199,9 +195,6 @@ 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; - 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; - 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; - 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; 564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; 564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; 564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; @@ -457,6 +450,7 @@ 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; 5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; 5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; + 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; 568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; @@ -761,6 +755,9 @@ 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; + 56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; + 56DDDDF6242F87C70025E381 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; + 56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; 56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56DF001B228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0019228DDBA200D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF001C228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0019228DDBA200D611F3 /* AssociationPrefetchingRowTests.swift */; }; @@ -864,7 +861,6 @@ AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA482291707D00478429 /* Inflections+English.swift */; }; AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; }; AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172947223533F40006E219 /* EncodableRecord.swift */; }; - AAA4DCAB230F1E0600C74B15 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; @@ -1005,7 +1001,6 @@ AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */; }; AAA4DD51230F262000C74B15 /* FoundationURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB351D108BA9006283EF /* FoundationURLTests.swift */; }; - AAA4DD52230F262000C74B15 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; }; AAA4DD53230F262000C74B15 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; }; AAA4DD54230F262000C74B15 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; AAA4DD55230F262000C74B15 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56959615222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; }; @@ -1098,7 +1093,6 @@ AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; AAA4DDAE230F262000C74B15 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA20228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; AAA4DDAF230F262000C74B15 /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623935F1DEE06D300A6B01F /* CursorTests.swift */; }; - AAA4DDB0230F262000C74B15 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; }; AAA4DDB1230F262000C74B15 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */; }; AAA4DDB2230F262000C74B15 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; AAA4DDB3230F262000C74B15 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; @@ -1117,7 +1111,7 @@ AAA4DDC0230F262000C74B15 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; }; AAA4DDC1230F262000C74B15 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; }; AAA4DDC2230F262000C74B15 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; - AAA4DDC3230F262000C74B15 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; }; + AAA4DDC3230F262000C74B15 /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */; }; AAA4DDC4230F262000C74B15 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; AAA4DDC5230F262000C74B15 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; AAA4DDC6230F262000C74B15 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; @@ -1234,9 +1228,7 @@ 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; - 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; - 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; - 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; + 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = ""; }; 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; @@ -1254,7 +1246,6 @@ 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 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 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.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 = ""; }; @@ -1353,6 +1344,7 @@ 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; + 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1671,7 +1663,7 @@ isa = PBXGroup; children = ( 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, - 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */, + 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */, 564CE43021AA901800652B19 /* ValueObserver.swift */, 56AACAA022ACEC9700A40F2A /* ValueReducer */, ); @@ -1806,7 +1798,6 @@ 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, - 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */, 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */, 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, @@ -1814,10 +1805,9 @@ 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */, 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */, 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, - 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */, - 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */, + 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */, ); name = ValueObservation; sourceTree = ""; @@ -2767,7 +2757,6 @@ 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, - 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, 569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, @@ -2784,6 +2773,7 @@ 5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 56DDDDF6242F87C70025E381 /* ValueObservationScheduler.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, @@ -2913,11 +2903,11 @@ 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, + 56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 569BBA4F229170F900478429 /* Inflections+English.swift in Sources */, 5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294F223533F40006E219 /* EncodableRecord.swift in Sources */, - 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -3070,7 +3060,6 @@ 5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */, 564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */, 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 5695961D222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */, @@ -3167,7 +3156,6 @@ 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, - 563B06C62185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -3187,7 +3175,7 @@ 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, 56677C1A241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */, 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, - 563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */, + 563B06BE2185CCD300B38F35 /* ValueObservationTests.swift in Sources */, 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */, 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */, @@ -3279,7 +3267,6 @@ 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, - 563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */, 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, 564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */, 5695961C222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */, @@ -3376,7 +3363,6 @@ 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, 569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, - 563B06C52185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, @@ -3396,7 +3382,7 @@ 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56677C19241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */, 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, - 563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */, + 563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */, 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */, 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, @@ -3459,11 +3445,11 @@ AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */, AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */, AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */, + 56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */, AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */, AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */, AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */, AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */, - AAA4DCAB230F1E0600C74B15 /* ValueObservation+MapReducer.swift in Sources */, AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */, AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */, AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */, @@ -3616,7 +3602,6 @@ 5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */, AAA4DD51230F262000C74B15 /* FoundationURLTests.swift in Sources */, - AAA4DD52230F262000C74B15 /* ValueObservationExtentTests.swift in Sources */, AAA4DD53230F262000C74B15 /* DatabaseValueConversionErrorTests.swift in Sources */, AAA4DD54230F262000C74B15 /* AssociationHasOneSQLDerivationTests.swift in Sources */, AAA4DD55230F262000C74B15 /* AssociationHasManyThroughSQLTests.swift in Sources */, @@ -3713,7 +3698,6 @@ AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */, AAA4DDAE230F262000C74B15 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, AAA4DDAF230F262000C74B15 /* CursorTests.swift in Sources */, - AAA4DDB0230F262000C74B15 /* ValueObservationSchedulingTests.swift in Sources */, AAA4DDB1230F262000C74B15 /* FoundationNSStringTests.swift in Sources */, AAA4DDB2230F262000C74B15 /* OrderedDictionaryTests.swift in Sources */, AAA4DDB3230F262000C74B15 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -3733,7 +3717,7 @@ AAA4DDC1230F262000C74B15 /* RecordWithColumnNameManglingTests.swift in Sources */, 56677C1B241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */, AAA4DDC2230F262000C74B15 /* AssociationParallelSQLTests.swift in Sources */, - AAA4DDC3230F262000C74B15 /* ValueObservationReducerTests.swift in Sources */, + AAA4DDC3230F262000C74B15 /* ValueObservationTests.swift in Sources */, AAA4DDC4230F262000C74B15 /* RecordUniqueIndexTests.swift in Sources */, AAA4DDC5230F262000C74B15 /* CGFloatTests.swift in Sources */, AAA4DDC6230F262000C74B15 /* DatabaseRegionTests.swift in Sources */, @@ -3779,7 +3763,6 @@ 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, @@ -3789,6 +3772,7 @@ 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, + 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */, 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8fc4c63e6..f2efde776 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -403,6 +403,50 @@ extension DatabasePool: DatabaseReader { } } + /// :nodoc: + public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + // First async jump in order to grab a reader connection. + // Honor configuration dispatching (qos/targetQueue). + configuration + .makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead") + .async { [weak self] in + guard let self = self else { + block(nil) + return + } + + do { + let (reader, releaseReader) = try self.readerPool.get() + + // Second async jump because sync could deadlock if + // configuration has a serial targetQueue. + reader.weakAsync { db in + guard let db = db else { + block(nil) + return + } + + defer { + try? db.commit() // Ignore commit error + releaseReader() + } + do { + // The block isolation comes from the DEFERRED transaction. + try db.beginTransaction(.deferred) + + // Reset the schema cache before running user code in snapshot isolation + db.clearSchemaCache() + block(.success(db)) + } catch { + block(.failure(error)) + } + } + } catch { + block(.failure(error)) + } + } + } + /// Synchronously executes a read-only block in a protected dispatch queue, /// and returns its result. /// @@ -724,6 +768,11 @@ extension DatabasePool: DatabaseReader { writer.async(updates) } + /// :nodoc: + public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) { + writer.weakAsync(updates) + } + // MARK: - Functions /// Add or redefine an SQL function. @@ -775,16 +824,97 @@ extension DatabasePool: DatabaseReader { public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - add( - observation: observation, - // DatabasePool supports concurrent reads - prependingConcurrentFetch: !observation.requiresWriteAccess, + if configuration.readonly { + return addReadOnly(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) + } + + if observation.requiresWriteAccess { + return addWriteOnly(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) + } + + let observer = ValueObserver( + requiresWriteAccess: observation.requiresWriteAccess, + writer: self, + reducer: observation.makeReducer(), + scheduler: scheduler, + reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), onError: onError, onChange: onChange) + + if scheduler.immediateInitialValue() { + do { + // Fetch an initial value without waiting for the writer. + let initialValue = try unsafeReentrantRead(observer.fetchInitialValue) + onChange(initialValue) + + // Now wait for the writer + _weakAsyncWriteWithoutTransaction { db in + guard let db = db else { + observer.cancel() + return + } + if observer.isCompleted { return } + do { + // Don't miss eventual changes between the + // initial fetch and the writer access. + if let value = try observer.fetchNextValue(db) { + observer.send(value) + } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) + } catch { + observer.complete(withError: error) + } + } + } catch { + observer.cancel() + onError(error) + } + } else { + // Fetch an initial value without waiting for the writer. + _weakAsyncRead { [weak self] dbResult in + guard let dbResult = dbResult, let self = self else { + observer.cancel() + return + } + if observer.isCompleted { return } + do { + let initialValue = try observer.fetchInitialValue(dbResult.get()) + observer.send(initialValue) + + // Now wait for the writer + self._weakAsyncWriteWithoutTransaction { db in + guard let db = db else { + observer.cancel() + return + } + if observer.isCompleted { return } + do { + // Don't miss eventual changes between the + // initial fetch and the writer access. + if let value = try observer.fetchNextValue(db) { + observer.send(value) + } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) + } catch { + observer.complete(withError: error) + } + } + } catch { + observer.complete(withError: error) + } + } + } + + return ValueObserverToken(writer: self, observer: observer) } // MARK: - Custom FTS5 Tokenizers diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index f29007fec..7eaf30b91 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -231,6 +231,28 @@ extension DatabaseQueue { } } + /// :nodoc: + public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + writer.weakAsync { db in + guard let db = db else { + block(nil) + return + } + + do { + try db.beginReadOnly() + } catch { + block(.failure(error)) + return + } + + block(.success(db)) + + // Ignore error because we can not notify it. + try? db.endReadOnly() + } + } + /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// @@ -404,6 +426,11 @@ extension DatabaseQueue { writer.async(updates) } + /// :nodoc: + public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) { + writer.weakAsync(updates) + } + // MARK: - Functions /// Add or redefine an SQL function. @@ -451,15 +478,15 @@ extension DatabaseQueue { public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - add( - observation: observation, - // DatabaseQueue does not support concurrent reads - prependingConcurrentFetch: false, - onError: onError, - onChange: onChange) + if configuration.readonly { + return addReadOnly(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) + } + + return addWriteOnly(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 34436f2bd..2b2d22d88 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -140,6 +140,11 @@ public protocol DatabaseReader: AnyObject { /// - parameter block: A block that accesses the database. func asyncRead(_ block: @escaping (Result) -> Void) + /// Same as asyncRead, but without retaining self + /// + /// :nodoc: + func _weakAsyncRead(_ block: @escaping (Result?) -> Void) + /// Synchronously executes a read-only block that takes a database /// connection, and returns its result. /// @@ -254,10 +259,12 @@ public protocol DatabaseReader: AnyObject { /// - returns: a TransactionObserver func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver + // TODO: move to DatabaseWriter when we have proper support for Observation cancellation /// Remove a transaction observer. func remove(transactionObserver: TransactionObserver) } @@ -297,64 +304,63 @@ extension DatabaseReader { extension DatabaseReader { // MARK: - Value Observation Support - + + /// Adding an observation in a read-only database emits only the + /// initial value. func addReadOnly( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - switch observation.scheduling { - case .mainQueue: - if DispatchQueue.isMain { - do { - try onChange(unsafeReentrantRead(observation.fetchValue)) - } catch { - onError(error) - } - } else { - asyncRead { dbResult in - let result = dbResult.tryMap(observation.fetchValue) - DispatchQueue.main.async { - do { - try onChange(result.get()) - } catch { - onError(error) - } - } - } + // A dummy observer is enough, because read-only ValueObservation + // never changes. + let observer = DummyObserver() + + if scheduler.immediateInitialValue() { + do { + try onChange(unsafeReentrantRead(observation.fetchValue)) + } catch { + observer.cancel() + onError(error) } - case let .async(onQueue: queue): - asyncRead { dbResult in + } else { + _weakAsyncRead { [weak observer] dbResult in + guard let observer = observer else { + return + } + guard let dbResult = dbResult else { + observer.cancel() + return + } let result = dbResult.tryMap(observation.fetchValue) - queue.async { + scheduler.schedule { [weak observer] in + guard let observer = observer else { + return + } do { try onChange(result.get()) } catch { + observer.cancel() onError(error) } } } - case .unsafe: - do { - try onChange(unsafeReentrantRead(observation.fetchValue)) - } catch { - onError(error) - } } - // Return a dummy observer, because read-only ValueObservation - // never changes. - return DummyObserver() + return observer } } +// TODO: remove when we have proper support for cancellation /// Support for DatabaseReader.addReadonly(observation:onError:onChange:) private class DummyObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } + func cancel() { } } /// A type-erased DatabaseReader @@ -393,6 +399,11 @@ public final class AnyDatabaseReader: DatabaseReader { base.asyncRead(block) } + /// :nodoc: + public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + base._weakAsyncRead(block) + } + /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) throws -> T { try base.unsafeRead(block) @@ -432,11 +443,12 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - return base.add(observation: observation, onError: onError, onChange: onChange) + return base.add(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } /// :nodoc: diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 8d7dbc14e..046019f2f 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -84,6 +84,11 @@ extension DatabaseSnapshot { serializedDatabase.async { block(.success($0)) } } + /// :nodoc: + public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + serializedDatabase.weakAsync { block($0.map { .success($0) }) } + } + /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { try serializedDatabase.sync(block) @@ -118,13 +123,15 @@ extension DatabaseSnapshot { public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - return addReadOnly(observation: observation, onError: onError, onChange: onChange) + return addReadOnly(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } + // TODO: remove when we have proper support for Observation cancellation public func remove(transactionObserver: TransactionObserver) { // Can't remove an observer which could not be added :-) } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index d1be3bd48..acf3b09d7 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -99,6 +99,12 @@ public protocol DatabaseWriter: DatabaseReader { /// in a transaction. func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + /// Asynchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, without retaining self. + /// + /// :nodoc: + func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// @@ -274,10 +280,10 @@ extension DatabaseWriter { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } - /// Default implementation for the DatabaseReader requirement. - /// :nodoc: public func remove(transactionObserver: TransactionObserver) { - unsafeReentrantWrite { $0.remove(transactionObserver: transactionObserver) } + _weakAsyncWriteWithoutTransaction { + $0?.remove(transactionObserver: transactionObserver) + } } // MARK: - Erasing the content of the database @@ -301,76 +307,27 @@ extension DatabaseWriter { } // MARK: - Database Observation - - func add( + + /// A write-only observation only uses the serialized writer + func addWriteOnly( observation: ValueObservation, - prependingConcurrentFetch: Bool, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - if configuration.readonly { - return addReadOnly(observation: observation, onError: onError, onChange: onChange) - } - - // True if initial value must be sent to the onChange callback - // before this method returns. - // This flag supersedes prependingConcurrentFetch. - let initialFetchSync: Bool - - // The queue for other values. Nil for any queue. - let notificationQueue: DispatchQueue? - - switch observation.scheduling { - case .mainQueue: - if DispatchQueue.isMain { - // Use case: observation starts on the main queue and wants - // a synchronous initial fetch. This helps avoiding flashes of - // missing content. - initialFetchSync = true - notificationQueue = DispatchQueue.main - } else { - // TODO: make this a fatal error when .mainQueue is no longer - // the default scheduling. - // Use case: observation does not start on the main queue, but - // has the default scheduling .mainQueue - initialFetchSync = false - notificationQueue = DispatchQueue.main - } - - case let .async(onQueue: queue): - // Use case: observation must not block the target queue - initialFetchSync = false - notificationQueue = queue - - case .unsafe: - // Use case: third-party integration (RxSwift, Combine, ...) that - // need a synchronous initial fetch. - // - // This is really super extra unsafe. - // - // If the observation is started on one dispatch queue, then - // the onChange and onError callbacks must be asynchronously - // dispatched on the *same* queue. - // - // A failure to follow this rule may mess with the ordering of - // initial values. - initialFetchSync = true - notificationQueue = nil - } - - // --- + assert(!configuration.readonly, "Use addReadOnly(observation:) instead") let observer = ValueObserver( requiresWriteAccess: observation.requiresWriteAccess, writer: self, reducer: observation.makeReducer(), - notificationQueue: notificationQueue, + scheduler: scheduler, reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), onError: onError, onChange: onChange) - if initialFetchSync { + if scheduler.immediateInitialValue() { do { let initialValue: Reducer.Value = try unsafeReentrantWrite { db in let initialValue = try observer.fetchInitialValue(db) @@ -379,52 +336,26 @@ extension DatabaseWriter { } onChange(initialValue) } catch { + observer.cancel() onError(error) } - } else if prependingConcurrentFetch { - asyncRead { dbResult in - do { - let db = try dbResult.get() - let initialValue = try observer.fetchInitialValue(db) - observer.send(initialValue) - - self.asyncWriteWithoutTransaction { [weak observer] db in - guard let observer = observer else { return } - if observer.isCancelled { return } - do { - if let value = try observer.fetchNextValue(db) { - observer.send(value) - } - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - observer.send(error) - } - } - } catch { - observer.send(error) - } - } } else { - asyncWriteWithoutTransaction { db in + _weakAsyncWriteWithoutTransaction { db in + guard let db = db else { + observer.cancel() + return + } + if observer.isCompleted { return } do { let initialValue = try observer.fetchInitialValue(db) observer.send(initialValue) db.add(transactionObserver: observer, extent: .observerLifetime) } catch { - observer.send(error) + observer.complete(withError: error) } } } - // TODO - // - // We promise that observation stops when the returned observer is - // deallocated. But the real observer may have not started observing - // the database, because some observations start asynchronously. - // Well... This forces us to return a "token" that cancels any - // observation started asynchronously. - // - // We'll eventually return a proper Cancellable. In GRDB 5? return ValueObserverToken(writer: self, observer: observer) } } @@ -504,6 +435,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.asyncRead(block) } + /// :nodoc: + public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + base._weakAsyncRead(block) + } + /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) throws -> T { try base.unsafeRead(block) @@ -554,6 +490,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.asyncWriteWithoutTransaction(updates) } + /// :nodoc: + public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) { + base._weakAsyncWriteWithoutTransaction(updates) + } + /// :nodoc: public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { try base.unsafeReentrantWrite(updates) @@ -585,13 +526,19 @@ public final class AnyDatabaseWriter: DatabaseWriter { // MARK: - Database Observation + /// :nodoc: + public func remove(transactionObserver: TransactionObserver) { + base.remove(transactionObserver: transactionObserver) + } + /// :nodoc: public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - base.add(observation: observation, onError: onError, onChange: onChange) + base.add(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index f5a1a5383..f51a64840 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -184,6 +184,19 @@ final class SerializedDatabase { } } + /// Asynchronously executes a block in the serialized dispatch queue, + /// without retaining self. + func weakAsync(_ block: @escaping (Database?) -> Void) { + queue.async { [weak self] in + if let self = self { + block(self.db) + self.preconditionNoUnsafeTransactionLeft(self.db) + } else { + block(nil) + } + } + } + /// Returns true if any only if the current dispatch queue is valid. var onValidQueue: Bool { SchedulingWatchdog.current?.allows(db) ?? false diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 7e052695b..120f2f1f0 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -1,6 +1,7 @@ // Fixits for changes introduced by GRDB 5.0.0 // swiftlint:disable all +import Dispatch #if os(iOS) import UIKit #endif @@ -199,10 +200,16 @@ extension TableRecord where Self: FetchableRecord { @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchOne) instead") public static func observationForFirst() -> ValueObservation> - { preconditionFailure() } + { preconditionFailure() } } extension ValueObservation { + @available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration") + var scheduling: ValueScheduling { + get { preconditionFailure() } + set { preconditionFailure() } + } + @available(*, unavailable, message: "Custom reducers are no longer supported") public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: @escaping (Database) throws -> Reducer) -> ValueObservation { preconditionFailure() } @@ -307,16 +314,19 @@ extension ValueReducers { public func fetch(_ db: Database) throws -> Never { preconditionFailure() } - public mutating func value(_ fetched: Never) -> T? - { preconditionFailure() } + public mutating func value(_ fetched: Never) -> T? { } } } @available(*, unavailable, message: "Custom reducers are no longer supported") typealias ValueReducer = _ValueReducer -@available(*, unavailable, renamed: "ValueObservationScheduling") -typealias ValueScheduling = ValueObservationScheduling +@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration") +enum ValueScheduling { + case mainQueue + case async(onQueue: DispatchQueue, startImmediately: Bool) + case unsafe(startImmediately: Bool) +} #if SQLITE_HAS_CODEC extension Configuration { diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift deleted file mode 100644 index dfaef4b90..000000000 --- a/GRDB/ValueObservation/ValueObservation+MapReducer.swift +++ /dev/null @@ -1,10 +0,0 @@ -extension ValueObservation { - /// Returns a ValueObservation with a transformed reducer. - func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { - let makeReducer = self.makeReducer - return ValueObservation( - makeReducer: { transform(makeReducer()) }, - requiresWriteAccess: requiresWriteAccess, - scheduling: scheduling) - } -} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 13fad7f59..1813a177a 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -1,79 +1,14 @@ import Dispatch -// MARK: - ValueScheduling - -/// ValueObservationScheduling controls how ValueObservation schedules the -/// fresh values to your application. -public enum ValueObservationScheduling { - /// All values are notified on the main queue. - /// - /// If the observation starts on the main queue, the initial value is - /// notified right upon subscription, synchronously: - /// - /// // On main queue - /// let observation = ValueObservation.tracking(Player.fetchAll) - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { players: [Player] in - /// print("fresh players: \(players)") - /// }) - /// // <- here "fresh players" is already printed. - /// - /// If the observation does not start on the main queue, the initial value - /// is also notified on the main queue, but asynchronously: - /// - /// // Not on the main queue: "fresh players" is eventually printed - /// // on the main queue. - /// let observation = ValueObservation.tracking(Player.fetchAll) - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { players: [Player] in - /// print("fresh players: \(players)") - /// }) - /// - /// When the database changes, fresh values are asynchronously notified on - /// the main queue: - /// - /// // Eventually prints "fresh players" on the main queue - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - case mainQueue - - /// All values are asychronously notified on the specified queue. - case async(onQueue: DispatchQueue) - - /// Values are not all notified on the same dispatch queue. - /// - /// The initial value is notified right upon subscription, synchronously, on - /// the dispatch queue which starts the observation. - /// - /// // On any queue - /// var observation = ValueObservation.tracking(Player.fetchAll) - /// observation.scheduling = .unsafe - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { players: [Player] in - /// print("fresh players: \(players)") - /// }) - /// // <- here "fresh players" is already printed. - /// - /// When the database changes, other values are notified on - /// unspecified queues. - case unsafe -} - -// MARK: - ValueObservation - /// ValueObservation tracks changes in the results of database requests, and /// notifies fresh values whenever the database changes. /// /// For example: /// -/// let observation = ValueObservation.tracking(Player.fetchAll) +/// let observation = ValueObservation.tracking { db in +/// try Player.fetchAll(db) +/// } +/// /// let observer = try observation.start( /// in: dbQueue, /// onError: { error in ... }, @@ -82,7 +17,7 @@ public enum ValueObservationScheduling { /// }) public struct ValueObservation { /// The reducer is created when observation starts, and is triggered upon - /// each database change in *observedRegion*. + /// each database change. var makeReducer: () -> Reducer /// Default is false. Set this property to true when the observation @@ -93,9 +28,13 @@ public struct ValueObservation { /// observation is less efficient than a read-only observation. public var requiresWriteAccess: Bool = false - /// `scheduling` controls how fresh values are notified. Default - /// is `.mainQueue`. - public var scheduling: ValueObservationScheduling = .mainQueue + /// Returns a ValueObservation with a transformed reducer. + func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { + let makeReducer = self.makeReducer + return ValueObservation( + makeReducer: { transform(makeReducer()) }, + requiresWriteAccess: requiresWriteAccess) + } } extension ValueObservation { @@ -105,17 +44,50 @@ extension ValueObservation { /// Starts the value observation in the provided database reader (such as /// a database queue or database pool), and returns a transaction observer. /// + /// The observation lasts until the returned observer is deallocated. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + /// + /// By default, fresh values are dispatched asynchronously on the + /// main queue. You can change this behavior by providing a scheduler. + /// For example, `.immediate` notifies all values on the main queue as well, + /// but the first one is immediately notified when the start() method + /// is called: + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// scheduler: .immediate, // <- + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + /// // <- here "fresh players" is already printed. + /// /// - parameter reader: A DatabaseReader. + /// - parameter scheduler: A Scheduler. By default, fresh values are + /// dispatched asynchronously on the main queue. /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation + /// happen during observation /// - parameter onChange: A closure that is provided fresh values /// - returns: a TransactionObserver public func start( in reader: DatabaseReader, + scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - return reader.add(observation: self, onError: onError, onChange: onChange) + return reader.add(observation: self, scheduler: scheduler, onError: onError, onChange: onChange) } // MARK: - Fetching Values diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift new file mode 100644 index 000000000..57e4b2c06 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -0,0 +1,90 @@ +import Dispatch +import Foundation + +/// ValueObservationScheduler determines how ValueObservation notifies its +/// fresh values. +public class ValueObservationScheduler { + private let impl: ValueObservationSchedulerImpl + + private init(impl: ValueObservationSchedulerImpl) { + self.impl = impl + } + + func schedule(_ action: @escaping () -> Void) { + impl.schedule(action) + } + + func immediateInitialValue() -> Bool { + impl.immediateInitialValue() + } + + /// A scheduler which asynchronously notifies fresh value of the + /// given DispatchQueue. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// scheduler: .async(onQueue: .main), + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + public static func async(onQueue queue: DispatchQueue) -> ValueObservationScheduler { + return ValueObservationScheduler(impl: queue) + } + + /// A scheduler which notifies all values on the main queue. The first one + /// is immediately notified when the start() method is called. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// scheduler: .immediate, + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + /// // <- here "fresh players" is already printed. + /// + /// - important: this scheduler requires that the observation is started + /// from the main queue. A fatal error is raised otherwise. + public static let immediate = ValueObservationScheduler(impl: ImmediateImpl()) +} + +private protocol ValueObservationSchedulerImpl { + func schedule(_ action: @escaping () -> Void) + func immediateInitialValue() -> Bool +} + +private struct ImmediateImpl: ValueObservationSchedulerImpl { + func schedule(_ action: @escaping () -> Void) { + DispatchQueue.main.async(execute: action) + } + + func immediateInitialValue() -> Bool { + GRDBPrecondition( + Thread.isMainThread, + "ValueObservation must be started from the main thread.") + return true + } +} + +extension DispatchQueue: ValueObservationSchedulerImpl { + func schedule(_ action: @escaping () -> Void) { + async(execute: action) + } + + func immediateInitialValue() -> Bool { + false + } +} diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index a31d7404d..381c4bb08 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -4,21 +4,23 @@ import Foundation /// See DatabaseWriter.add(observation:onError:onChange:) final class ValueObserver { var observedRegion: DatabaseRegion? - private(set) var isCancelled = false + var isCompleted: Bool { synchronized { _isCompleted } } + private var _isCompleted = false private var reducer: Reducer private let requiresWriteAccess: Bool private weak var writer: DatabaseWriter? - private let notificationQueue: DispatchQueue? + private let scheduler: ValueObservationScheduler private let reduceQueue: DispatchQueue private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void private var isChanged = false + private var lock = NSRecursiveLock() init( requiresWriteAccess: Bool, writer: DatabaseWriter, reducer: Reducer, - notificationQueue: DispatchQueue?, + scheduler: ValueObservationScheduler, reduceQueue: DispatchQueue, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) @@ -26,11 +28,17 @@ final class ValueObserver { self.writer = writer self.reducer = reducer self.requiresWriteAccess = requiresWriteAccess - self.notificationQueue = notificationQueue + self.scheduler = scheduler self.reduceQueue = reduceQueue self.onError = onError self.onChange = onChange } + + private func synchronized(_ execute: () throws -> T) rethrows -> T { + lock.lock() + defer { lock.unlock() } + return try execute() + } } extension ValueObserver { @@ -50,47 +58,45 @@ extension ValueObserver { } func cancel() { - isCancelled = true - writer?.asyncWriteWithoutTransaction { db in - db.remove(transactionObserver: self) - } + complete() } func send(_ value: Reducer.Value) { - if isCancelled { return } - if let queue = notificationQueue { - let onChange = self.onChange - queue.async { - if self.isCancelled { return } - onChange(value) - } - } else { - onChange(value) + if isCompleted { return } + scheduler.schedule { + if self.isCompleted { return } + self.onChange(value) } } - func send(_ error: Error) { - if isCancelled { return } - if let queue = notificationQueue { - let onError = self.onError - queue.async { - if self.isCancelled { return } - onError(error) + func complete(withError error: Error) { + if isCompleted { return } + scheduler.schedule { + let shouldNotify: Bool = self.synchronized { + if self._isCompleted { return false } + self._isCompleted = true + return true } - } else { - onError(error) + if shouldNotify { + self.onError(error) + } + } + } + + func complete() { + synchronized { + _isCompleted = true + writer?.remove(transactionObserver: self) } } } extension ValueObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - if isCancelled { return false } - return observedRegion!.isModified(byEventsOfKind: eventKind) + observedRegion!.isModified(byEventsOfKind: eventKind) } func databaseDidChange(with event: DatabaseEvent) { - if isCancelled { return } if observedRegion!.isModified(by: event) { isChanged = true stopObservingDatabaseChangesUntilNextTransaction() @@ -99,7 +105,7 @@ extension ValueObserver: TransactionObserver { func databaseDidCommit(_ db: Database) { guard let writer = writer else { return } - if isCancelled { return } + if isCompleted { return } guard isChanged else { return } isChanged = false @@ -124,13 +130,13 @@ extension ValueObserver: TransactionObserver { // - that expensive reduce operations are computed without blocking // any database dispatch queue. reduceQueue.async { - if self.isCancelled { return } + if self.isCompleted { return } do { if let value = try self.reducer.value(fetchedValue.wait()) { self.send(value) } } catch { - self.send(error) + self.complete(withError: error) } } } @@ -168,6 +174,7 @@ extension ValueObserver { } } +// TODO: remove when we have proper support for cancellation class ValueObserverToken: TransactionObserver { // Useless junk func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3c20bc305..4c12329e6 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -73,16 +73,12 @@ 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; - 563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; - 563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; + 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */; }; + 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */; }; 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */; }; 563B06D42185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */; }; 563B06D52185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */; }; 563B06D62185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */; }; - 563B06D72185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */; }; - 563B06D82185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */; }; - 563B06D92185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */; }; - 563B06DA2185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */; }; 563B06FF21861D9D00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */; }; 563B070021861D9D00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */; }; 563B0702218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */; }; @@ -101,6 +97,8 @@ 563EF44E2161F196007DAACD /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF44C2161F196007DAACD /* Inflections.swift */; }; 563EF45621631E3F007DAACD /* QueryInterfacePromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */; }; 563EF45721631E3F007DAACD /* QueryInterfacePromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */; }; + 563F4CB4242F7F140052E96C /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB3242F7F130052E96C /* ValueObservationTests.swift */; }; + 563F4CB5242F7F140052E96C /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB3242F7F130052E96C /* ValueObservationTests.swift */; }; 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; }; @@ -113,8 +111,6 @@ 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; - 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; - 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.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 */; }; @@ -773,11 +769,9 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; - 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; + 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; - 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; - 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; @@ -787,6 +781,7 @@ 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; 563EF44C2161F196007DAACD /* Inflections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Inflections.swift; sourceTree = ""; }; 563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfacePromiseTests.swift; sourceTree = ""; }; + 563F4CB3242F7F130052E96C /* ValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; @@ -794,7 +789,6 @@ 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; 564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 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 = ""; }; 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 = ""; }; @@ -1186,7 +1180,7 @@ isa = PBXGroup; children = ( 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, - 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */, + 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */, 564CE43B21AA955B00652B19 /* ValueObserver.swift */, 56C0538822ACEECD0029D27D /* ValueReducer */, ); @@ -1320,7 +1314,6 @@ 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */, 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, - 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */, 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */, 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, @@ -1328,10 +1321,9 @@ 56677C24241E6EA20050755D /* ValueObservationRecorder.swift */, 56677C23241E6EA10050755D /* ValueObservationRecorderTests.swift */, 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, - 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */, - 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */, + 563F4CB3242F7F130052E96C /* ValueObservationTests.swift */, ); name = ValueObservation; sourceTree = ""; @@ -2173,7 +2165,6 @@ 566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */, 5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, @@ -2188,6 +2179,7 @@ 5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */, 56C0539A22ACEECD0029D27D /* Combine.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, + 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5656A88A2295BD56001FF3FF /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2351,7 +2343,6 @@ 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 5615B286222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, - 563B06D82185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */, 5657AB6D1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 563B06D42185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, @@ -2406,12 +2397,10 @@ 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, - 563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */, 5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, - 563B06DA2185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2457,6 +2446,7 @@ 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 563F4CB5242F7F140052E96C /* ValueObservationTests.swift in Sources */, 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */, 56959636222D058B002CB7C9 /* AssociationHasManySQLTests.swift in Sources */, @@ -2510,7 +2500,6 @@ 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */, 5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, @@ -2525,6 +2514,7 @@ 5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */, 56C0539922ACEECD0029D27D /* Combine.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, + 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5656A8892295BD56001FF3FF /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2688,7 +2678,6 @@ 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 5615B285222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */, - 563B06D72185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */, 56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */, 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, @@ -2743,12 +2732,10 @@ F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, - 563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */, 5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, - 563B06D92185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2794,6 +2781,7 @@ 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, + 563F4CB4242F7F140052E96C /* ValueObservationTests.swift in Sources */, 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */, 56959637222D058B002CB7C9 /* AssociationHasManySQLTests.swift in Sources */, diff --git a/README.md b/README.md index 7d358a889..085361626 100644 --- a/README.md +++ b/README.md @@ -5487,6 +5487,7 @@ Tracked changes include changes performed by the [query interface](#the-query-in **ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Application](#demo-application) for a sample code. - [ValueObservation Usage](#valueobservation-usage) +- [ValueObservation Scheduling](#valueobservation-scheduling) - [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... - [ValueObservation Performance](#valueobservation-performance) @@ -5588,8 +5589,8 @@ let disposable = observation.rx.changes(in: dbQueue).subscribe( **Generally speaking**: -- ValueObservation notifies an initial value before the eventual changes. This initial value is notified immediately by default (when the `start` method is called). It can be notified [asynchronously](#valueobservationscheduling) if preferred. -- ValueObservation schedules changes notifications on the main thread by default. This can be [configured](#valueobservationscheduling). +- ValueObservation notifies an initial value before the eventual changes. +- By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. This can be [configured](#valueobservation-scheduling). - ValueObservation may coalesce subsequent changes into a single notification. - ValueObservation may notify consecutive identical values. You can filter out the undesired duplicates with the [removeDuplicates()](#valueobservationremoveduplicates) method. @@ -5632,6 +5633,67 @@ let observation = ValueObservation.trackingVaryingRegion { db -> Int in Observing a varying region can prevent some optimizations. See [ValueObservation Performance](#valueobservation-performance) for more information. +### ValueObservation Scheduling + +By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously: + +```swift +// The default scheduling +let observer = observation.start( + in: dbQueue, + onError: { error in ... }, // called asynchronously on the main thread + onChange: { value in print("fresh value") }) // called asynchronously on the main thread +``` + +You can change this behavior by adding a `scheduler` argument to the `start()` method. + +For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the observation starts. It helps your application update the user interface without having to wait for any asynchronous notifications: + +```swift +class PlayersViewController: UIViewController { + private var observer: TransactionObserver? + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + // Start observing the database + let observation = ValueObservation.tracking(Player.fetchAll) + observer = observation.start( + in: dbQueue, + scheduler: .immediate, // <- immediate scheduler + onError: { error in ... }, + onChange: { [weak self] (players: [Player]) in + guard let self = self else { return } + self.updateView(players) + }) + // <- Here the view has already been updated. + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + + // Stop observing the database + observer = nil + } + + private func updateView(_ players: [Player]) { ... } +} +``` + +Note that the `.immediate` scheduler requires that the observation is started from the main thread. It raises a fatal error otherwise. + +The other built-in scheduler `.async(onQueue:)` asynchronously schedules values and errors on the dispatch queue of your choice: + +```swift +let queue: DispatchQueue = ... +let observer = observation.start( + in: dbQueue, + scheduler: .async(onQueue: queue) + onError: { error in ... }, // called asynchronously on queue + onChange: { value in print("fresh value") }) // called asynchronously on queue +``` + + ### ValueObservation Operators **Operators** are methods that transform and configure value observations so that they better fit the needs of your application. @@ -5639,8 +5701,7 @@ Observing a varying region can prevent some optimizations. See [ValueObservation - [ValueObservation.map](#valueobservationmap) - [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) - [ValueObservation.combine](#valueobservationcombine) -- [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values. -- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database. +- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess) #### ValueObservation.map @@ -5743,65 +5804,6 @@ let observation = playerCountObservation.combine(bestPlayersObservation) { > :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the ValueObservation `combine` method. This is partially exact, because the reactive operator is unable to guarantee data consistency. If you use a Reactive layer such as [GRDBCombine] or [RxGRDB], make sure you compose observations with `ValueObservation.combine`, and never with the CombineLatest operator. -#### ValueObservation.scheduling - -The `scheduling` property lets you control how fresh values are notified: - -- `.mainQueue` (the default): all values are notified on the main queue. - - If the observation starts on the main queue, the initial value is notified right upon subscription, synchronously: - - ```swift - // On main queue - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - // On main queue - print("fresh value: \(value)") - }) - // <- Here "fresh value" is already printed. - ``` - - If the observation does not start on the main queue, the initial value is also notified on the main queue, but asynchronously: - - ```swift - // Not on the main queue - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - // On main queue - print("fresh value: \(value)") - }) - ``` - - After the initial value has been notified, all subsequent values are notified asynchronously: - - ```swift - try dbQueue.write { db in ... } - // <- Eventually prints "fresh value" on the main queue - ``` - -- `.async(onQueue:)`: all values, including the initial value, are asynchronously notified on the specified queue. - - For example: - - ```swift - // On main queue - var observation = ... - observation.scheduling = .async(onQueue: .main) - let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { value in - // On main queue - print("fresh value: \(value)") - }) - // <- Eventually prints "fresh value" - ``` - - #### ValueObservation.requiresWriteAccess The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): @@ -5835,42 +5837,7 @@ When needed, you can help GRDB optimize observations and reduce database content 1. :bulb: **Tip**: Stop observations when possible. - For example, if a UIViewController needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`, as in the sample code below: - - -
- UIViewController example - - ```swift - class PlayersViewController: UIViewController { - private var observer: TransactionObserver? - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - - // Start observing the database - let observation = ValueObservation.tracking(Player.fetchAll) - observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { [weak self] (players: [Player]) in - guard let self = self else { return } - self.updateView(players) - }) - } - - override func viewWillDisappear(_ animated: Bool) { - super.viewWillDisappear(animated) - - // Stop observing the database - observer = nil - } - - private func updateView(_ players: [Player]) { ... } - } - ``` - -
+ For example, if a UIViewController needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`. Check the sample code [above](#valueobservation-scheduling). 2. :bulb: **Tip**: Share observations when possible. diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index c5caf8361..82c508f51 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 561CFAB12376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; }; 563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; }; + 563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; }; + 563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; }; 564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; }; 564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; }; 564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; }; @@ -56,7 +58,6 @@ 564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F45226B89D0001F64F1 /* DatabaseValueTests.swift */; }; 564A1FFD226B89E1001F64F1 /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */; }; 564A1FFE226B89E1001F64F1 /* FilterCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F47226B89D1001F64F1 /* FilterCursorTests.swift */; }; - 564A1FFF226B89E1001F64F1 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */; }; 564A2000226B89E1001F64F1 /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */; }; 564A2001226B89E1001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4A226B89D1001F64F1 /* RecordPrimaryKeyNoneTests.swift */; }; 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4B226B89D1001F64F1 /* DerivableRequestTests.swift */; }; @@ -118,7 +119,6 @@ 564A203B226B89E1001F64F1 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */; }; 564A203C226B89E1001F64F1 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */; }; 564A203D226B89E1001F64F1 /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */; }; - 564A203E226B89E1001F64F1 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */; }; 564A203F226B89E1001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F88226B89D8001F64F1 /* AssociationBelongsToRowScopeTests.swift */; }; 564A2040226B89E1001F64F1 /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F89226B89D8001F64F1 /* StatementColumnConvertibleFetchTests.swift */; }; 564A2041226B89E1001F64F1 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */; }; @@ -166,7 +166,6 @@ 564A206B226B89E1001F64F1 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB4226B89DD001F64F1 /* AssociationHasManyThroughSQLTests.swift */; }; 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB5226B89DD001F64F1 /* FTS5CustomTokenizerTests.swift */; }; 564A206D226B89E1001F64F1 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB6226B89DD001F64F1 /* ValueObservationCombineTests.swift */; }; - 564A206E226B89E1001F64F1 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */; }; 564A206F226B89E1001F64F1 /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */; }; 564A2071226B89E1001F64F1 /* VirtualTableModuleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */; }; 564A2072226B89E1001F64F1 /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FBB226B89DD001F64F1 /* DropFirstCursorTests.swift */; }; @@ -219,7 +218,6 @@ 564A20A4226B8E18001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F92226B89D9001F64F1 /* DatabaseQueueReadOnlyTests.swift */; }; 564A20A5226B8E18001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F39226B89CF001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift */; }; 564A20A6226B8E18001F64F1 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F33226B89CF001F64F1 /* AssociationChainRowScopesTests.swift */; }; - 564A20A7226B8E18001F64F1 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */; }; 564A20A8226B8E18001F64F1 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */; }; 564A20A9226B8E18001F64F1 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */; }; 564A20AA226B8E18001F64F1 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */; }; @@ -322,7 +320,6 @@ 564A210C226B8E18001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F88226B89D8001F64F1 /* AssociationBelongsToRowScopeTests.swift */; }; 564A210D226B8E18001F64F1 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */; }; 564A210E226B8E18001F64F1 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB3226B89DC001F64F1 /* FoundationNSStringTests.swift */; }; - 564A210F226B8E18001F64F1 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */; }; 564A2110226B8E18001F64F1 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */; }; 564A2111226B8E18001F64F1 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F94226B89D9001F64F1 /* FoundationNSDataTests.swift */; }; 564A2112226B8E18001F64F1 /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */; }; @@ -355,7 +352,6 @@ 564A212D226B8E18001F64F1 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F2B226B89CF001F64F1 /* DatabaseQueueBackupTests.swift */; }; 564A212E226B8E18001F64F1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F40226B89D0001F64F1 /* DatabaseValueConvertibleDecodableTests.swift */; }; 564A212F226B8E18001F64F1 /* UpdateStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FBD226B89DE001F64F1 /* UpdateStatementTests.swift */; }; - 564A2130226B8E18001F64F1 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */; }; 564A2131226B8E18001F64F1 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F7E226B89D7001F64F1 /* Row+FoundationTests.swift */; }; 564A2132226B8E18001F64F1 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FA3226B89DB001F64F1 /* QueryInterfaceRequestTests.swift */; }; 564A2133226B8E18001F64F1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F5A226B89D3001F64F1 /* FetchRequestTests.swift */; }; @@ -423,6 +419,7 @@ 561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; + 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; @@ -459,7 +456,6 @@ 564A1F45226B89D0001F64F1 /* DatabaseValueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueTests.swift; sourceTree = ""; }; 564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 564A1F47226B89D1001F64F1 /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; - 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; 564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; 564A1F4A226B89D1001F64F1 /* RecordPrimaryKeyNoneTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeyNoneTests.swift; sourceTree = ""; }; 564A1F4B226B89D1001F64F1 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; @@ -521,7 +517,6 @@ 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; - 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; 564A1F88226B89D8001F64F1 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 564A1F89226B89D8001F64F1 /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; 564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -569,7 +564,6 @@ 564A1FB4226B89DD001F64F1 /* AssociationHasManyThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughSQLTests.swift; sourceTree = ""; }; 564A1FB5226B89DD001F64F1 /* FTS5CustomTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizerTests.swift; sourceTree = ""; }; 564A1FB6226B89DD001F64F1 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; - 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = ""; }; 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VirtualTableModuleTests.swift; sourceTree = ""; }; 564A1FBB226B89DD001F64F1 /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; @@ -857,18 +851,16 @@ 564A1FB6226B89DD001F64F1 /* ValueObservationCombineTests.swift */, 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */, 564A1F6C226B89D5001F64F1 /* ValueObservationDatabaseValueConvertibleTests.swift */, - 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */, 564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */, 564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */, 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 56C8123924279584004FBBFF /* ValueObservationRecorder.swift */, 56C8123824279584004FBBFF /* ValueObservationRecorderTests.swift */, + 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, - 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */, 564A1F9C226B89DA001F64F1 /* ValueObservationRowTests.swift */, - 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */, 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */, ); name = GRDBTests; @@ -1095,7 +1087,6 @@ 564A2049226B89E1001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */, 564A1FF0226B89E1001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 564A1FEA226B89E1001F64F1 /* AssociationChainRowScopesTests.swift in Sources */, - 564A1FFF226B89E1001F64F1 /* ValueObservationSchedulingTests.swift in Sources */, 564A207D226B89E1001F64F1 /* ValueObservationFetchTests.swift in Sources */, 564A203C226B89E1001F64F1 /* ValueObservationReadonlyTests.swift in Sources */, 564A203B226B89E1001F64F1 /* ValueObservationCountTests.swift in Sources */, @@ -1139,6 +1130,7 @@ 564A202E226B89E1001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, + 563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */, 564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, @@ -1206,7 +1198,6 @@ 564A203F226B89E1001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */, 564A2030226B89E1001F64F1 /* DatabaseSavepointTests.swift in Sources */, 564A206A226B89E1001F64F1 /* FoundationNSStringTests.swift in Sources */, - 564A206E226B89E1001F64F1 /* ValueObservationExtentTests.swift in Sources */, 5656A802229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 564A2066226B89E1001F64F1 /* DatabaseTimestampTests.swift in Sources */, 564A204B226B89E1001F64F1 /* FoundationNSDataTests.swift in Sources */, @@ -1245,7 +1236,6 @@ 56DF0029228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, 564A1FF7226B89E1001F64F1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 564A2074226B89E1001F64F1 /* UpdateStatementTests.swift in Sources */, - 564A203E226B89E1001F64F1 /* ValueObservationReducerTests.swift in Sources */, 564A2035226B89E1001F64F1 /* Row+FoundationTests.swift in Sources */, 569BBA31228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 564A205A226B89E1001F64F1 /* QueryInterfaceRequestTests.swift in Sources */, @@ -1301,7 +1291,6 @@ 564A20A4226B8E18001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */, 564A20A5226B8E18001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 564A20A6226B8E18001F64F1 /* AssociationChainRowScopesTests.swift in Sources */, - 564A20A7226B8E18001F64F1 /* ValueObservationSchedulingTests.swift in Sources */, 564A20A8226B8E18001F64F1 /* ValueObservationFetchTests.swift in Sources */, 564A20A9226B8E18001F64F1 /* ValueObservationReadonlyTests.swift in Sources */, 564A20AA226B8E18001F64F1 /* ValueObservationCountTests.swift in Sources */, @@ -1345,6 +1334,7 @@ 564A20CD226B8E18001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, + 563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */, 564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, @@ -1412,7 +1402,6 @@ 564A210C226B8E18001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */, 564A210D226B8E18001F64F1 /* DatabaseSavepointTests.swift in Sources */, 564A210E226B8E18001F64F1 /* FoundationNSStringTests.swift in Sources */, - 564A210F226B8E18001F64F1 /* ValueObservationExtentTests.swift in Sources */, 5656A803229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 564A2110226B8E18001F64F1 /* DatabaseTimestampTests.swift in Sources */, 564A2111226B8E18001F64F1 /* FoundationNSDataTests.swift in Sources */, @@ -1451,7 +1440,6 @@ 56DF002A228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, 564A212E226B8E18001F64F1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 564A212F226B8E18001F64F1 /* UpdateStatementTests.swift in Sources */, - 564A2130226B8E18001F64F1 /* ValueObservationReducerTests.swift in Sources */, 564A2131226B8E18001F64F1 /* Row+FoundationTests.swift in Sources */, 569BBA32228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 564A2132226B8E18001F64F1 /* QueryInterfaceRequestTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 9fff6a351..e20e802d7 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 561CFAAB2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 563DE4FE231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; }; 563DE4FF231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; }; + 563F4CB7242F80030052E96C /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB6242F80030052E96C /* ValueObservationTests.swift */; }; + 563F4CB8242F80030052E96C /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB6242F80030052E96C /* ValueObservationTests.swift */; }; 564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; }; 564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; }; 564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; }; @@ -56,7 +58,6 @@ 564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F45226B89D0001F64F1 /* DatabaseValueTests.swift */; }; 564A1FFD226B89E1001F64F1 /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */; }; 564A1FFE226B89E1001F64F1 /* FilterCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F47226B89D1001F64F1 /* FilterCursorTests.swift */; }; - 564A1FFF226B89E1001F64F1 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */; }; 564A2000226B89E1001F64F1 /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */; }; 564A2001226B89E1001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4A226B89D1001F64F1 /* RecordPrimaryKeyNoneTests.swift */; }; 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4B226B89D1001F64F1 /* DerivableRequestTests.swift */; }; @@ -118,7 +119,6 @@ 564A203B226B89E1001F64F1 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */; }; 564A203C226B89E1001F64F1 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */; }; 564A203D226B89E1001F64F1 /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */; }; - 564A203E226B89E1001F64F1 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */; }; 564A203F226B89E1001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F88226B89D8001F64F1 /* AssociationBelongsToRowScopeTests.swift */; }; 564A2040226B89E1001F64F1 /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F89226B89D8001F64F1 /* StatementColumnConvertibleFetchTests.swift */; }; 564A2041226B89E1001F64F1 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */; }; @@ -166,7 +166,6 @@ 564A206B226B89E1001F64F1 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB4226B89DD001F64F1 /* AssociationHasManyThroughSQLTests.swift */; }; 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB5226B89DD001F64F1 /* FTS5CustomTokenizerTests.swift */; }; 564A206D226B89E1001F64F1 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB6226B89DD001F64F1 /* ValueObservationCombineTests.swift */; }; - 564A206E226B89E1001F64F1 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */; }; 564A206F226B89E1001F64F1 /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */; }; 564A2071226B89E1001F64F1 /* VirtualTableModuleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */; }; 564A2072226B89E1001F64F1 /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FBB226B89DD001F64F1 /* DropFirstCursorTests.swift */; }; @@ -219,7 +218,6 @@ 564A20A4226B8E18001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F92226B89D9001F64F1 /* DatabaseQueueReadOnlyTests.swift */; }; 564A20A5226B8E18001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F39226B89CF001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift */; }; 564A20A6226B8E18001F64F1 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F33226B89CF001F64F1 /* AssociationChainRowScopesTests.swift */; }; - 564A20A7226B8E18001F64F1 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */; }; 564A20A8226B8E18001F64F1 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */; }; 564A20A9226B8E18001F64F1 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */; }; 564A20AA226B8E18001F64F1 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */; }; @@ -322,7 +320,6 @@ 564A210C226B8E18001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F88226B89D8001F64F1 /* AssociationBelongsToRowScopeTests.swift */; }; 564A210D226B8E18001F64F1 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */; }; 564A210E226B8E18001F64F1 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB3226B89DC001F64F1 /* FoundationNSStringTests.swift */; }; - 564A210F226B8E18001F64F1 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */; }; 564A2110226B8E18001F64F1 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */; }; 564A2111226B8E18001F64F1 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F94226B89D9001F64F1 /* FoundationNSDataTests.swift */; }; 564A2112226B8E18001F64F1 /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */; }; @@ -355,7 +352,6 @@ 564A212D226B8E18001F64F1 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F2B226B89CF001F64F1 /* DatabaseQueueBackupTests.swift */; }; 564A212E226B8E18001F64F1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F40226B89D0001F64F1 /* DatabaseValueConvertibleDecodableTests.swift */; }; 564A212F226B8E18001F64F1 /* UpdateStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FBD226B89DE001F64F1 /* UpdateStatementTests.swift */; }; - 564A2130226B8E18001F64F1 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */; }; 564A2131226B8E18001F64F1 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F7E226B89D7001F64F1 /* Row+FoundationTests.swift */; }; 564A2132226B8E18001F64F1 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FA3226B89DB001F64F1 /* QueryInterfaceRequestTests.swift */; }; 564A2133226B8E18001F64F1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F5A226B89D3001F64F1 /* FetchRequestTests.swift */; }; @@ -425,6 +421,7 @@ 561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; + 563F4CB6242F80030052E96C /* ValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = ""; }; 564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; @@ -461,7 +458,6 @@ 564A1F45226B89D0001F64F1 /* DatabaseValueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueTests.swift; sourceTree = ""; }; 564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 564A1F47226B89D1001F64F1 /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; - 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; 564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; 564A1F4A226B89D1001F64F1 /* RecordPrimaryKeyNoneTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeyNoneTests.swift; sourceTree = ""; }; 564A1F4B226B89D1001F64F1 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; @@ -523,7 +519,6 @@ 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 564A1F86226B89D8001F64F1 /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; - 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; 564A1F88226B89D8001F64F1 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 564A1F89226B89D8001F64F1 /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; 564A1F8A226B89D9001F64F1 /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -571,7 +566,6 @@ 564A1FB4226B89DD001F64F1 /* AssociationHasManyThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughSQLTests.swift; sourceTree = ""; }; 564A1FB5226B89DD001F64F1 /* FTS5CustomTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizerTests.swift; sourceTree = ""; }; 564A1FB6226B89DD001F64F1 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; - 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = ""; }; 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VirtualTableModuleTests.swift; sourceTree = ""; }; 564A1FBB226B89DD001F64F1 /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; @@ -861,7 +855,6 @@ 564A1FB6226B89DD001F64F1 /* ValueObservationCombineTests.swift */, 564A1F84226B89D8001F64F1 /* ValueObservationCountTests.swift */, 564A1F6C226B89D5001F64F1 /* ValueObservationDatabaseValueConvertibleTests.swift */, - 564A1FB7226B89DD001F64F1 /* ValueObservationExtentTests.swift */, 564A1FC6226B89DF001F64F1 /* ValueObservationFetchTests.swift */, 564A1F59226B89D3001F64F1 /* ValueObservationMapTests.swift */, 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */, @@ -869,10 +862,9 @@ 56C8122F24279549004FBBFF /* ValueObservationRecorder.swift */, 56C8123024279549004FBBFF /* ValueObservationRecorderTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, - 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */, 564A1F9C226B89DA001F64F1 /* ValueObservationRowTests.swift */, - 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */, + 563F4CB6242F80030052E96C /* ValueObservationTests.swift */, 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */, ); name = GRDBTests; @@ -1100,7 +1092,6 @@ 564A2049226B89E1001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */, 564A1FF0226B89E1001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 564A1FEA226B89E1001F64F1 /* AssociationChainRowScopesTests.swift in Sources */, - 564A1FFF226B89E1001F64F1 /* ValueObservationSchedulingTests.swift in Sources */, 564A207D226B89E1001F64F1 /* ValueObservationFetchTests.swift in Sources */, 564A203C226B89E1001F64F1 /* ValueObservationReadonlyTests.swift in Sources */, 564A203B226B89E1001F64F1 /* ValueObservationCountTests.swift in Sources */, @@ -1211,7 +1202,6 @@ 564A203F226B89E1001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */, 564A2030226B89E1001F64F1 /* DatabaseSavepointTests.swift in Sources */, 564A206A226B89E1001F64F1 /* FoundationNSStringTests.swift in Sources */, - 564A206E226B89E1001F64F1 /* ValueObservationExtentTests.swift in Sources */, 5656A805229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 564A2066226B89E1001F64F1 /* DatabaseTimestampTests.swift in Sources */, 564A204B226B89E1001F64F1 /* FoundationNSDataTests.swift in Sources */, @@ -1243,6 +1233,7 @@ 564A1FFE226B89E1001F64F1 /* FilterCursorTests.swift in Sources */, 564A208A226B89E1001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, 564A2092226B89E1001F64F1 /* DatabasePoolConcurrencyTests.swift in Sources */, + 563F4CB7242F80030052E96C /* ValueObservationTests.swift in Sources */, 564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */, 564A2007226B89E1001F64F1 /* FoundationDataTests.swift in Sources */, 564A201A226B89E1001F64F1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1250,7 +1241,6 @@ 564A1FE2226B89E1001F64F1 /* DatabaseQueueBackupTests.swift in Sources */, 564A1FF7226B89E1001F64F1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 564A2074226B89E1001F64F1 /* UpdateStatementTests.swift in Sources */, - 564A203E226B89E1001F64F1 /* ValueObservationReducerTests.swift in Sources */, 564A2035226B89E1001F64F1 /* Row+FoundationTests.swift in Sources */, 564A205A226B89E1001F64F1 /* QueryInterfaceRequestTests.swift in Sources */, 569BBA2E228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, @@ -1306,7 +1296,6 @@ 564A20A4226B8E18001F64F1 /* DatabaseQueueReadOnlyTests.swift in Sources */, 564A20A5226B8E18001F64F1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 564A20A6226B8E18001F64F1 /* AssociationChainRowScopesTests.swift in Sources */, - 564A20A7226B8E18001F64F1 /* ValueObservationSchedulingTests.swift in Sources */, 564A20A8226B8E18001F64F1 /* ValueObservationFetchTests.swift in Sources */, 564A20A9226B8E18001F64F1 /* ValueObservationReadonlyTests.swift in Sources */, 564A20AA226B8E18001F64F1 /* ValueObservationCountTests.swift in Sources */, @@ -1417,7 +1406,6 @@ 564A210C226B8E18001F64F1 /* AssociationBelongsToRowScopeTests.swift in Sources */, 564A210D226B8E18001F64F1 /* DatabaseSavepointTests.swift in Sources */, 564A210E226B8E18001F64F1 /* FoundationNSStringTests.swift in Sources */, - 564A210F226B8E18001F64F1 /* ValueObservationExtentTests.swift in Sources */, 5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 564A2110226B8E18001F64F1 /* DatabaseTimestampTests.swift in Sources */, 564A2111226B8E18001F64F1 /* FoundationNSDataTests.swift in Sources */, @@ -1449,6 +1437,7 @@ 564A2126226B8E18001F64F1 /* FilterCursorTests.swift in Sources */, 564A2127226B8E18001F64F1 /* MutablePersistableRecordChangesTests.swift in Sources */, 564A2128226B8E18001F64F1 /* DatabasePoolConcurrencyTests.swift in Sources */, + 563F4CB8242F80030052E96C /* ValueObservationTests.swift in Sources */, 564A2129226B8E18001F64F1 /* RowCopiedFromStatementTests.swift in Sources */, 564A212A226B8E18001F64F1 /* FoundationDataTests.swift in Sources */, 564A212B226B8E18001F64F1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1456,7 +1445,6 @@ 564A212D226B8E18001F64F1 /* DatabaseQueueBackupTests.swift in Sources */, 564A212E226B8E18001F64F1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 564A212F226B8E18001F64F1 /* UpdateStatementTests.swift in Sources */, - 564A2130226B8E18001F64F1 /* ValueObservationReducerTests.swift in Sources */, 564A2131226B8E18001F64F1 /* Row+FoundationTests.swift in Sources */, 564A2132226B8E18001F64F1 /* QueryInterfaceRequestTests.swift in Sources */, 569BBA2F228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift index 75e845bad..4a62de833 100644 --- a/Tests/GRDBTests/ValueObservationCombineTests.swift +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -658,12 +658,13 @@ class ValueObservationCombineTests: GRDBTestCase { func testHeterogeneusCombine2() throws { struct V1 { } struct V2 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation = ValueObservation.combine(observation1, observation2) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }) var value: (V1, V2)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -673,13 +674,14 @@ class ValueObservationCombineTests: GRDBTestCase { struct V1 { } struct V2 { } struct V3 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation = ValueObservation.combine(observation1, observation2, observation3) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }) var value: (V1, V2, V3)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -690,14 +692,15 @@ class ValueObservationCombineTests: GRDBTestCase { struct V2 { } struct V3 { } struct V4 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation = ValueObservation.combine(observation1, observation2, observation3, observation4) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }) var value: (V1, V2, V3, V4)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -709,15 +712,16 @@ class ValueObservationCombineTests: GRDBTestCase { struct V3 { } struct V4 { } struct V5 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }) var value: (V1, V2, V3, V4, V5)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -730,16 +734,17 @@ class ValueObservationCombineTests: GRDBTestCase { struct V4 { } struct V5 { } struct V6 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation6 = ValueObservation.tracking { _ in V6() } - let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }, + ValueObservation.tracking { _ in V6() }) var value: (V1, V2, V3, V4, V5, V6)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -753,17 +758,18 @@ class ValueObservationCombineTests: GRDBTestCase { struct V5 { } struct V6 { } struct V7 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation6 = ValueObservation.tracking { _ in V6() } - let observation7 = ValueObservation.tracking { _ in V7() } - let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }, + ValueObservation.tracking { _ in V6() }, + ValueObservation.tracking { _ in V7() }) var value: (V1, V2, V3, V4, V5, V6, V7)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -778,18 +784,19 @@ class ValueObservationCombineTests: GRDBTestCase { struct V6 { } struct V7 { } struct V8 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation6 = ValueObservation.tracking { _ in V6() } - let observation7 = ValueObservation.tracking { _ in V7() } - let observation8 = ValueObservation.tracking { _ in V8() } - let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7, observation8) + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }, + ValueObservation.tracking { _ in V6() }, + ValueObservation.tracking { _ in V7() }, + ValueObservation.tracking { _ in V8() }) var value: (V1, V2, V3, V4, V5, V6, V7, V8)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -805,6 +812,7 @@ class ValueObservationCombineTests: GRDBTestCase { var value: Combined? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -822,6 +830,7 @@ class ValueObservationCombineTests: GRDBTestCase { var value: Combined? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -841,6 +850,7 @@ class ValueObservationCombineTests: GRDBTestCase { var value: Combined? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -862,6 +872,7 @@ class ValueObservationCombineTests: GRDBTestCase { var value: Combined? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 3cf00eaed..0f5328e92 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -259,60 +259,4 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { try db.execute(sql: "UPDATE t SET name = 'qux'") }) } - - func testViewOptimization() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { - try $0.execute(sql: """ - CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT); - CREATE VIEW v AS SELECT * FROM t - """) - } - - var results: [[Name]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - // Test that view v is included in the request region - let request = SQLRequest(sql: "SELECT name FROM v ORDER BY id") - try dbQueue.inDatabase { db in - let region = try request.databaseRegion(db) - XCTAssertEqual(region.description, "t(id,name),v(id,name)") - } - - // Test that view v is not included in the observed region. - // This optimization helps observation of views that feed from a - // single table. - let observation = ValueObservation.tracking(request.fetchAll) - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { names in - results.append(names) - notificationExpectation.fulfill() - }) - let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion!.description, "t(id,name)") // view is not tracked - try withExtendedLifetime(observer) { - // Test view observation - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map(\.rawValue)}, [ - [], - ["foo"], - ["foo", "bar"], - ["bar"]]) - } - } } diff --git a/Tests/GRDBTests/ValueObservationExtentTests.swift b/Tests/GRDBTests/ValueObservationExtentTests.swift deleted file mode 100644 index 1e88592b3..000000000 --- a/Tests/GRDBTests/ValueObservationExtentTests.swift +++ /dev/null @@ -1,59 +0,0 @@ -import XCTest -#if GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - #if SWIFT_PACKAGE - import CSQLite - #else - import SQLite3 - #endif - import GRDB -#endif - -class ValueObservationExtentTests: GRDBTestCase { - func testExtentObserverLifetime() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer process - var changesCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - // Create an observation - let observation = ValueObservation.tracking { - try Int.fetchOne($0, sql: "SELECT * FROM t") - } - - // Start observation and deallocate observer after second change - var observer: TransactionObserver? - observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - changesCount += 1 - if changesCount == 2 { - observer = nil - } - notificationExpectation.fulfill() - }) - - // notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - // not notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - // Avoid "Variable 'observer' was written to, but never read" warning - _ = observer - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(changesCount, 2) - } -} diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index 04d08279f..f400ccb88 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -13,9 +13,7 @@ import XCTest class ValueObservationMapTests: GRDBTestCase { func testMap() throws { let valueObservation = ValueObservation - .tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } .map { "\($0)" } try assertValueObservation( @@ -33,15 +31,8 @@ class ValueObservationMapTests: GRDBTestCase { func testMapPreservesConfiguration() { var observation = ValueObservation.tracking { _ in } observation.requiresWriteAccess = true - observation.scheduling = .unsafe let mappedObservation = observation.map { _ in } XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) - switch mappedObservation.scheduling { - case .unsafe: - break - default: - XCTFail() - } } } diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 282afdd0e..b4384aab6 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -125,6 +125,28 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { recordedUpdates: { db in try db.execute(sql: "DELETE FROM child") }) + + // The fundamental technique for removing duplicates of non-Equatable types + try assertValueObservation( + ValueObservation + .tracking { db in try Row.fetchOne(db, request) } + .removeDuplicates() + .map { row in row.map(ParentInfo.init(row:)) }, + records: [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: []), + ], + setup: setup, + recordedUpdates: { db in + try db.execute(sql: "DELETE FROM child") + }) } func testAllRecordsWithPrefetchedRows() throws { @@ -162,5 +184,39 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { recordedUpdates: { db in try db.execute(sql: "DELETE FROM child") }) + + // The fundamental technique for removing duplicates of non-Equatable types + try assertValueObservation( + ValueObservation + .tracking { db in try Row.fetchAll(db, request) } + .removeDuplicates() + .map { rows in rows.map(ParentInfo.init(row:)) }, + records: [ + [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: [ + Child(id: 3, parentId: 2, name: "barA"), + ]), + ], + [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: []), + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: []), + ], + ], + setup: setup, + recordedUpdates: { db in + try db.execute(sql: "DELETE FROM child") + }) } } diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index 526108904..a61033456 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -49,6 +49,7 @@ class ValueObservationRecordTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 1") }) + // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( ValueObservation .tracking { try Row.fetchAll($0, request) } @@ -101,6 +102,7 @@ class ValueObservationRecordTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t") }) + // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( ValueObservation .tracking { try Row.fetchOne($0, request) } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 591747bed..d9b51ec01 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -12,6 +12,7 @@ public class ValueObservationRecorder { private struct RecorderExpectation { var expectation: XCTestExpectation var remainingCount: Int? // nil for error expectation + var isIncluded: ((Value) -> Bool)? // nil for error expectation } /// The recorder state @@ -47,13 +48,21 @@ public class ValueObservationRecorder { state.values.append(value) - if let exp = state.recorderExpectation, let remainingCount = exp.remainingCount { + if let exp = state.recorderExpectation, + let remainingCount = exp.remainingCount, + let isIncluded = exp.isIncluded + { assert(remainingCount > 0) - exp.expectation.fulfill() - if remainingCount > 1 { - state.recorderExpectation = RecorderExpectation(expectation: exp.expectation, remainingCount: remainingCount - 1) - } else { - state.recorderExpectation = nil + if isIncluded(value) { + exp.expectation.fulfill() + if remainingCount > 1 { + state.recorderExpectation = RecorderExpectation( + expectation: exp.expectation, + remainingCount: remainingCount - 1, + isIncluded: isIncluded) + } else { + state.recorderExpectation = nil + } } } } @@ -77,7 +86,7 @@ public class ValueObservationRecorder { // MARK: ValueObservationExpectation API - func fulfillOnValue(_ expectation: XCTestExpectation, includingConsumed: Bool) { + func fulfillOnValue(_ expectation: XCTestExpectation, includingConsumed: Bool, isIncluded: @escaping (Value) -> Bool) { synchronized { preconditionCanFulfillExpectation() @@ -88,16 +97,20 @@ public class ValueObservationRecorder { return } - let values = state.values + let values = state.values.filter(isIncluded) + let consumedValues = state.values[0.. 0 { - state.recorderExpectation = RecorderExpectation(expectation: expectation, remainingCount: remainingCount) + state.recorderExpectation = RecorderExpectation( + expectation: expectation, + remainingCount: remainingCount, + isIncluded: isIncluded) } else { state.recorderExpectation = nil } @@ -113,7 +126,10 @@ public class ValueObservationRecorder { return } - state.recorderExpectation = RecorderExpectation(expectation: expectation, remainingCount: nil) + state.recorderExpectation = RecorderExpectation( + expectation: expectation, + remainingCount: nil, + isIncluded: nil) } } @@ -188,19 +204,42 @@ extension ValueObservationRecorder { } public func prefix(_ maxLength: Int) -> ValueObservationExpectations.Prefix { - ValueObservationExpectations.Prefix(recorder: self, maxLength: maxLength) + ValueObservationExpectations.Prefix( + recorder: self, + expectedFulfillmentCount: maxLength, + isIncluded: { _ in true }) + } + + public func prefix(until predicate: @escaping (Value) -> Bool) -> ValueObservationExpectations.Prefix { + ValueObservationExpectations.Prefix( + recorder: self, + expectedFulfillmentCount: 1, + isIncluded: predicate) } } // MARK: - ValueObservation + ValueObservationRecorder extension ValueObservation { - public func record(in reader: DatabaseReader) -> ValueObservationRecorder { + public func record( + in reader: DatabaseReader, + scheduler: ValueObservationScheduler = .async(onQueue: .main), + onError: ((Error) -> Void)? = nil, + onChange: ((Reducer.Value) -> Void)? = nil) + -> ValueObservationRecorder + { let recorder = ValueObservationRecorder() let observer = start( in: reader, - onError: recorder.onError, - onChange: recorder.onChange) + scheduler: scheduler, + onError: { + onError?($0) + recorder.onError($0) + }, + onChange: { + onChange?($0) + recorder.onChange($0) + }) recorder.receive(observer) return recorder } @@ -296,7 +335,7 @@ extension XCTestCase { _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) - where + where R: BidirectionalCollection, E: BidirectionalCollection, R.Element == E.Element, @@ -334,109 +373,273 @@ extension XCTestCase { extension GRDBTestCase { func assertValueObservation( - _ valueObservation: ValueObservation, + _ observation: ValueObservation, records expectedValues: [Reducer.Value], setup: (Database) throws -> Void, - recordedUpdates: (Database) throws -> Void, + recordedUpdates: @escaping (Database) throws -> Void, file: StaticString = #file, line: UInt = #line) throws where Reducer.Value: Equatable { - func testRecordingEqual(writer: DatabaseWriter, observation: ValueObservation) throws { - try writer.write(setup) - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction(recordedUpdates) - let expectation = recorder.next(expectedValues.count) - let values = try wait(for: expectation, timeout: 0.3) - XCTAssertEqual(values, expectedValues, file: file, line: line) - } - - func testRecordingMatch(writer: DatabaseWriter, observation: ValueObservation) throws { - try writer.write(setup) - let recorder = observation.record(in: writer) - try writer.writeWithoutTransaction(recordedUpdates) - let expectation = recorder - .prefix(expectedValues.count + 2 /* pool may perform double initial fetch */) - .inverted - let values = try wait(for: expectation, timeout: 0.3) - assertValueObservationRecordingMatch( - recorded: values, - expected: expectedValues, - file: file, line: line) - } - - do { - var observation = valueObservation - observation.scheduling = .mainQueue - try testRecordingEqual(writer: DatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabasePool(), observation: observation) - } - - do { - var observation = valueObservation - observation.scheduling = .async(onQueue: .main) - try testRecordingEqual(writer: DatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) - if valueObservation.requiresWriteAccess || !valueObservation.makeReducer().isObservedRegionDeterministic { - try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + func test( + observation: ValueObservation, + scheduler: ValueObservationScheduler, + testValueDispatching: @escaping () -> Void) throws + { + func testRecordingEqualWhenWriteAfterStart(writer: DatabaseWriter) throws { + try writer.write(setup) + + var value: Reducer.Value? + let recorder = observation.record( + in: writer, + scheduler: scheduler, + onChange: { + testValueDispatching() + value = $0 + }) + + // Test that initial value is set when scheduler is immediate + if scheduler.immediateInitialValue() { + XCTAssertNotNil(value) + } + + // Perform writes after start + try writer.writeWithoutTransaction(recordedUpdates) + + let expectation = recorder.next(expectedValues.count) + let values = try wait(for: expectation, timeout: 0.3) + XCTAssertEqual( + values, expectedValues, + "\(#function), \(writer), \(scheduler)", file: file, line: line) + } + + func testRecordingEqualWhenWriteAfterFirstValue(writer: DatabaseWriter) throws { + try writer.write(setup) + + var valueCount = 0 + var value: Reducer.Value? + let recorder = observation.record( + in: writer, + scheduler: scheduler, + onChange: { [unowned writer] in + testValueDispatching() + valueCount += 1 + if valueCount == 1 { + // Perform writes after initial value + try! writer.writeWithoutTransaction(recordedUpdates) + } + value = $0 + }) + + // Test that initial value is set when scheduler is immediate + if scheduler.immediateInitialValue() { + XCTAssertNotNil(value) + } + + let expectation = recorder.next(expectedValues.count) + let values = try wait(for: expectation, timeout: 0.3) + XCTAssertEqual( + values, expectedValues, + "\(#function), \(writer), \(scheduler)", file: file, line: line) + } + + func testRecordingMatchWhenWriteAfterStart(writer: DatabaseWriter) throws { + try writer.write(setup) + + var value: Reducer.Value? + let recorder = observation.record( + in: writer, + scheduler: scheduler, + onChange: { + testValueDispatching() + value = $0 + }) + + // Test that initial value is set when scheduler is immediate + if scheduler.immediateInitialValue() { + XCTAssertNotNil(value) + } + + try writer.writeWithoutTransaction(recordedUpdates) + + let expectation = recorder + .prefix(expectedValues.count + 2 /* pool may perform double initial fetch */) + .inverted + let values = try wait(for: expectation, timeout: 0.3) + + if scheduler.immediateInitialValue() { + XCTAssertEqual(values.first, expectedValues.first) + } + + assertValueObservationRecordingMatch( + recorded: values, + expected: expectedValues, + "\(#function), \(writer), \(scheduler)", file: file, line: line) + } + + func testRecordingMatchWhenWriteAfterFirstValue(writer: DatabaseWriter) throws { + try writer.write(setup) + + var valueCount = 0 + var value: Reducer.Value? + let recorder = observation.record( + in: writer, + scheduler: scheduler, + onChange: { [unowned writer] in + testValueDispatching() + valueCount += 1 + if valueCount == 1 { + // Perform writes after initial value + try! writer.writeWithoutTransaction(recordedUpdates) + } + value = $0 + }) + + // Test that initial value is set when scheduler is immediate + if scheduler.immediateInitialValue() { + XCTAssertNotNil(value) + } + + let recordedValues: [Reducer.Value] + let lastExpectedValue = expectedValues.last! + let waitForLast = expectedValues.firstIndex(of: lastExpectedValue) == expectedValues.count - 1 + if waitForLast { + // Optimization! + let expectation = recorder.prefix(until: { $0 == lastExpectedValue } ) + recordedValues = try wait(for: expectation, timeout: 1) + } else { + // Slow! + let expectation = recorder + .prefix(expectedValues.count + 2 /* pool may perform double initial fetch */) + .inverted + #if SQLITE_HAS_CODEC || GRDBCUSTOMSQLITE + // debug SQLite builds can be *very* slow + recordedValues = try wait(for: expectation, timeout: 1) + #else + recordedValues = try wait(for: expectation, timeout: 0.3) + #endif + } + + XCTAssertEqual(recordedValues.first, expectedValues.first) + + assertValueObservationRecordingMatch( + recorded: recordedValues, + expected: expectedValues, + "\(#function), \(writer), \(scheduler)", file: file, line: line) + } + + try testRecordingEqualWhenWriteAfterStart(writer: DatabaseQueue()) + try testRecordingEqualWhenWriteAfterFirstValue(writer: DatabaseQueue()) + + try testRecordingEqualWhenWriteAfterStart(writer: makeDatabaseQueue()) + try testRecordingEqualWhenWriteAfterFirstValue(writer: makeDatabaseQueue()) + + if observation.requiresWriteAccess { + try testRecordingEqualWhenWriteAfterStart(writer: makeDatabasePool()) + try testRecordingEqualWhenWriteAfterFirstValue(writer: makeDatabasePool()) } else { - // DatabasePool performs an immediate async fetch and may miss initial changes - try testRecordingMatch(writer: makeDatabasePool(), observation: observation) + // DatabasePool may miss some changes + try testRecordingMatchWhenWriteAfterStart(writer: makeDatabasePool()) + try testRecordingMatchWhenWriteAfterFirstValue(writer: makeDatabasePool()) } } do { - var observation = valueObservation - observation.scheduling = .unsafe - try testRecordingEqual(writer: DatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + try test( + observation: observation, + scheduler: .immediate, + testValueDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) + } + + do { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + try test( + observation: observation, + scheduler: .async(onQueue: .main), + testValueDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) + } + + do { + let queue = DispatchQueue(label: "custom") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + try test( + observation: observation, + scheduler: .async(onQueue: queue), + testValueDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } } func assertValueObservation( - _ valueObservation: ValueObservation, + _ observation: ValueObservation, fails testFailure: (Failure, DatabaseWriter) throws -> Void, setup: (Database) throws -> Void, file: StaticString = #file, line: UInt = #line) throws { - func test(writer: DatabaseWriter, observation: ValueObservation) throws { - try writer.write(setup) - let recorder = observation.record(in: writer) - let (_, error) = try wait(for: recorder.failure(), timeout: 0.3) - if let error = error as? Failure { - try testFailure(error, writer) - } else { - throw error + func test( + observation: ValueObservation, + scheduler: ValueObservationScheduler, + testErrorDispatching: @escaping () -> Void) throws + { + func test(writer: DatabaseWriter) throws { + try writer.write(setup) + + let recorder = observation.record( + in: writer, + scheduler: scheduler, + onError: { _ in testErrorDispatching() }) + + let (_, error) = try wait(for: recorder.failure(), timeout: 0.3) + if let error = error as? Failure { + try testFailure(error, writer) + } else { + throw error + } } + + try test(writer: DatabaseQueue()) + try test(writer: makeDatabaseQueue()) + try test(writer: makeDatabasePool()) } do { - var observation = valueObservation - observation.scheduling = .mainQueue - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + try test( + observation: observation, + scheduler: .immediate, + testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } do { - var observation = valueObservation - observation.scheduling = .async(onQueue: .main) - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + try test( + observation: observation, + scheduler: .async(onQueue: .main), + testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } do { - var observation = valueObservation - observation.scheduling = .unsafe - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) + let queue = DispatchQueue(label: "custom") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + try test( + observation: observation, + scheduler: .async(onQueue: queue), + testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } } } @@ -468,7 +671,7 @@ extension ValueObservationExpectations { let recorder: ValueObservationRecorder public func _setup(_ expectation: XCTestExpectation) { - recorder.fulfillOnValue(expectation, includingConsumed: false) + recorder.fulfillOnValue(expectation, includingConsumed: false, isIncluded: { _ in true }) } public func get() throws -> Value { @@ -497,7 +700,7 @@ extension ValueObservationExpectations { public func _setup(_ expectation: XCTestExpectation) { expectation.isInverted = true - recorder.fulfillOnValue(expectation, includingConsumed: false) + recorder.fulfillOnValue(expectation, includingConsumed: false, isIncluded: { _ in true }) } public func get() throws { @@ -531,7 +734,7 @@ extension ValueObservationExpectations { expectation.fulfill() } else { expectation.expectedFulfillmentCount = count - recorder.fulfillOnValue(expectation, includingConsumed: false) + recorder.fulfillOnValue(expectation, includingConsumed: false, isIncluded: { _ in true }) } } @@ -554,31 +757,43 @@ extension ValueObservationExpectations { public struct Prefix: ValueObservationExpectation { let recorder: ValueObservationRecorder - let maxLength: Int + let expectedFulfillmentCount: Int + let isIncluded: (Value) -> Bool - init(recorder: ValueObservationRecorder, maxLength: Int) { - precondition(maxLength >= 0, "Invalid negative count") + init(recorder: ValueObservationRecorder, expectedFulfillmentCount: Int, isIncluded: @escaping (Value) -> Bool) { + precondition(expectedFulfillmentCount >= 0, "Invalid negative count") self.recorder = recorder - self.maxLength = maxLength + self.expectedFulfillmentCount = expectedFulfillmentCount + self.isIncluded = isIncluded } public func _setup(_ expectation: XCTestExpectation) { - if maxLength == 0 { + if expectedFulfillmentCount == 0 { // Such an expectation is immediately fulfilled, by essence. expectation.expectedFulfillmentCount = 1 expectation.fulfill() } else { - expectation.expectedFulfillmentCount = maxLength - recorder.fulfillOnValue(expectation, includingConsumed: true) + expectation.expectedFulfillmentCount = expectedFulfillmentCount + recorder.fulfillOnValue(expectation, includingConsumed: true, isIncluded: isIncluded) } } public func get() throws -> [Value] { - try recorder.value { (values, error, remainingValues, consume) in - if values.count >= maxLength { - let extraCount = max(maxLength + remainingValues.count - values.count, 0) + if expectedFulfillmentCount == 0 { + return [] + } + + return try recorder.value { (values, error, remainingValues, consume) in + let includedValues = values.filter(isIncluded) + if includedValues.count >= expectedFulfillmentCount { + let matchedCount = values + .indices + .filter { isIncluded(values[$0]) } + .prefix(expectedFulfillmentCount) + .last! + 1 + let extraCount = max(matchedCount + remainingValues.count - values.count, 0) consume(extraCount) - return Array(values.prefix(maxLength)) + return Array(values.prefix(matchedCount)) } if let error = error { throw error diff --git a/Tests/GRDBTests/ValueObservationRecorderTests.swift b/Tests/GRDBTests/ValueObservationRecorderTests.swift index 4f3bc843b..51e87afba 100644 --- a/Tests/GRDBTests/ValueObservationRecorderTests.swift +++ b/Tests/GRDBTests/ValueObservationRecorderTests.swift @@ -334,9 +334,9 @@ class ValueObservationRecorderTests: FailureTestCase { } catch ValueRecordingError.notEnoughValues { } } - // MARK: - Prefix + // MARK: - Prefix(maxLength) - func testPrefixSuccess() throws { + func testPrefixMaxLengthSuccess() throws { struct CustomError: Error { } do { let recorder = ValueObservationRecorder() @@ -374,19 +374,19 @@ class ValueObservationRecorderTests: FailureTestCase { } } - func testPrefixError() throws { + func testPrefixMaxLengthError() throws { struct CustomError: Error { } do { let recorder = ValueObservationRecorder() recorder.onError(CustomError()) - _ = try recorder.next(2).get() + _ = try recorder.prefix(2).get() XCTFail("Expected error") } catch is CustomError { } do { let recorder = ValueObservationRecorder() recorder.onChange("foo") recorder.onError(CustomError()) - _ = try recorder.next(2).get() + _ = try recorder.prefix(2).get() XCTFail("Expected error") } catch is CustomError { } do { @@ -394,7 +394,7 @@ class ValueObservationRecorderTests: FailureTestCase { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { recorder.onError(CustomError()) } - _ = try wait(for: recorder.next(2), timeout: 0.5) + _ = try wait(for: recorder.prefix(2), timeout: 0.5) XCTFail("Expected error") } catch is CustomError { } do { @@ -405,42 +405,36 @@ class ValueObservationRecorderTests: FailureTestCase { recorder.onError(CustomError()) } } - _ = try wait(for: recorder.next(2), timeout: 0.5) + _ = try wait(for: recorder.prefix(2), timeout: 0.5) XCTFail("Expected error") } catch is CustomError { } } - func testPrefixTimeout() throws { + func testPrefixMaxLengthTimeout() throws { try assertFailure("Asynchronous wait failed") { - do { - let recorder = ValueObservationRecorder() - _ = try wait(for: recorder.next(2), timeout: 0.1) - XCTFail("Expected error") - } catch ValueRecordingError.notEnoughValues { } + let recorder = ValueObservationRecorder() + let values = try wait(for: recorder.prefix(2), timeout: 0.1) + XCTAssertEqual(values, []) } try assertFailure("Asynchronous wait failed") { - do { - let recorder = ValueObservationRecorder() + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + let values = try wait(for: recorder.prefix(2), timeout: 0.1) + XCTAssertEqual(values, ["foo"]) + } + try assertFailure("Asynchronous wait failed") { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { recorder.onChange("foo") - _ = try wait(for: recorder.next(2), timeout: 0.1) - XCTFail("Expected error") - } catch ValueRecordingError.notEnoughValues { } - } - try assertFailure("Asynchronous wait failed") { - do { - let recorder = ValueObservationRecorder() - DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { - recorder.onChange("foo") - } - _ = try wait(for: recorder.next(2), timeout: 0.5) - XCTFail("Expected error") - } catch ValueRecordingError.notEnoughValues { } + } + let values = try wait(for: recorder.prefix(2), timeout: 0.5) + XCTAssertEqual(values, ["foo"]) } } - // MARK: - Prefix Inverted + // MARK: - Prefix(maxLength) Inverted - func testPrefixInvertedSuccess() throws { + func testPrefixMaxLengthInvertedSuccess() throws { do { let recorder = ValueObservationRecorder() try XCTAssertEqual(recorder.prefix(1).inverted.get(), []) @@ -459,7 +453,7 @@ class ValueObservationRecorderTests: FailureTestCase { } } - func testPrefixInvertedError() throws { + func testPrefixMaxLengthInvertedError() throws { struct CustomError: Error { } do { let recorder = ValueObservationRecorder() @@ -476,7 +470,7 @@ class ValueObservationRecorderTests: FailureTestCase { } catch is CustomError { } } - func testPrefixInvertedTimeout() throws { + func testPrefixMaxLengthInvertedTimeout() throws { struct CustomError: Error { } do { let recorder = ValueObservationRecorder() @@ -528,6 +522,96 @@ class ValueObservationRecorderTests: FailureTestCase { } } + // MARK: - Prefix(maxLength) + + func testPrefixUntilSuccess() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + try XCTAssertEqual(recorder.prefix(until: { $0 == "foo" }).get(), ["foo"]) + recorder.onChange("bar") + recorder.onChange("baz") + try XCTAssertEqual(recorder.prefix(until: { $0 == "foo" }).get(), ["foo"]) + try XCTAssertEqual(recorder.prefix(until: { $0 == "bar" }).get(), ["foo", "bar"]) + try XCTAssertEqual(recorder.prefix(until: { $0 == "baz" }).get(), ["foo", "bar", "baz"]) + } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + try XCTAssertEqual(recorder.prefix(until: { $0 == "foo" }).get(), ["foo"]) + } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("bar") + } + } + try XCTAssertEqual(wait(for: recorder.prefix(until: { $0 == "bar" }), timeout: 0.5), ["foo", "bar"]) + } + } + + func testPrefixUntilError() throws { + struct CustomError: Error { } + do { + let recorder = ValueObservationRecorder() + recorder.onError(CustomError()) + _ = try recorder.prefix(until: { $0 == "bar" }).get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + recorder.onError(CustomError()) + _ = try recorder.prefix(until: { $0 == "bar" }).get() + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + _ = try wait(for: recorder.prefix(until: { $0 == "bar" }), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + do { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onError(CustomError()) + } + } + _ = try wait(for: recorder.prefix(until: { $0 == "bar" }), timeout: 0.5) + XCTFail("Expected error") + } catch is CustomError { } + } + + func testPrefixUntilTimeout() throws { + try assertFailure("Asynchronous wait failed") { + let recorder = ValueObservationRecorder() + let values = try wait(for: recorder.prefix(until: { $0 == "bar" }), timeout: 0.1) + XCTAssertEqual(values, []) + } + try assertFailure("Asynchronous wait failed") { + let recorder = ValueObservationRecorder() + recorder.onChange("foo") + let values = try wait(for: recorder.prefix(until: { $0 == "bar" }), timeout: 0.1) + XCTAssertEqual(values, ["foo"]) + } + try assertFailure("Asynchronous wait failed") { + let recorder = ValueObservationRecorder() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { + recorder.onChange("foo") + } + let values = try wait(for: recorder.prefix(until: { $0 == "bar" }), timeout: 0.5) + XCTAssertEqual(values, ["foo"]) + } + } + // MARK: - Failure func testFailureSuccess() throws { diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift deleted file mode 100644 index 6a000d79d..000000000 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ /dev/null @@ -1,326 +0,0 @@ -import XCTest -import Dispatch -#if GRDBCUSTOMSQLITE - @testable import GRDBCustomSQLite -#else - #if SWIFT_PACKAGE - import CSQLite - #else - import SQLite3 - #endif - @testable import GRDB -#endif - -class ValueObservationReducerTests: GRDBTestCase { - func testReducer() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer process - var fetchCount = 0 - var reduceCount = 0 - var errors: [Error] = [] - var changes: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - // A reducer which tracks its progress - let reducer = AnyValueReducer( - fetch: { db -> Int in - fetchCount += 1 - // test for database access - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! - }, - value: { count -> String? in - reduceCount += 1 - if count == 3 { - // test that reducer can drop values - return nil - } - // test that the fetched type and the notified type can be different - return count.description - }) - - // Create an observation - let observation = ValueObservation(makeReducer: { reducer }) - - // Start observation - let observer = observation.start( - in: dbWriter, - onError: { - errors.append($0) - notificationExpectation.fulfill() - }, - onChange: { - changes.append($0) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - // Test that default config synchronously notifies initial value - XCTAssertEqual(fetchCount, 1) - XCTAssertEqual(reduceCount, 1) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0"]) - - try dbWriter.writeWithoutTransaction { db in - // Test a 1st notified transaction - try db.inTransaction { - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - return .commit - } - - // Test an untracked transaction - try db.inTransaction { - try db.execute(sql: "CREATE TABLE ignored(a)") - return .commit - } - - // Test a dropped transaction - try db.inTransaction { - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - return .commit - } - - // Test a rollbacked transaction - try db.inTransaction { - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - return .rollback - } - - // Test a 2nd notified transaction - try db.inTransaction { - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - return .commit - } - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(fetchCount, 4) - XCTAssertEqual(reduceCount, 4) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0", "1", "5"]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testInitialErrorWithErrorHandling() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // Create an observation - struct TestError: Error { } - let observation = ValueObservation.tracking { _ in throw TestError() } - - // Start observation - var error: TestError? - _ = observation.start( - in: dbWriter, - onError: { error = $0 as? TestError }, - onChange: { _ in }) - XCTAssertNotNil(error) - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testSuccessThenErrorThenSuccess() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer process - var errors: [Error] = [] - var changes: [Void] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - var nextError: Error? = nil // If not null, observation throws an error - let observation = ValueObservation.tracking { - _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") - if let error = nextError { - nextError = nil - throw error - } - } - - // Start observation - let observer = observation.start( - in: dbWriter, - onError: { - errors.append($0) - notificationExpectation.fulfill() - }, - onChange: { - changes.append($0) - notificationExpectation.fulfill() - }) - - try withExtendedLifetime(observer) { - struct TestError: Error { } - nextError = TestError() - try dbWriter.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errors.count, 1) - XCTAssertEqual(changes.count, 2) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testReducerQueueLabel() throws { - func test(_ dbWriter: DatabaseWriter, expectedLabels: [String]) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let reduceExpectation = expectation(description: "notification") - reduceExpectation.assertForOverFulfill = true - reduceExpectation.expectedFulfillmentCount = expectedLabels.count - - var labels: [String] = [] - let reducer = AnyValueReducer( - fetch: { _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") }, - value: { _ in - // This test CAN break in future releases: the dispatch queue labels - // are documented to be a debug-only tool. - if let label = String(utf8String: __dispatch_queue_get_label(nil)) { - labels.append(label) - } - reduceExpectation.fulfill() - }) - let observation = ValueObservation(makeReducer: { reducer }) - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in }) - try withExtendedLifetime(observer) { - try dbWriter.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(labels, expectedLabels) - } - } - do { - // dbQueue with default label - dbConfiguration.label = nil - let dbQueue = try makeDatabaseQueue() - try test(dbQueue, expectedLabels: ["GRDB.DatabaseQueue", "GRDB.ValueObservation.reducer"]) - } - do { - // dbQueue with custom label - dbConfiguration.label = "Custom" - let dbQueue = try makeDatabaseQueue() - try test(dbQueue, expectedLabels: ["Custom", "Custom.ValueObservation.reducer"]) - } - do { - // dbPool with default label - dbConfiguration.label = nil - let dbPool = try makeDatabasePool() - try test(dbPool, expectedLabels: ["GRDB.DatabasePool.writer", "GRDB.ValueObservation.reducer"]) - } - do { - // dbPool with custom label - dbConfiguration.label = "Custom" - let dbPool = try makeDatabasePool() - try test(dbPool, expectedLabels: ["Custom.writer", "Custom.ValueObservation.reducer"]) - } - } - - func testObserverInvalidation1() throws { - // Test that observation stops when observer is deallocated - func test(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let notificationExpectation = expectation(description: "notification") - notificationExpectation.isInverted = true - notificationExpectation.expectedFulfillmentCount = 2 - - do { - var observer: TransactionObserver? = nil - _ = observer // Avoid "Variable 'observer' was written to, but never read" warning - var shouldStopObservation = false - var observation = ValueObservation(makeReducer: { - AnyValueReducer( - fetch: { _ in - if shouldStopObservation { - observer = nil /* deallocation */ - } - shouldStopObservation = true - }, - value: { _ in () }) - }) - observation.scheduling = .unsafe - observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - notificationExpectation.fulfill() - }) - } - - try dbWriter.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - waitForExpectations(timeout: 0.2, handler: nil) - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testObserverInvalidation2() throws { - // Test that observation stops when observer is deallocated - func test(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let notificationExpectation = expectation(description: "notification") - notificationExpectation.isInverted = true - notificationExpectation.expectedFulfillmentCount = 2 - - do { - var observer: TransactionObserver? = nil - _ = observer // Avoid "Variable 'observer' was written to, but never read" warning - var shouldStopObservation = false - var observation = ValueObservation(makeReducer: { - AnyValueReducer( - fetch: { _ in }, - value: { _ in - if shouldStopObservation { - observer = nil /* deallocation right before notification */ - } - shouldStopObservation = true - return () - }) - }) - observation.scheduling = .unsafe - observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - notificationExpectation.fulfill() - }) - } - - try dbWriter.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - waitForExpectations(timeout: 0.2, handler: nil) - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } -} diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 93b6897f9..bc7f72099 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -123,7 +123,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { onChange: { (int: Int, string: String) in }) // <- destructure } - func testVaryingRegionTrackingMainQueueScheduling() throws { + func testVaryingRegionTrackingImmediateScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: """ @@ -146,6 +146,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { let observer = observation.start( in: dbQueue, + scheduler: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in results.append(count) @@ -189,14 +190,14 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - var observation = ValueObservation.trackingVaryingRegion { db -> Int in + let observation = ValueObservation.trackingVaryingRegion { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - observation.scheduling = .async(onQueue: DispatchQueue.main) let observer = observation.start( in: dbQueue, + scheduler: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in results.append(count) @@ -222,55 +223,4 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(token.observer.observedRegion!.description, "b(value),source(name)") } } - - func testVaryingRegionTrackingUnsafeScheduling() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { - try $0.execute(sql: """ - CREATE TABLE source(name TEXT); - INSERT INTO source VALUES ('a'); - CREATE TABLE a(value INTEGER); - CREATE TABLE b(value INTEGER); - """) - } - - var results: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - var observation = ValueObservation.trackingVaryingRegion { db -> Int in - let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! - } - observation.scheduling = .unsafe - - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - results.append(count) - notificationExpectation.fulfill() - }) - - let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion!.description, "a(value),source(name)") - - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 - try db.execute(sql: "INSERT INTO b VALUES (1)") // - - try db.execute(sql: "INSERT INTO b VALUES (1)") // - - try db.execute(sql: "UPDATE source SET name = 'b'") // 2 - try db.execute(sql: "INSERT INTO a VALUES (1)") // - - try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) - - let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion!.description, "b(value),source(name)") - } - } } diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift deleted file mode 100644 index 5d0809c25..000000000 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ /dev/null @@ -1,431 +0,0 @@ -import XCTest -#if GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - #if SWIFT_PACKAGE - import CSQLite - #else - import SQLite3 - #endif - import GRDB -#endif - -class ValueObservationSchedulingTests: GRDBTestCase { - func testMainQueueObservationStartedFromMainQueue() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - let observation = ValueObservation.tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - }) - // .mainQueue scheduling: initial value MUST be synchronously - // dispatched when observation is started from the main queue - XCTAssertEqual(counts, [0]) - - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testMainQueueObservationStartedFromAnotherQueue() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.expectedFulfillmentCount = 4 - notificationExpectation.isInverted = true - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - let observation = ValueObservation.tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } - var observer: TransactionObserver? - DispatchQueue.global(qos: .default).async { - observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - }) - try! dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - } - - withExtendedLifetime(observer) { - waitForExpectations(timeout: 0.5, handler: nil) - assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testMainQueueError() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var nextError: Error? = nil // If not null, observation throws an error - let observation = ValueObservation.tracking { db in - _ = try Int.fetchOne(db, sql: "SELECT * FROM t") - if let error = nextError { - nextError = nil - throw error - } - } - - let observer = observation.start( - in: dbWriter, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - struct TestError: Error { } - nextError = TestError() - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testCustomQueue() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } - observation.scheduling = .async(onQueue: queue) - - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 0.5, handler: nil) - assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testCustomQueueImmediateError() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - struct TestError: Error { } - var observation = ValueObservation.tracking { _ in throw TestError() } - observation.scheduling = .async(onQueue: queue) - - let observer = observation.start( - in: dbWriter, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in XCTFail("Unexpected value") }) - withExtendedLifetime(observer) { - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testCustomQueueDelayedError() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - struct TestError: Error { } - var shouldThrow = false - var observation = ValueObservation.tracking { db in - _ = try Int.fetchOne(db, sql: "SELECT * FROM t") - if shouldThrow { - throw TestError() - } - shouldThrow = true - } - observation.scheduling = .async(onQueue: queue) - - let observer = observation.start( - in: dbWriter, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in }) - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testUnsafeStartFromMainQueue() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } - observation.scheduling = .unsafe - - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - if counts.isEmpty { - // require main queue on first element - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - } - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testUnsafeStartFromCustomQueue() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } - observation.scheduling = .unsafe - var observer: TransactionObserver? - queue.async { - observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - if counts.isEmpty { - // require custom queue on first notification - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - } - counts.append(count) - notificationExpectation.fulfill() - }) - try! dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - } - - withExtendedLifetime(observer) { - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testUnsafeImmediateError() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - struct TestError: Error { } - var observation = ValueObservation.tracking { _ in throw TestError() } - observation.scheduling = .unsafe - - let observer = observation.start( - in: dbWriter, - onError: { error in - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in XCTFail("Unexpected value") }) - withExtendedLifetime(observer) { - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testUnsafeDelayedError() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - struct TestError: Error { } - var shouldThrow = false - var observation = ValueObservation.tracking { db in - _ = try Int.fetchOne(db, sql: "SELECT * FROM t") - if shouldThrow { - throw TestError() - } - shouldThrow = true - } - observation.scheduling = .unsafe - - let observer = observation.start( - in: dbWriter, - onError: { error in - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in }) - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } -} diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift new file mode 100644 index 000000000..7c9f0dc59 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -0,0 +1,244 @@ +import XCTest +import Dispatch +#if GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + @testable import GRDB +#endif + +class ValueObservationTests: GRDBTestCase { + func testImmediateError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // Create an observation + struct TestError: Error { } + let observation = ValueObservation.tracking { _ in throw TestError() } + + // Start observation + var error: TestError? + _ = observation.start( + in: dbWriter, + scheduler: .immediate, + onError: { error = $0 as? TestError }, + onChange: { _ in }) + XCTAssertNotNil(error) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testErrorCompletesTheObservation() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + notificationExpectation.isInverted = true + + struct TestError: Error { } + var nextError: Error? = nil // If not null, observation throws an error + let observation = ValueObservation.tracking { + _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") + if let error = nextError { + throw error + } + } + + // Start observation + var errorCaught = false + let observer = observation.start( + in: dbWriter, + onError: { _ in + errorCaught = true + notificationExpectation.fulfill() + }, + onChange: { + XCTAssertFalse(errorCaught) + nextError = TestError() + notificationExpectation.fulfill() + // Trigger another change + try! dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + }) + + withExtendedLifetime(observer) { + waitForExpectations(timeout: 0.3, handler: nil) + XCTAssertTrue(errorCaught) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testViewOptimization() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT); + CREATE VIEW v AS SELECT * FROM t + """) + } + + // Test that view v is included in the request region + let request = SQLRequest(sql: "SELECT name FROM v ORDER BY id") + try dbQueue.inDatabase { db in + let region = try request.databaseRegion(db) + XCTAssertEqual(region.description, "t(id,name),v(id,name)") + } + + // Test that view v is not included in the observed region. + // This optimization helps observation of views that feed from a + // single table. + let observation = ValueObservation.tracking(request.fetchAll) + let observer = observation.start( + in: dbQueue, + scheduler: .immediate, // So that we can test the observedRegion + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in }) + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion!.description, "t(id,name)") // view is NOT tracked + } + + // MARK: - Cancellation + + func testExtentObserverLifetime() throws { + // We need something to change + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var changesCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // Create an observation + let observation = ValueObservation.tracking { + try Int.fetchOne($0, sql: "SELECT * FROM t") + } + + // Start observation and deallocate observer after second change + var observer: TransactionObserver? + observer = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + changesCount += 1 + if changesCount == 2 { + observer = nil + } + notificationExpectation.fulfill() + }) + + // notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + + // not notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + + // Avoid "Variable 'observer' was written to, but never read" warning + _ = observer + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(changesCount, 2) + } + + func testObserverInvalidation1() throws { + // Test that observation stops when observer is deallocated + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.isInverted = true + notificationExpectation.expectedFulfillmentCount = 2 + + do { + var observer: TransactionObserver? = nil + _ = observer // Avoid "Variable 'observer' was written to, but never read" warning + var shouldStopObservation = false + let observation = ValueObservation(makeReducer: { + AnyValueReducer( + fetch: { _ in + if shouldStopObservation { + observer = nil /* deallocation */ + } + shouldStopObservation = true + }, + value: { _ in () }) + }) + observer = observation.start( + in: dbWriter, + scheduler: .immediate, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + notificationExpectation.fulfill() + }) + } + + try dbWriter.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + waitForExpectations(timeout: 0.2, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testObserverInvalidation2() throws { + // Test that observation stops when observer is deallocated + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.isInverted = true + notificationExpectation.expectedFulfillmentCount = 2 + + do { + var observer: TransactionObserver? = nil + _ = observer // Avoid "Variable 'observer' was written to, but never read" warning + var shouldStopObservation = false + let observation = ValueObservation(makeReducer: { + AnyValueReducer( + fetch: { _ in }, + value: { _ in + if shouldStopObservation { + observer = nil /* deallocation right before notification */ + } + shouldStopObservation = true + return () + }) + }) + observer = observation.start( + in: dbWriter, + scheduler: .immediate, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + notificationExpectation.fulfill() + }) + } + + try dbWriter.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + waitForExpectations(timeout: 0.2, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } +}