diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index fb4c0af20..afb8fb877 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -63,18 +63,6 @@ 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; - 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; - 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; - 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; - 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; - 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; - 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; - 5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; - 5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; - 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; - 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; - 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; - 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; 5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; }; 5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; }; 5615B261222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; @@ -842,7 +830,6 @@ AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; }; AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; }; - AAA4DC88230F1E0600C74B15 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; }; @@ -897,7 +884,6 @@ AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; }; AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; - AAA4DCBF230F1E0600C74B15 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; AAA4DCC1230F1E0600C74B15 /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; }; AAA4DCC2230F1E0600C74B15 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; AAA4DCC3230F1E0600C74B15 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -922,14 +908,12 @@ AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; - AAA4DCDA230F1E0600C74B15 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; }; AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; - AAA4DCE1230F1E0600C74B15 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; }; AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; }; @@ -1212,10 +1196,6 @@ 5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; 5613ED3E21A95A8B00DC7A68 /* Combine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Combine.swift; sourceTree = ""; }; 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; - 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; - 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; - 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; - 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = ""; }; 5615B269222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughRowScopeTests.swift; sourceTree = ""; }; @@ -1691,11 +1671,7 @@ isa = PBXGroup; children = ( 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, - 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */, - 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, - 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */, - 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */, 564CE43021AA901800652B19 /* ValueObserver.swift */, 56AACAA022ACEC9700A40F2A /* ValueReducer */, ); @@ -2760,7 +2736,6 @@ 5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, 56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, - 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, 564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, @@ -2789,7 +2764,6 @@ 5613ED4121A95A8B00DC7A68 /* Combine.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, - 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, @@ -2800,8 +2774,6 @@ 567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, - 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, - 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E9FAD9221053DD00C703A8 /* SQLLiteral.swift in Sources */, @@ -2911,7 +2883,6 @@ 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, - 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */, 56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */, @@ -2967,7 +2938,6 @@ 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, - 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 563EF44B2161F179007DAACD /* Inflections.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -2993,14 +2963,12 @@ 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, - 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, - 5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -3461,7 +3429,6 @@ AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */, AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */, AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */, - AAA4DC88230F1E0600C74B15 /* ValueObservation+Row.swift in Sources */, AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */, AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */, AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */, @@ -3517,7 +3484,6 @@ AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */, AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */, AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */, - AAA4DCBF230F1E0600C74B15 /* ValueObservation+FetchableRecord.swift in Sources */, AAA4DCC1230F1E0600C74B15 /* Inflections.swift in Sources */, AAA4DCC2230F1E0600C74B15 /* FetchableRecord.swift in Sources */, AAA4DCC3230F1E0600C74B15 /* DatabaseSchemaCache.swift in Sources */, @@ -3543,14 +3509,12 @@ AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */, AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */, AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */, - AAA4DCDA230F1E0600C74B15 /* ValueObservation+Count.swift in Sources */, AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */, AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */, AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */, AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */, AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */, AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */, - AAA4DCE1230F1E0600C74B15 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */, AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */, AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -3787,7 +3751,6 @@ files = ( 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */, - 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */, @@ -3807,7 +3770,6 @@ 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, - 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, @@ -3855,10 +3817,8 @@ 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, - 5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, - 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index d87db3bf7..bf8fb3ec6 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -634,4 +634,19 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { try Optional.fetchAll(db, self) } + + /// The first fetched value. + /// + /// The result is nil if the request returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request: ... // Some FetchRequest that fetches String? + /// let string = try request.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { + try RowDecoder.Wrapped.fetchOne(db, self) + } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 452ed0b27..3dc81ffb9 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -642,4 +642,19 @@ extension FetchRequest public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { try Optional.fetchAll(db, self) } + + /// The first fetched value. + /// + /// The result is nil if the request returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request: ... // Some FetchRequest that fetches String? + /// let string = try request.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { + try RowDecoder.Wrapped.fetchOne(db, self) + } } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index d084dcd85..7e052695b 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -87,6 +87,50 @@ extension FetchRequest { @available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.") func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } + + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchCount) instead") + public func observationForCount() -> ValueObservation> + { preconditionFailure() } +} + +extension FetchRequest where RowDecoder: DatabaseValueConvertible { + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") + public func observationForAll() -> ValueObservation> + { preconditionFailure() } + + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") + public func observationForFirst() -> ValueObservation> + { preconditionFailure() } +} + +extension FetchRequest where RowDecoder: FetchableRecord { + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") + public func observationForAll() -> ValueObservation> + { preconditionFailure() } + + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") + public func observationForFirst() -> ValueObservation> + { preconditionFailure() } +} + +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") + public func observationForAll() -> ValueObservation> + { preconditionFailure() } + + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") + public func observationForFirst() -> ValueObservation> + { preconditionFailure() } +} + +extension FetchRequest where RowDecoder == Row { + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead") + public func observationForAll() -> ValueObservation> + { preconditionFailure() } + + @available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead") + public func observationForFirst() -> ValueObservation> + { preconditionFailure() } } extension SQLExpression { @@ -142,6 +186,22 @@ extension Statement { { preconditionFailure() } } +extension TableRecord { + @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchCount) instead") + public static func observationForCount() -> ValueObservation> + { preconditionFailure() } +} + +extension TableRecord where Self: FetchableRecord { + @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchAll) instead") + public static func observationForAll() -> ValueObservation> + { preconditionFailure() } + + @available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchOne) instead") + public static func observationForFirst() -> ValueObservation> + { preconditionFailure() } +} + extension ValueObservation { @available(*, unavailable, message: "Custom reducers are no longer supported") public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: @escaping (Database) throws -> Reducer) -> ValueObservation @@ -152,7 +212,7 @@ extension ValueObservation { { preconditionFailure() } @available(*, unavailable, message: "compactMap is no longer available") - public func compactMap(_ transform: @escaping (Reducer.Value) -> T?) -> ValueObservation> + public func compactMap(_ transform: @escaping (Reducer.Value) -> T?) -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "Use start(in:onError:onChange:) instead.") @@ -163,51 +223,51 @@ extension ValueObservation { } extension ValueObservation where Reducer == ValueReducers.Auto { - @available(*, unavailable, message: "Use request.observationForCount() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingCount(_ request: Request) - -> ValueObservation>> + -> ValueObservation> { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForAll() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: DatabaseValueConvertible { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForFirst() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingOne(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: DatabaseValueConvertible { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForAll() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: _OptionalProtocol, Request.RowDecoder.Wrapped: DatabaseValueConvertible { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForAll() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: FetchableRecord { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForFirst() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingOne(_ request: Request) -> - ValueObservation> + ValueObservation> where Request.RowDecoder: FetchableRecord { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForAll() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingAll(_ request: Request) - -> ValueObservation + -> ValueObservation> where Request.RowDecoder == Row { preconditionFailure() } - @available(*, unavailable, message: "Use request.observationForFirst() instead") + @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func trackingOne(_ request: Request) - -> ValueObservation + -> ValueObservation> where Request.RowDecoder == Row { preconditionFailure() } @@ -215,39 +275,39 @@ extension ValueObservation where Reducer == ValueReducers.Auto { public static func tracking( _ regions: DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead") public static func tracking( _ regions: [DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } @available(*, unavailable, renamed: "tracking(_:)") public static func tracking( value: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { preconditionFailure() } } extension ValueObservation where Reducer.Value: Equatable { @available(*, unavailable, renamed: "removeDuplicates") - public func distinctUntilChanged() -> ValueObservation> + public func distinctUntilChanged() -> ValueObservation> { preconditionFailure() } } extension ValueReducers { - @available(*, unavailable, message: "ValueReducers.CompactMap is no longer available") - public struct CompactMap: _ValueReducer { + @available(*, unavailable) + public enum Unavailable: _ValueReducer { public var isObservedRegionDeterministic: Bool { preconditionFailure() } - public func fetch(_ db: Database) throws -> Base.Fetched + public func fetch(_ db: Database) throws -> Never { preconditionFailure() } - public mutating func value(_ fetched: Base.Fetched) -> Value? + public mutating func value(_ fetched: Never) -> T? { preconditionFailure() } } } diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift deleted file mode 100644 index 7814ff607..000000000 --- a/GRDB/ValueObservation/ValueObservation+Count.swift +++ /dev/null @@ -1,70 +0,0 @@ -extension FetchRequest { - - // MARK: - Observation - - /// Creates a ValueObservation which observes *request*, and notifies its - /// count whenever it is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = request.observationForCount() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { count: Int in - /// print("Number of players has changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForCount() -> - ValueObservation>> - { - ValueObservation.tracking(fetchCount).removeDuplicates() - } -} - -extension TableRecord { - - // MARK: - Observation - - /// Creates a ValueObservation which observes the record table, and notifies - /// its count whenever it is modified by a database transaction. - /// - /// For example: - /// - /// let observation = Player.observationForCount() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { count: Int in - /// print("Number of players has changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public static func observationForCount() -> - ValueObservation>> - { - return all().observationForCount() - } -} diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift deleted file mode 100644 index 5aede8000..000000000 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ /dev/null @@ -1,240 +0,0 @@ -extension FetchRequest where RowDecoder: DatabaseValueConvertible { - - // MARK: - Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: String.self) - /// let observation = request.observationForAll() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { names: [String] in - /// print("Player names have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForAll() -> ValueObservation> { - ValueObservation(makeReducer: { ValueReducers.AllValues { try DatabaseValue.fetchAll($0, self) } }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh value whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.select(max(Column("score")), as: Int.self) - /// let observation = request.observationForFirst() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { maxScore: Int? in - /// print("Maximum score has changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public func observationForFirst() -> ValueObservation> { - ValueObservation(makeReducer: { ValueReducers.OneValue { try DatabaseValue.fetchOne($0, self) } }) - } -} - -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { - - // MARK: - Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: Optional.self) - /// let observation = request.observationForAll() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { names: [String?] in - /// print("Player names have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForAll() -> ValueObservation> { - ValueObservation(makeReducer: { ValueReducers.AllOptionalValues { try DatabaseValue.fetchAll($0, self) } }) - } - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: Optional.self) - /// let observation = request.observationForAll() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { names: [String?] in - /// print("Player names have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForFirst() -> ValueObservation> { - ValueObservation(makeReducer: { ValueReducers.OneValue { try DatabaseValue.fetchOne($0, self) } }) - } -} - -extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs arrays of values, filtering out consecutive - /// identical database values. - /// - /// :nodoc: - public struct AllValues: _ValueReducer - where RowDecoder: DatabaseValueConvertible - { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> [DatabaseValue] { - try _fetch(db) - } - - public mutating func value(_ dbValues: [DatabaseValue]) -> [RowDecoder]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - RowDecoder.decode(from: $0, conversionContext: nil) - } - } - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs optional values, filtering out consecutive - /// identical database values. - /// - /// :nodoc: - public struct OneValue: _ValueReducer - where RowDecoder: DatabaseValueConvertible - { - private let _fetch: (Database) throws -> DatabaseValue? - private var previousDbValue: DatabaseValue?? - private var previousValueWasNil = false - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> DatabaseValue?) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> DatabaseValue? { - try _fetch(db) - } - - public mutating func value(_ dbValue: DatabaseValue?) -> RowDecoder?? { - if let previousDbValue = previousDbValue, previousDbValue == dbValue { - // Don't notify consecutive identical dbValue - return nil - } - self.previousDbValue = dbValue - if let dbValue = dbValue, - let value = RowDecoder.decodeIfPresent(from: dbValue, conversionContext: nil) - { - previousValueWasNil = false - return .some(value) - } else if previousValueWasNil { - // Don't notify consecutive nil values - return nil - } else { - previousValueWasNil = true - return .some(nil) - } - } - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs arrays of optional values, filtering out consecutive - /// identical database values. - /// - /// :nodoc: - public struct AllOptionalValues: _ValueReducer - where RowDecoder: DatabaseValueConvertible - { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> [DatabaseValue] { - try _fetch(db) - } - - public mutating func value(_ dbValues: [DatabaseValue]) -> [RowDecoder?]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - RowDecoder.decodeIfPresent(from: $0, conversionContext: nil) - } - } - } -} diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift deleted file mode 100644 index 4da8ccbbd..000000000 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ /dev/null @@ -1,191 +0,0 @@ -extension FetchRequest where RowDecoder: FetchableRecord { - - // MARK: - Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh records whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = request.observationForAll() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { players: [Player] in - /// print("Players have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForAll() -> ValueObservation> { - ValueObservation(makeReducer: { ValueReducers.AllRecords { try Row.fetchAll($0, self) } }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh record whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.filter(key: 1) - /// let observation = request.observationForFirst() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { player: Player? in - /// print("Player has changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForFirst() -> ValueObservation> { - ValueObservation(makeReducer: { ValueReducers.OneRecord { try Row.fetchOne($0, self) } }) - } -} - -extension TableRecord where Self: FetchableRecord { - - // MARK: - Observation - - /// Creates a ValueObservation which observes the record table, and notifies - /// fresh records whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let observation = Player.observationForAll() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { players: [Player] in - /// print("Players have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public static func observationForAll() -> ValueObservation> { - all().observationForAll() - } - - /// Creates a ValueObservation which observes the table record, and notifies - /// a fresh record whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let observation = Player.observationForFirst() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { player: Player? in - /// print("Player has changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public static func observationForFirst() -> ValueObservation> { - // TODO: check that limit(1) has no impact on requests like filter(key:) - return limit(1).observationForFirst() - } -} - -extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs arrays of records, filtering out consecutive - /// identical database rows. - /// - /// :nodoc: - public struct AllRecords: _ValueReducer - where RowDecoder: FetchableRecord - { - private let _fetch: (Database) throws -> [Row] - private var previousRows: [Row]? - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> [Row]) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> [Row] { - try _fetch(db) - } - - public mutating func value(_ rows: [Row]) -> [RowDecoder]? { - if let previousRows = previousRows, previousRows == rows { - // Don't notify consecutive identical row arrays - return nil - } - self.previousRows = rows - return rows.map(RowDecoder.init(row:)) - } - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs optional records, filtering out consecutive - /// identical database rows. - /// - /// :nodoc: - public struct OneRecord: _ValueReducer - where RowDecoder: FetchableRecord - { - private let _fetch: (Database) throws -> Row? - private var previousRow: Row?? - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> Row?) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> Row? { - try _fetch(db) - } - - public mutating func value(_ row: Row?) -> RowDecoder?? { - if let previousRow = previousRow, previousRow == row { - // Don't notify consecutive identical rows - return nil - } - self.previousRow = row - return .some(row.map(RowDecoder.init(row:))) - } - } -} diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift deleted file mode 100644 index ff4336166..000000000 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ /dev/null @@ -1,122 +0,0 @@ -extension FetchRequest where RowDecoder == Row { - - // MARK: - Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh rows whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest(sql: "SELECT * FROM player") - /// let observation = request.observationForAll() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { rows: [Row] in - /// print("Players have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForAll() -> ValueObservation { - ValueObservation(makeReducer: { ValueReducers.AllRows(fetch: self.fetchAll) }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh row whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest(sql: "SELECT * FROM player WHERE id = ?", arguments: [1]) - /// let observation = request.observationForFirst() - /// - /// let observer = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { row: Row? in - /// print("Players have changed") - /// }) - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - returns: a ValueObservation. - public func observationForFirst() -> ValueObservation { - ValueObservation(makeReducer: { ValueReducers.OneRow(fetch: self.fetchOne) }) - } -} - -extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs arrays of database rows, filtering out - /// consecutive identical arrays. - /// - /// :nodoc: - public struct AllRows: _ValueReducer { - private let _fetch: (Database) throws -> [Row] - private var previousRows: [Row]? - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> [Row]) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> [Row] { - try _fetch(db) - } - - public mutating func value(_ rows: [Row]) -> [Row]? { - if let previousRows = previousRows, previousRows == rows { - // Don't notify consecutive identical row arrays - return nil - } - self.previousRows = rows - return rows - } - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// A reducer which outputs optional records, filtering out consecutive - /// identical database rows. - /// - /// :nodoc: - public struct OneRow: _ValueReducer { - private let _fetch: (Database) throws -> Row? - private var previousRow: Row?? - public var isObservedRegionDeterministic: Bool { true } - - init(fetch: @escaping (Database) throws -> Row?) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> Row? { - try _fetch(db) - } - - public mutating func value(_ row: Row?) -> Row?? { - if let previousRow = previousRow, previousRow == row { - // Don't notify consecutive identical rows - return nil - } - self.previousRow = row - return row - } - } -} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 29e5c3b48..13fad7f59 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -11,7 +11,7 @@ public enum ValueObservationScheduling { /// notified right upon subscription, synchronously: /// /// // On main queue - /// let observation = Player.observationForAll() + /// let observation = ValueObservation.tracking(Player.fetchAll) /// let observer = try observation.start( /// in: dbQueue, /// onError: { error in ... }, @@ -25,7 +25,7 @@ public enum ValueObservationScheduling { /// /// // Not on the main queue: "fresh players" is eventually printed /// // on the main queue. - /// let observation = Player.observationForAll() + /// let observation = ValueObservation.tracking(Player.fetchAll) /// let observer = try observation.start( /// in: dbQueue, /// onError: { error in ... }, @@ -51,7 +51,7 @@ public enum ValueObservationScheduling { /// the dispatch queue which starts the observation. /// /// // On any queue - /// var observation = Player.observationForAll() + /// var observation = ValueObservation.tracking(Player.fetchAll) /// observation.scheduling = .unsafe /// let observer = try observation.start( /// in: dbQueue, @@ -73,7 +73,7 @@ public enum ValueObservationScheduling { /// /// For example: /// -/// let observation = Player.observationForAll() +/// let observation = ValueObservation.tracking(Player.fetchAll) /// let observer = try observation.start( /// in: dbQueue, /// onError: { error in ... }, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 357493f16..3c20bc305 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -20,12 +20,6 @@ 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; - 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */; }; - 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */; }; - 5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; - 5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; - 5613ED6F21A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; - 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; 5613EDA321A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; }; 5613EDA421A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; }; 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; }; @@ -423,8 +417,6 @@ 56BF22892417821F003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF22862417821F003D86EB /* UtilsTests.swift */; }; 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538A22ACEECD0029D27D /* Fetch.swift */; }; 56C0539422ACEECD0029D27D /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538A22ACEECD0029D27D /* Fetch.swift */; }; - 56C0539522ACEECD0029D27D /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538B22ACEECD0029D27D /* ValueObservation+Row.swift */; }; - 56C0539622ACEECD0029D27D /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538B22ACEECD0029D27D /* ValueObservation+Row.swift */; }; 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; }; 56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; }; 56C0539922ACEECD0029D27D /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538D22ACEECD0029D27D /* Combine.swift */; }; @@ -745,9 +737,6 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; - 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; - 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; - 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; 5614089E221596A100DAD589 /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = ""; }; 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = ""; }; @@ -1012,7 +1001,6 @@ 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = ""; }; 56BF22862417821F003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = ""; }; 56C0538A22ACEECD0029D27D /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = ""; }; - 56C0538B22ACEECD0029D27D /* ValueObservation+Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; 56C0538C22ACEECD0029D27D /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; 56C0538D22ACEECD0029D27D /* Combine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Combine.swift; sourceTree = ""; }; 56C0538E22ACEECD0029D27D /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; @@ -1198,11 +1186,7 @@ isa = PBXGroup; children = ( 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, - 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, - 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, - 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */, - 56C0538B22ACEECD0029D27D /* ValueObservation+Row.swift */, 564CE43B21AA955B00652B19 /* ValueObserver.swift */, 56C0538822ACEECD0029D27D /* ValueReducer */, ); @@ -2182,7 +2166,6 @@ 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, - 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5656A8922295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2234,7 +2217,6 @@ F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, - 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, @@ -2272,9 +2254,7 @@ 5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, 5656A8902295BD56001FF3FF /* Column.swift in Sources */, 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, - 5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5656A8622295BD56001FF3FF /* TableRecord+Association.swift in Sources */, - 56C0539622ACEECD0029D27D /* ValueObservation+Row.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, 56E9FAD62210538400C703A8 /* SQLLiteral.swift in Sources */, 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */, @@ -2523,7 +2503,6 @@ 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, - 5613ED6F21A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5656A8912295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2575,7 +2554,6 @@ F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, - 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, @@ -2613,9 +2591,7 @@ 5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, 5656A88F2295BD56001FF3FF /* Column.swift in Sources */, 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, - 5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */, - 56C0539522ACEECD0029D27D /* ValueObservation+Row.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, 56E9FAD52210538400C703A8 /* SQLLiteral.swift in Sources */, 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift index 065dd9782..75e845bad 100644 --- a/Tests/GRDBTests/ValueObservationCombineTests.swift +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -22,8 +22,8 @@ class ValueObservationCombineTests: GRDBTestCase { struct T1: TableRecord { } struct T2: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2) let recorder = observation.record(in: dbQueue) @@ -74,9 +74,9 @@ class ValueObservationCombineTests: GRDBTestCase { struct T1: TableRecord { } struct T2: TableRecord { } struct T3: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() - let observation3 = T3.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() + let observation3 = ValueObservation.tracking(T3.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2, observation3) let recorder = observation.record(in: dbQueue) @@ -140,10 +140,10 @@ class ValueObservationCombineTests: GRDBTestCase { struct T2: TableRecord { } struct T3: TableRecord { } struct T4: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() - let observation3 = T3.observationForCount() - let observation4 = T4.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() + let observation3 = ValueObservation.tracking(T3.fetchCount).removeDuplicates() + let observation4 = ValueObservation.tracking(T4.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4) let recorder = observation.record(in: dbQueue) @@ -220,11 +220,11 @@ class ValueObservationCombineTests: GRDBTestCase { struct T3: TableRecord { } struct T4: TableRecord { } struct T5: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() - let observation3 = T3.observationForCount() - let observation4 = T4.observationForCount() - let observation5 = T5.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() + let observation3 = ValueObservation.tracking(T3.fetchCount).removeDuplicates() + let observation4 = ValueObservation.tracking(T4.fetchCount).removeDuplicates() + let observation5 = ValueObservation.tracking(T5.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) let recorder = observation.record(in: dbQueue) @@ -314,12 +314,12 @@ class ValueObservationCombineTests: GRDBTestCase { struct T4: TableRecord { } struct T5: TableRecord { } struct T6: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() - let observation3 = T3.observationForCount() - let observation4 = T4.observationForCount() - let observation5 = T5.observationForCount() - let observation6 = T6.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() + let observation3 = ValueObservation.tracking(T3.fetchCount).removeDuplicates() + let observation4 = ValueObservation.tracking(T4.fetchCount).removeDuplicates() + let observation5 = ValueObservation.tracking(T5.fetchCount).removeDuplicates() + let observation6 = ValueObservation.tracking(T6.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6) let recorder = observation.record(in: dbQueue) @@ -422,13 +422,13 @@ class ValueObservationCombineTests: GRDBTestCase { struct T5: TableRecord { } struct T6: TableRecord { } struct T7: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() - let observation3 = T3.observationForCount() - let observation4 = T4.observationForCount() - let observation5 = T5.observationForCount() - let observation6 = T6.observationForCount() - let observation7 = T7.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() + let observation3 = ValueObservation.tracking(T3.fetchCount).removeDuplicates() + let observation4 = ValueObservation.tracking(T4.fetchCount).removeDuplicates() + let observation5 = ValueObservation.tracking(T5.fetchCount).removeDuplicates() + let observation6 = ValueObservation.tracking(T6.fetchCount).removeDuplicates() + let observation7 = ValueObservation.tracking(T7.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7) let recorder = observation.record(in: dbQueue) @@ -544,14 +544,14 @@ class ValueObservationCombineTests: GRDBTestCase { struct T6: TableRecord { } struct T7: TableRecord { } struct T8: TableRecord { } - let observation1 = T1.observationForCount() - let observation2 = T2.observationForCount() - let observation3 = T3.observationForCount() - let observation4 = T4.observationForCount() - let observation5 = T5.observationForCount() - let observation6 = T6.observationForCount() - let observation7 = T7.observationForCount() - let observation8 = T8.observationForCount() + let observation1 = ValueObservation.tracking(T1.fetchCount).removeDuplicates() + let observation2 = ValueObservation.tracking(T2.fetchCount).removeDuplicates() + let observation3 = ValueObservation.tracking(T3.fetchCount).removeDuplicates() + let observation4 = ValueObservation.tracking(T4.fetchCount).removeDuplicates() + let observation5 = ValueObservation.tracking(T5.fetchCount).removeDuplicates() + let observation6 = ValueObservation.tracking(T6.fetchCount).removeDuplicates() + let observation7 = ValueObservation.tracking(T7.fetchCount).removeDuplicates() + let observation8 = ValueObservation.tracking(T8.fetchCount).removeDuplicates() let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7, observation8) let recorder = observation.record(in: dbQueue) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index b492b6f47..b5d54c58f 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -13,29 +13,47 @@ import XCTest class ValueObservationCountTests: GRDBTestCase { func testCount() throws { struct T: TableRecord { } - let observations = [ - T.all().observationForCount(), - T.observationForCount()] - for observation in observations { - try assertValueObservation( - observation, - records: [0, 1, 2, 3, 2], - setup: { db in - try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") - }, - recordedUpdates: { db in + try assertValueObservation( + ValueObservation.tracking(T.fetchCount), + records: [0, 1, 1, 2, 3, 2], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "UPDATE t SET id = id") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.inTransaction { try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "UPDATE t SET id = id") try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.inTransaction { - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "DELETE FROM t WHERE id = 1") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 2") - }) - } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + return .commit + } + try db.execute(sql: "DELETE FROM t WHERE id = 2") + }) + } + + func testCountWithRemoveDuplicates() throws { + struct T: TableRecord { } + + try assertValueObservation( + ValueObservation.tracking(T.fetchCount).removeDuplicates(), + records: [0, 1, 2, 3, 2], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "UPDATE t SET id = id") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "DELETE FROM t WHERE id = 1") + return .commit + } + try db.execute(sql: "DELETE FROM t WHERE id = 2") + }) } } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index cd3c12cd1..3cf00eaed 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -12,7 +12,7 @@ import SQLite3 @testable import GRDB #endif -private struct Name: DatabaseValueConvertible, Equatable { +private struct Name: DatabaseValueConvertible, Equatable, CustomDebugStringConvertible { var rawValue: String var databaseValue: DatabaseValue { rawValue.databaseValue } @@ -23,12 +23,39 @@ private struct Name: DatabaseValueConvertible, Equatable { } return Name(rawValue: rawValue) } + + var debugDescription: String { rawValue } } class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { func testAll() throws { + let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id") + try assertValueObservation( - SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll(), + ValueObservation.tracking(request.fetchAll), + records: [ + [], + [Name(rawValue: "foo")], + [Name(rawValue: "foo")], + [Name(rawValue: "foo"), Name(rawValue: "bar")], + [Name(rawValue: "bar")]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) + + try assertValueObservation( + ValueObservation.tracking(request.fetchAll).removeDuplicates(), records: [ [], [Name(rawValue: "foo")], @@ -51,8 +78,43 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } func testOne() throws { + let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC") + try assertValueObservation( - SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst(), + ValueObservation.tracking(request.fetchOne), + records: [ + nil, + Name(rawValue: "foo"), + Name(rawValue: "foo"), + Name(rawValue: "bar"), + nil, + Name(rawValue: "baz"), + nil, + nil, + nil, + Name(rawValue: "qux")], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + 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") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'baz')") + try db.execute(sql: "UPDATE t SET name = NULL") + try db.execute(sql: "DELETE FROM t") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") + try db.execute(sql: "UPDATE t SET name = 'qux'") + }) + + try assertValueObservation( + ValueObservation.tracking(request.fetchOne).removeDuplicates(), records: [ nil, Name(rawValue: "foo"), @@ -83,8 +145,33 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } func testAllOptional() throws { + let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id") + try assertValueObservation( - SQLRequest(sql: "SELECT name FROM t ORDER BY id").observationForAll(), + ValueObservation.tracking(request.fetchAll), + records: [ + [], + [Name(rawValue: "foo")], + [Name(rawValue: "foo")], + [Name(rawValue: "foo"), nil], + [nil]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, NULL)") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) + + try assertValueObservation( + ValueObservation.tracking(request.fetchAll).removeDuplicates(), records: [ [], [Name(rawValue: "foo")], @@ -104,11 +191,46 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } try db.execute(sql: "DELETE FROM t WHERE id = 1") }) - } +} func testOneOptional() throws { + let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC") + try assertValueObservation( - SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst(), + ValueObservation.tracking(request.fetchOne), + records: [ + nil, + Name(rawValue: "foo"), + Name(rawValue: "foo"), + Name(rawValue: "bar"), + nil, + Name(rawValue: "baz"), + nil, + nil, + nil, + Name(rawValue: "qux")], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + 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") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'baz')") + try db.execute(sql: "UPDATE t SET name = NULL") + try db.execute(sql: "DELETE FROM t") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") + try db.execute(sql: "UPDATE t SET name = 'qux'") + }) + + try assertValueObservation( + ValueObservation.tracking(request.fetchOne).removeDuplicates(), records: [ nil, Name(rawValue: "foo"), @@ -162,7 +284,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { // Test that view v is not included in the observed region. // This optimization helps observation of views that feed from a // single table. - let observation = request.observationForAll() + let observation = ValueObservation.tracking(request.fetchAll) let observer = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, @@ -170,13 +292,12 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { results.append(names) notificationExpectation.fulfill() }) - let token = observer as! ValueObserverToken> // Non-public implementation detail + 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.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = try db.inTransaction { // +1 try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 006a2d1cc..282afdd0e 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -54,7 +54,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() .asRequest(of: Row.self) - let observation = request.observationForFirst() + let observation = ValueObservation.tracking(request.fetchOne) let recorder = observation.record(in: dbQueue) try dbQueue.inDatabase { db in @@ -78,7 +78,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() .asRequest(of: Row.self) - let observation = request.observationForAll() + let observation = ValueObservation.tracking(request.fetchAll) let recorder = observation.record(in: dbQueue) try dbQueue.inDatabase { db in @@ -109,7 +109,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .asRequest(of: ParentInfo.self) try assertValueObservation( - request.observationForFirst(), + ValueObservation.tracking(request.fetchOne), records: [ ParentInfo( parent: Parent(id: 1, name: "foo"), @@ -134,7 +134,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .asRequest(of: ParentInfo.self) try assertValueObservation( - request.observationForAll(), + ValueObservation.tracking(request.fetchAll), records: [ [ ParentInfo( diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index 7da7ffbf5..526108904 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -24,11 +24,14 @@ extension Player: TableRecord, FetchableRecord { class ValueObservationRecordTests: GRDBTestCase { func testAll() throws { + let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id") + try assertValueObservation( - SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll(), + ValueObservation.tracking(request.fetchAll), records: [ [], [Player(id: 1, name: "foo")], + [Player(id: 1, name: "foo")], [Player(id: 1, name: "foo"), Player(id: 2, name: "bar")], [Player(id: 2, name: "bar")]], setup: { db in @@ -45,11 +48,12 @@ class ValueObservationRecordTests: GRDBTestCase { } try db.execute(sql: "DELETE FROM t WHERE id = 1") }) - } - - func testTableRecordStaticAll() throws { + try assertValueObservation( - Player.observationForAll(), + ValueObservation + .tracking { try Row.fetchAll($0, request) } + .removeDuplicates() + .map { $0.map(Player.init(row:)) }, records: [ [], [Player(id: 1, name: "foo")], @@ -72,8 +76,36 @@ class ValueObservationRecordTests: GRDBTestCase { } func testOne() throws { + let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC") + try assertValueObservation( - SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(), + ValueObservation.tracking(request.fetchOne), + records: [ + nil, + Player(id: 1, name: "foo"), + Player(id: 1, name: "foo"), + Player(id: 2, name: "bar"), + nil], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t") + }) + + try assertValueObservation( + ValueObservation + .tracking { try Row.fetchOne($0, request) } + .removeDuplicates() + .map { $0.map(Player.init(row:)) }, records: [ nil, Player(id: 1, name: "foo"), diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index 508f3d36f..ee519aabf 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -12,8 +12,33 @@ import XCTest class ValueObservationRowTests: GRDBTestCase { func testAll() throws { + let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id") + try assertValueObservation( - SQLRequest(sql: "SELECT * FROM t ORDER BY id").observationForAll(), + ValueObservation.tracking(request.fetchAll), + records: [ + [], + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"], ["id":2, "name":"bar"]], + [["id":2, "name":"bar"]]], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t WHERE id = 1") + }) + + try assertValueObservation( + ValueObservation.tracking(request.fetchAll).removeDuplicates(), records: [ [], [["id":1, "name":"foo"]], @@ -36,8 +61,33 @@ class ValueObservationRowTests: GRDBTestCase { } func testOne() throws { + let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC") + try assertValueObservation( - SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(), + ValueObservation.tracking(request.fetchOne), + records: [ + nil, + ["id":1, "name":"foo"], + ["id":1, "name":"foo"], + ["id":2, "name":"bar"], + nil], + setup: { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute(sql: "DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute(sql: "DELETE FROM t") + }) + + try assertValueObservation( + ValueObservation.tracking(request.fetchOne).removeDuplicates(), records: [ nil, ["id":1, "name":"foo"], @@ -61,7 +111,7 @@ class ValueObservationRowTests: GRDBTestCase { func testFTS4Observation() throws { try assertValueObservation( - SQLRequest(sql: "SELECT * FROM ft_documents").observationForAll(), + ValueObservation.tracking(SQLRequest(sql: "SELECT * FROM ft_documents").fetchAll), records: [ [], [["content":"foo"]]], @@ -75,7 +125,7 @@ class ValueObservationRowTests: GRDBTestCase { func testSynchronizedFTS4Observation() throws { try assertValueObservation( - SQLRequest(sql: "SELECT * FROM ft_documents").observationForAll(), + ValueObservation.tracking(SQLRequest(sql: "SELECT * FROM ft_documents").fetchAll), records: [ [], [["content":"foo"]]], @@ -96,12 +146,11 @@ class ValueObservationRowTests: GRDBTestCase { func testJoinedFTS4Observation() throws { try assertValueObservation( - SQLRequest(sql: """ + ValueObservation.tracking(SQLRequest(sql: """ SELECT document.* FROM document JOIN ft_document ON ft_document.rowid = document.id WHERE ft_document MATCH 'foo' - """) - .observationForAll(), + """).fetchAll), records: [ [], [["id":1]]],