mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
Merge branch 'development'
This commit is contained in:
commit
e9b8df68ee
37 files changed
+1582
-768
No files matched your search
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.22.x` Releases - [5.22.0](#5220)
|
||||
- `5.21.x` Releases - [5.21.0](#5210)
|
||||
- `5.20.x` Releases - [5.20.0](#5200)
|
||||
- `5.19.x` Releases - [5.19.0](#5190)
|
||||
@@ -88,6 +89,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 5.22.0
|
||||
|
||||
Released March 22, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.21.0...v5.22.0)
|
||||
|
||||
- **New**: [#1186](https://github.com/groue/GRDB.swift/pull/1186) by [@benrb](https://github.com/benrb): DatabaseError provide error message as localizedFailureReason
|
||||
- **Breaking Change**: [#1183](https://github.com/groue/GRDB.swift/pull/1183) by [@groue](https://github.com/groue): Starting a ValueObservation keeps a strong reference on the database connection.
|
||||
|
||||
## 5.21.0
|
||||
|
||||
Released February 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.20.0...v5.21.0)
|
||||
|
||||
@@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -77,7 +77,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.21/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.22/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.21.0'
|
||||
s.version = '5.22.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -287,9 +287,9 @@
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; };
|
||||
@@ -539,6 +539,10 @@
|
||||
56781B0C243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
56781B0D243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
56781B0E243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533427E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533527E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533627E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
@@ -949,7 +953,7 @@
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; };
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
|
||||
AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */; };
|
||||
@@ -1385,7 +1389,7 @@
|
||||
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
@@ -1480,6 +1484,7 @@
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1815,9 +1820,10 @@
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
@@ -2583,9 +2589,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 565490B31D5A4798005622CB /* Build configuration list for PBXNativeTarget "GRDBWatchOS" */;
|
||||
buildPhases = (
|
||||
5654909D1D5A4798005622CB /* Headers */,
|
||||
5654909B1D5A4798005622CB /* Sources */,
|
||||
5654909C1D5A4798005622CB /* Frameworks */,
|
||||
5654909D1D5A4798005622CB /* Headers */,
|
||||
5654909E1D5A4798005622CB /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
@@ -2619,9 +2625,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 56E5D7DB1B4D3FEE00430942 /* Build configuration list for PBXNativeTarget "GRDBiOS" */;
|
||||
buildPhases = (
|
||||
56E5D7C71B4D3FED00430942 /* Headers */,
|
||||
56E5D7C51B4D3FED00430942 /* Sources */,
|
||||
56E5D7C61B4D3FED00430942 /* Frameworks */,
|
||||
56E5D7C71B4D3FED00430942 /* Headers */,
|
||||
56E5D7C81B4D3FED00430942 /* Resources */,
|
||||
56EB54FA22C9115E00850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2674,9 +2680,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = AAA4DCFB230F1E0600C74B15 /* Build configuration list for PBXNativeTarget "GRDBtvOS" */;
|
||||
buildPhases = (
|
||||
AAA4DCF5230F1E0600C74B15 /* Headers */,
|
||||
AAA4DC76230F1E0600C74B15 /* Sources */,
|
||||
AAA4DCF4230F1E0600C74B15 /* Frameworks */,
|
||||
AAA4DCF5230F1E0600C74B15 /* Headers */,
|
||||
AAA4DCF9230F1E0600C74B15 /* Resources */,
|
||||
AAA4DCFA230F1E0600C74B15 /* Swiftlint */,
|
||||
);
|
||||
@@ -2711,9 +2717,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = DC37740919C8CBB3004FCF85 /* Build configuration list for PBXNativeTarget "GRDBOSX" */;
|
||||
buildPhases = (
|
||||
DC3773F019C8CBB3004FCF85 /* Headers */,
|
||||
DC3773EE19C8CBB3004FCF85 /* Sources */,
|
||||
DC3773EF19C8CBB3004FCF85 /* Frameworks */,
|
||||
DC3773F019C8CBB3004FCF85 /* Headers */,
|
||||
DC3773F119C8CBB3004FCF85 /* Resources */,
|
||||
56EB54F322C8ED5100850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2943,11 +2949,12 @@
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56894FD12606589C00268F4D /* Decimal.swift in Sources */,
|
||||
5679533527E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
|
||||
@@ -3094,7 +3101,7 @@
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
@@ -3179,6 +3186,7 @@
|
||||
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5679533427E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
@@ -3699,7 +3707,7 @@
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */,
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */,
|
||||
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */,
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
@@ -3784,6 +3792,7 @@
|
||||
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */,
|
||||
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
|
||||
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5679533627E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
|
||||
@@ -4146,7 +4155,7 @@
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
|
||||
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
@@ -4154,6 +4163,7 @@
|
||||
5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
563B8F92249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
|
||||
@@ -297,6 +297,8 @@ public struct Configuration {
|
||||
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
}
|
||||
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of write accesses.
|
||||
func makeWriterDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = writeTargetQueue ?? targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
@@ -305,6 +307,8 @@ public struct Configuration {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of read accesses.
|
||||
func makeReaderDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
|
||||
@@ -1046,9 +1046,9 @@ struct SchemaInfo: Equatable {
|
||||
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try Set(SchemaObject.fetchCursor(db, sql: """
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
"""))
|
||||
""")
|
||||
}
|
||||
|
||||
/// All names for a given type
|
||||
|
||||
@@ -1001,6 +1001,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Runs the block with an isolation level equal or greater than
|
||||
/// snapshot isolation.
|
||||
///
|
||||
/// - parameter readOnly: If true, writes are forbidden.
|
||||
func isolated<T>(readOnly: Bool = false, _ block: () throws -> T) throws -> T {
|
||||
var result: T?
|
||||
try inSavepoint {
|
||||
|
||||
@@ -506,5 +506,11 @@ extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: description] }
|
||||
public var errorUserInfo: [String: Any] {
|
||||
var userInfo = [NSLocalizedDescriptionKey: description]
|
||||
if let message = message {
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = message
|
||||
}
|
||||
return userInfo
|
||||
}
|
||||
}
|
||||
+19
-230
@@ -366,54 +366,6 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeReaderDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.weakAsync { db in
|
||||
guard let db = db else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
@@ -748,11 +700,6 @@ extension DatabasePool: DatabaseReader {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
@@ -763,25 +710,26 @@ extension DatabasePool: DatabaseReader {
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
if observation.requiresWriteAccess {
|
||||
let observer = _addWriteOnly(
|
||||
|
||||
} else if observation.requiresWriteAccess {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
|
||||
} else {
|
||||
// DatabasePool can perform concurrent observation
|
||||
return _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
let observer = _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
/// A concurrent observation fetches the initial value without waiting for
|
||||
@@ -790,178 +738,19 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
writer: self,
|
||||
let observer = ValueConcurrentObserver(
|
||||
dbPool: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeReaderDispatchQueue(label: reduceQueueLabel),
|
||||
trackingMode: observation.trackingMode,
|
||||
reducer: observation.makeReducer(),
|
||||
events: observation.events,
|
||||
onChange: onChange)
|
||||
|
||||
// Starting a concurrent observation means that we'll fetch the initial
|
||||
// value right away, without waiting for an access to the writer queue,
|
||||
// and the opportunity to install a transaction observer.
|
||||
//
|
||||
// This is how DatabasePool can start an observation and promptly notify
|
||||
// an initial value, even when there is a long-running write transaction
|
||||
// in the background.
|
||||
//
|
||||
// We thus have to deal with the fact that between this initial fetch,
|
||||
// and the beginning of transaction tracking, any number of untracked
|
||||
// writes may occur.
|
||||
//
|
||||
// We must notify changes that happen during this untracked window. But
|
||||
// how do we spot them, since we're not tracking database changes yet?
|
||||
//
|
||||
// A safe solution is to always perform a second fetch. We may fetch the
|
||||
// same initial value, if no change did happen. But we don't miss
|
||||
// possible changes.
|
||||
//
|
||||
// We can avoid this second fetch when SQLite is compiled with the
|
||||
// SQLITE_ENABLE_SNAPSHOT option:
|
||||
//
|
||||
// 1. Perform the initial fetch in a DatabaseSnapshot. Its long running
|
||||
// transaction acquires a lock that will prevent checkpointing until we
|
||||
// get a writer access, so that we can reliably compare database
|
||||
// versions with `sqlite3_snapshot`:
|
||||
// https://www.sqlite.org/c3ref/snapshot.html.
|
||||
//
|
||||
// 2. Get a writer access, and compare the versions of the initial
|
||||
// snapshot, and the current state of the database: if versions are
|
||||
// identical, we can avoid the second fetch. If they are not, we perform
|
||||
// the second fetch, even if the actual changes are unrelated to the
|
||||
// tracked database region (we have no way to know).
|
||||
//
|
||||
// 3. Install the transaction observer.
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialSnapshot = try makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "ValueObservation")
|
||||
configuration
|
||||
.makeReaderDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
let initialSnapshot = try self.makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
observer.notifyChange(initialValue)
|
||||
self.add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue = try read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
addObserver(observer: observer)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncRead { [weak self] dbResult in
|
||||
guard let self = self, let dbResult = dbResult else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(dbResult.get())
|
||||
observer.notifyChange(initialValue)
|
||||
self.addObserver(observer: observer)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return observer
|
||||
return observer.start()
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func add<Reducer: ValueReducer>(
|
||||
observer: ValueObserver<Reducer>,
|
||||
from initialSnapshot: DatabaseSnapshot)
|
||||
{
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
// Transaction is needed for version snapshotting
|
||||
try db.inTransaction(.deferred) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps versions (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let fetchNeeded: Bool = try withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialVersion = initialSnapshot.version else {
|
||||
return true
|
||||
}
|
||||
return try db.wasChanged(since: initialVersion)
|
||||
}
|
||||
|
||||
if fetchNeeded {
|
||||
observer.events.databaseDidChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func addObserver<Reducer: ValueReducer>(observer: ValueObserver<Reducer>) {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
observer.events.databaseDidChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
@@ -212,32 +212,6 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
writer.weakAsync { db in
|
||||
guard let db = db else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(value)
|
||||
}
|
||||
@@ -366,11 +340,6 @@ extension DatabaseQueue {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
@@ -381,16 +350,17 @@ extension DatabaseQueue {
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
}
|
||||
@@ -178,11 +178,6 @@ public protocol DatabaseReader: AnyObject, GRDBSendable {
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Same as asyncRead, but without retaining self
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
@@ -566,6 +561,8 @@ extension DatabaseReader {
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Perform a reentrant read, in case the observation would be
|
||||
// started from a database access.
|
||||
let value = try unsafeReentrantRead { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
try observation.fetchValue(db)
|
||||
@@ -575,13 +572,11 @@ extension DatabaseReader {
|
||||
} catch {
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
|
||||
} else {
|
||||
var isCancelled = false
|
||||
_weakAsyncRead { dbResult in
|
||||
guard !isCancelled,
|
||||
let dbResult = dbResult
|
||||
else { return }
|
||||
asyncRead { dbResult in
|
||||
guard !isCancelled else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchValue(db) }
|
||||
@@ -638,11 +633,6 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
|
||||
@@ -95,11 +95,6 @@ extension DatabaseSnapshot {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
serializedDatabase.weakAsync { value($0.map { .success($0) }) }
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(value)
|
||||
}
|
||||
|
||||
@@ -134,12 +134,6 @@ 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.
|
||||
///
|
||||
@@ -299,9 +293,7 @@ extension DatabaseWriter {
|
||||
}
|
||||
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
_weakAsyncWriteWithoutTransaction {
|
||||
$0?.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
@@ -366,52 +358,25 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// A write-only observation only uses the serialized writer
|
||||
/// Starts an observation that fetches fresh database values synchronously,
|
||||
/// from the writer database connection, right after the database
|
||||
/// was modified.
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
let observer = ValueWriteOnlyObserver(
|
||||
writer: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeWriterDispatchQueue(label: reduceQueueLabel),
|
||||
readOnly: !observation.requiresWriteAccess,
|
||||
trackingMode: observation.trackingMode,
|
||||
reducer: observation.makeReducer(),
|
||||
events: observation.events,
|
||||
onChange: onChange)
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue: Reducer.Value = try unsafeReentrantWrite { db in
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
return initialValue
|
||||
}
|
||||
onChange(initialValue)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
observer.notifyChange(initialValue)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return observer
|
||||
return observer.start()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -760,11 +725,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
@@ -819,11 +779,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
base._weakAsyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
@@ -185,9 +185,11 @@ public protocol _RowAdapter {
|
||||
/// GRDB ships with four concrete types that adopt the RowAdapter protocol:
|
||||
///
|
||||
/// - `ColumnMapping`: renames row columns
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
/// - `RangeRowAdapter`: only exposes a range of columns
|
||||
/// - `EmptyRowAdapter`: hides all columns
|
||||
/// - `RangeRowAdapter`: exposes a range of columns
|
||||
/// - `RenameColumnAdapter`: transforms column names with a function
|
||||
/// - `ScopeAdapter`: defines row scopes
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
///
|
||||
/// To use a row adapter, provide it to any method that fetches:
|
||||
///
|
||||
|
||||
@@ -197,19 +197,6 @@ 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
|
||||
|
||||
@@ -271,7 +271,7 @@ public struct DatabaseMigrator {
|
||||
/// - throws: An eventual database error.
|
||||
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
|
||||
do {
|
||||
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
|
||||
return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations")
|
||||
} catch {
|
||||
// Rethrow if we can't prove grdb_migrations does not exist yet
|
||||
if (try? !db.tableExists("grdb_migrations")) ?? false {
|
||||
|
||||
@@ -117,8 +117,6 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
}
|
||||
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
// Nil is only possible for columns and scopes (optional
|
||||
// associations), not for prefetched rows.
|
||||
let row = decoder.row
|
||||
if let column = try? decodeColumn(forKey: key), row[column] != nil {
|
||||
return false
|
||||
@@ -126,6 +124,9 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
if row.scopesTree[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
if row.prefetchedRows[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -218,9 +219,15 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
}
|
||||
}
|
||||
|
||||
// Scope? (beware left joins: check if scoped row contains non-null values)
|
||||
if let scopedRow = row.scopesTree[key.stringValue], scopedRow.containsNonNullValue {
|
||||
return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key])
|
||||
// Scope?
|
||||
if let scopedRow = row.scopesTree[key.stringValue] {
|
||||
// Beware left joins: check if scoped row contains non-null
|
||||
// values before decoding
|
||||
if scopedRow.containsNonNullValue {
|
||||
return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key])
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Prefetched Rows?
|
||||
@@ -229,7 +236,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
return try T(from: decoder)
|
||||
}
|
||||
|
||||
// Key is not a column, and not a scope.
|
||||
// Unknown key
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -264,7 +271,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
return try T(from: decoder)
|
||||
}
|
||||
|
||||
// Key is not a column, and not a scope.
|
||||
// Unknown key
|
||||
//
|
||||
// Should be throw an error? Well... The use case is the following:
|
||||
//
|
||||
@@ -291,7 +298,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
//
|
||||
// Our current strategy is to assume that a missing key (such as
|
||||
// "book", which is not the name of a column, and not the name of a
|
||||
// scope) has to be decoded right from the base row.
|
||||
// scope) has to be decoded right from the base row. But this can
|
||||
// happen only once.
|
||||
if let decodedRootKey = decodedRootKey {
|
||||
let keys = [decodedRootKey.stringValue, key.stringValue].sorted()
|
||||
throw DecodingError.keyNotFound(key, DecodingError.Context(
|
||||
|
||||
@@ -172,7 +172,7 @@ func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
|
||||
}
|
||||
}
|
||||
|
||||
extension NSRecursiveLock {
|
||||
extension NSLocking {
|
||||
func synchronized<T>(
|
||||
_ message: @autoclosure () -> String = #function,
|
||||
_ block: () throws -> T)
|
||||
|
||||
@@ -17,10 +17,14 @@ public class AnyDatabaseCancellable: DatabaseCancellable {
|
||||
_cancel = cancel
|
||||
}
|
||||
|
||||
/// Initializes a cancellable object that forwards cancellation to the
|
||||
/// Creates a cancellable object that forwards cancellation to the
|
||||
/// provided cancellable.
|
||||
public convenience init(_ cancellable: DatabaseCancellable) {
|
||||
self.init(cancel: cancellable.cancel)
|
||||
var cancellable: DatabaseCancellable? = cancellable
|
||||
self.init {
|
||||
cancellable?.cancel()
|
||||
cancellable = nil // Release memory
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -0,0 +1,759 @@
|
||||
import Foundation
|
||||
|
||||
/// `ValueConcurrentObserver` observes the database for `ValueObservation`, in
|
||||
/// a `DatabasePool`.
|
||||
///
|
||||
/// It performs the following database observation cycle:
|
||||
///
|
||||
/// 1. Start observation or detect a database change
|
||||
/// 2. Fetch
|
||||
/// 3. Reduce
|
||||
/// 4. Notify
|
||||
///
|
||||
/// **Fetch** is performed concurrently (hence the name of this observer).
|
||||
///
|
||||
/// **Reduce** is the operation that turns the fetched database values into the
|
||||
/// observed values. Those are not the same. Consider, for example, the `map()`
|
||||
/// and `removeDuplicates()` operators: they perform their job during the
|
||||
/// reducing stage.
|
||||
///
|
||||
/// **Notify** is calling user callbacks, in case of database change or error.
|
||||
final class ValueConcurrentObserver<Reducer: ValueReducer> {
|
||||
// MARK: - Configuration
|
||||
//
|
||||
// Configuration is not mutable.
|
||||
|
||||
/// How to schedule observed values and errors.
|
||||
private let scheduler: ValueObservationScheduler
|
||||
|
||||
/// Configures the tracked database region.
|
||||
private let trackingMode: ValueObservationTrackingMode
|
||||
|
||||
// MARK: - Mutable State
|
||||
//
|
||||
// The observer has four distinct mutable states that evolve independently,
|
||||
// and are made thread-safe with various mechanisms:
|
||||
//
|
||||
// - A `DatabaseAccess`: ability to access the database. It is constant but
|
||||
// turns nil after the observation fails or is cancelled, in order to
|
||||
// release memory and resources when the observation completes. It is
|
||||
// guarded by `lock`, because observation can fail or be cancelled from
|
||||
// multiple threads.
|
||||
//
|
||||
// - A `NotificationCallbacks`: ability to notify observation events. It is
|
||||
// constant but turns nil when failure or cancellation is notified, in
|
||||
// order to release memory and resources when the observation completes.
|
||||
// It is guarded by `lock`, because observation can fail or be cancelled
|
||||
// from multiple threads.
|
||||
//
|
||||
// - An `ObservationState`: relationship with the `TransactionObserver`
|
||||
// protocol. It is only accessed from the serialized writer
|
||||
// dispatch queue.
|
||||
//
|
||||
// - A `Reducer`: the observation reducer, only accessed from the
|
||||
// serialized dispatch queue `reduceQueue`.
|
||||
//
|
||||
// The `reduceQueue` guarantees that fresh value notifications have the same
|
||||
// order as transactions. It is different from the serialized writer
|
||||
// dispatch queue because we do not want to lock the database as
|
||||
// computations (`map`, `removeDuplicates()`, etc.) are performed.
|
||||
//
|
||||
// Despite being protected by the same lock, `DatabaseAccess` and
|
||||
// `NotificationCallbacks` are not merged together. This is because the
|
||||
// observer does not lose `DatabaseAccess` at the same time it
|
||||
// looses `NotificationCallbacks`:
|
||||
//
|
||||
// - In case of cancellation, `NotificationCallbacks` is lost first, and
|
||||
// `DatabaseAccess` is lost asynchronously, after the observer could
|
||||
// resign as a transaction observer. See `cancel()`.
|
||||
//
|
||||
// - In case of error, `DatabaseAccess` may be lost synchronously, and
|
||||
// `NotificationCallbacks` is lost asynchronously, after the error could
|
||||
// be notified. See error catching clauses.
|
||||
|
||||
/// Ability to access the database
|
||||
private struct DatabaseAccess {
|
||||
/// The observed DatabasePool.
|
||||
let dbPool: DatabasePool
|
||||
|
||||
/// The function that fetches database values.
|
||||
let fetch: (Database) throws -> Reducer.Fetched
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
let events: ValueObservationEvents
|
||||
let onChange: (Reducer.Value) -> Void
|
||||
}
|
||||
|
||||
/// Relationship with the `TransactionObserver` protocol
|
||||
private struct ObservationState {
|
||||
var region: DatabaseRegion?
|
||||
var isModified = false
|
||||
|
||||
static var notObserving: Self { .init(region: nil, isModified: false) }
|
||||
}
|
||||
|
||||
/// Protects `databaseAccess` and `notificationCallbacks`.
|
||||
///
|
||||
/// Check out this compiler bug:
|
||||
/// - <https://github.com/groue/GRDB.swift/issues/1026>
|
||||
/// - <https://github.com/groue/GRDB.swift/pull/1025>
|
||||
private let lock = NSLock()
|
||||
|
||||
/// The dispatch queue where database values are reduced into observed
|
||||
/// values before being notified. Protects `reducer`.
|
||||
private let reduceQueue: DispatchQueue
|
||||
|
||||
/// Access to the database, protected by `lock`.
|
||||
private var databaseAccess: DatabaseAccess?
|
||||
|
||||
/// Ability to notify observation events, protected by `lock`.
|
||||
private var notificationCallbacks: NotificationCallbacks?
|
||||
|
||||
/// Support for `TransactionObserver`, protected by the serialized writer
|
||||
/// dispatch queue.
|
||||
private var observationState = ObservationState.notObserving
|
||||
|
||||
/// Protected by `reduceQueue`.
|
||||
private var reducer: Reducer
|
||||
|
||||
init(
|
||||
dbPool: DatabasePool,
|
||||
scheduler: ValueObservationScheduler,
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
reducer: Reducer,
|
||||
events: ValueObservationEvents,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
// Configuration
|
||||
self.scheduler = scheduler
|
||||
self.trackingMode = trackingMode
|
||||
|
||||
// State
|
||||
self.databaseAccess = DatabaseAccess(
|
||||
dbPool: dbPool,
|
||||
// ValueReducer semantics guarantees that reducer._fetch
|
||||
// is independent from the reducer state
|
||||
fetch: reducer._fetch)
|
||||
self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange)
|
||||
self.reducer = reducer
|
||||
self.reduceQueue = dbPool.configuration.makeReaderDispatchQueue(label: dbPool.configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation"))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Starting the Observation
|
||||
//
|
||||
// When we start an observation from a `DatabasePool`, we do not wait for an
|
||||
// access to the writer connection before fetching the initial value. That is
|
||||
// because the user of a `DatabasePool` expects to be notified with the initial
|
||||
// value as fast as possible, even if a long write transaction is running in the
|
||||
// background.
|
||||
//
|
||||
// We will thus perform the initial fetch from a reader connection, and only
|
||||
// then access the writer connection, and start database observation.
|
||||
//
|
||||
// Between this initial fetch, and the beginning of database observation, any
|
||||
// number of unobserved writes may occur. We must notify the changes that happen
|
||||
// during this unobserved window. But how do we spot them, since we were not
|
||||
// observing the database yet?
|
||||
//
|
||||
// The solution depends on the presence of the `SQLITE_ENABLE_SNAPSHOT`
|
||||
// SQLite compilation flag.
|
||||
//
|
||||
// Without `SQLITE_ENABLE_SNAPSHOT`, we have NO WAY to detect if the database
|
||||
// was changed or not between the initial fetch and the beginning of database
|
||||
// observation. We will thus always perform a secondary fetch from the initial
|
||||
// access to the writer connection. Even if no change was performed. We may end
|
||||
// up notifying the same value twice. Such stuttering is a documented glitch,
|
||||
// and the user can perform deduplication with the
|
||||
// `removeDuplicates()` operator.
|
||||
//
|
||||
// With `SQLITE_ENABLE_SNAPSHOT`, we can detect if the database was not changed
|
||||
// at all between the initial fetch and the beginning of database observation.
|
||||
// If the database was changed, we perform a secondary fetch from the initial
|
||||
// access to the writer connection. It is possible that the change was not
|
||||
// related to the observed value. Actually we have NO WAY to know. So we may end
|
||||
// up notifying the same value twice. Such stuttering is a documented glitch,
|
||||
// and the user can perform deduplication with the
|
||||
// `removeDuplicates()` operator.
|
||||
//
|
||||
// This is how we can both:
|
||||
// 1. Start the observation without waiting for a write access (the expected
|
||||
// benefit of `DatabasePool`).
|
||||
// 2. Make sure we do not miss a change (a documented guarantee)
|
||||
extension ValueConcurrentObserver {
|
||||
// Starts the observation
|
||||
func start() -> DatabaseCancellable {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let (notificationCallbacksOpt, databaseAccessOpt) = lock.synchronized {
|
||||
(self.notificationCallbacks, self.databaseAccess)
|
||||
}
|
||||
guard let notificationCallbacks = notificationCallbacksOpt, let databaseAccess = databaseAccessOpt else {
|
||||
// Likely a GRDB bug
|
||||
fatalError("can't start a cancelled or failed observation")
|
||||
}
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Start the observation in an synchronous way
|
||||
let initialValue = try syncStart(from: databaseAccess)
|
||||
|
||||
// Notify the initial value from the dispatch queue the
|
||||
// observation was started from
|
||||
notificationCallbacks.onChange(initialValue)
|
||||
} catch {
|
||||
// Notify error from the dispatch queue the observation
|
||||
// was started from.
|
||||
notificationCallbacks.events.didFail?(error)
|
||||
|
||||
// Early return!
|
||||
return AnyDatabaseCancellable { /* nothing to cancel */ }
|
||||
}
|
||||
} else {
|
||||
// Start the observation in an asynchronous way
|
||||
asyncStart(from: databaseAccess)
|
||||
}
|
||||
|
||||
// Make sure the returned cancellable cancels the observation
|
||||
// when deallocated. We can't relying on the deallocation of
|
||||
// self to trigger early cancellation, because self may be retained by
|
||||
// some closure waiting to run in some DispatchQueue.
|
||||
return AnyDatabaseCancellable(self)
|
||||
}
|
||||
|
||||
private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
writerDB.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// MARK: - Starting the Observation (with SQLITE_ENABLE_SNAPSHOT)
|
||||
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// Fetch value & tracked region in a synchronous way.
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialSnapshot.read { db in
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
let fetchedValue = try db.recordingSelection(®ion) {
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion)
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
let initialValue: Reducer.Value = reduceQueue.sync {
|
||||
guard let initialValue = reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
return initialValue
|
||||
}
|
||||
|
||||
// Start observation
|
||||
asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialRegion: initialRegion)
|
||||
|
||||
return initialValue
|
||||
}
|
||||
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from databaseAccess: DatabaseAccess) {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
do {
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
initialSnapshot.asyncRead { dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
let db = try dbResult.get()
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
initialRegion = try region.observableRegion(db)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try db.recordingSelection(®ion) {
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
initialRegion = try region.observableRegion(db)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// a database dispatch queue longer than necessary.
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
guard let initialValue = self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncStartObservation(
|
||||
from databaseAccess: DatabaseAccess,
|
||||
initialSnapshot: DatabaseSnapshot,
|
||||
initialRegion: DatabaseRegion)
|
||||
{
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
var observedRegion = initialRegion
|
||||
|
||||
// Transaction is needed for comparing version snapshots
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps versions (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let isModified: Bool = try withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialVersion = initialSnapshot.version else {
|
||||
return true
|
||||
}
|
||||
return try writerDB.wasChanged(since: initialVersion)
|
||||
}
|
||||
|
||||
if isModified {
|
||||
events.databaseDidChange?()
|
||||
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
|
||||
switch self.trackingMode {
|
||||
case .constantRegion:
|
||||
fetchedValue = try databaseAccess.fetch(writerDB)
|
||||
events.willTrackRegion?(initialRegion)
|
||||
self.startObservation(writerDB, observedRegion: initialRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try writerDB.recordingSelection(®ion) {
|
||||
try databaseAccess.fetch(writerDB)
|
||||
}
|
||||
observedRegion = try region.observableRegion(writerDB)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
self.startObservation(writerDB, observedRegion: observedRegion)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering
|
||||
// between transactions and notifications!
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
events.willTrackRegion?(initialRegion)
|
||||
self.startObservation(writerDB, observedRegion: initialRegion)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// MARK: - Starting the Observation (without SQLITE_ENABLE_SNAPSHOT)
|
||||
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// Fetch in a synchronous reentrant way, in case this method is called
|
||||
// from a database access.
|
||||
let fetchedValue = try databaseAccess.dbPool.unsafeReentrantRead { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
let initialValue: Reducer.Value = reduceQueue.sync {
|
||||
guard let initialValue = reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
return initialValue
|
||||
}
|
||||
|
||||
// Start observation
|
||||
asyncStartObservation(from: databaseAccess)
|
||||
|
||||
return initialValue
|
||||
}
|
||||
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from databaseAccess: DatabaseAccess) {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
databaseAccess.dbPool.asyncRead { dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue = try databaseAccess.fetch(dbResult.get())
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// a database dispatch queue longer than necessary.
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
guard let initialValue = self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(from: databaseAccess)
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncStartObservation(from databaseAccess: DatabaseAccess) {
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
|
||||
// We don't know if database has changed or not.
|
||||
// So we assume it did, so that we are sure that we do
|
||||
// not miss a database change.
|
||||
events.databaseDidChange?()
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
fetchedValue = try writerDB.isolated(readOnly: true) {
|
||||
try databaseAccess.fetch(writerDB)
|
||||
}
|
||||
let region = try DatabaseRegion.union(regions)(writerDB)
|
||||
let observedRegion = try region.observableRegion(writerDB)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
self.startObservation(writerDB, observedRegion: observedRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try writerDB.recordingSelection(®ion) {
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
try databaseAccess.fetch(writerDB)
|
||||
}
|
||||
}
|
||||
let observedRegion = try region.observableRegion(writerDB)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
self.startObservation(writerDB, observedRegion: observedRegion)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering
|
||||
// between transactions and notifications!
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.stopDatabaseObservation(writerDB)
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
|
||||
extension ValueConcurrentObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if let region = observationState.region {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ writerDB: Database) {
|
||||
// Ignore transaction unless database was modified
|
||||
guard observationState.isModified else { return }
|
||||
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Ignore transaction unless we are still notifying database events, and
|
||||
// we can still access the database.
|
||||
let (eventsOpt, databaseAccessOpt) = lock.synchronized {
|
||||
(notificationCallbacks?.events, self.databaseAccess)
|
||||
}
|
||||
guard let events = eventsOpt, let databaseAccess = databaseAccessOpt else { return /* Cancelled */ }
|
||||
|
||||
events.databaseDidChange?()
|
||||
|
||||
// Fetch
|
||||
let future: DatabaseFuture<Reducer.Fetched>
|
||||
|
||||
switch trackingMode {
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
future = databaseAccess.dbPool.concurrentRead { db in
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// When the tracked region is not constant, we can't perform
|
||||
// concurrent fetches of observed values.
|
||||
//
|
||||
// This is because after a concurrent fetch has acquired snapshot
|
||||
// isolation, and before it completes, a change can be performed
|
||||
// in the *next* tracked region. When this happens, the
|
||||
// concurrent fetch has loaded an obsolete value, and we need to
|
||||
// perform a new fetch, with the latest values. But the
|
||||
// observation was not triggered by the change because we didn't
|
||||
// know that this change was about to be tracked! This means
|
||||
// that we'd miss a change, and fail notifying the latest value.
|
||||
//
|
||||
// Conclusion: fetch from the writer connection, and update the
|
||||
// tracked region.
|
||||
do {
|
||||
var region = DatabaseRegion()
|
||||
let fetchedValue = try writerDB.recordingSelection(®ion) {
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
try databaseAccess.fetch(writerDB)
|
||||
}
|
||||
}
|
||||
|
||||
let observedRegion = try region.observableRegion(writerDB)
|
||||
|
||||
// Don't spam the user with region tracking events: wait for an actual change
|
||||
if let willTrackRegion = events.willTrackRegion, observedRegion != observationState.region {
|
||||
willTrackRegion(observedRegion)
|
||||
}
|
||||
|
||||
observationState.region = observedRegion
|
||||
future = DatabaseFuture(.success(fetchedValue))
|
||||
} catch {
|
||||
stopDatabaseObservation(writerDB)
|
||||
notifyError(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering between
|
||||
// transactions and notifications!
|
||||
reduceQueue.async {
|
||||
do {
|
||||
// Wait until fetch has completed
|
||||
// TODO: find a way to guarantee correct ordering without waiting for a semaphore and blocking a thread.
|
||||
let fetchedValue = try future.wait()
|
||||
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify value
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool }
|
||||
dbPool?.asyncWriteWithoutTransaction { writerDB in
|
||||
self.stopDatabaseObservation(writerDB)
|
||||
}
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Ending the Observation
|
||||
|
||||
extension ValueConcurrentObserver: DatabaseCancellable {
|
||||
func cancel() {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Notify cancellation
|
||||
let (eventsOpt, dbPoolOpt): (ValueObservationEvents?, DatabasePool?) = lock.synchronized {
|
||||
let events = notificationCallbacks?.events
|
||||
notificationCallbacks = nil
|
||||
return (events, databaseAccess?.dbPool)
|
||||
}
|
||||
|
||||
guard let events = eventsOpt else { return /* Cancelled or failed */ }
|
||||
events.didCancel?()
|
||||
|
||||
// Stop observing the database
|
||||
// Do it asynchronously, so that we do not block the current thread:
|
||||
// cancellation may be triggered while a long write access is executing.
|
||||
guard let dbPool = dbPoolOpt else { return /* Failed */ }
|
||||
dbPool.asyncWriteWithoutTransaction { db in
|
||||
self.stopDatabaseObservation(db)
|
||||
}
|
||||
}
|
||||
|
||||
func notifyError(_ error: Error) {
|
||||
scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt: ValueObservationEvents? = self.lock.synchronized {
|
||||
let events = self.notificationCallbacks?.events
|
||||
self.notificationCallbacks = nil
|
||||
return events
|
||||
}
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
events.didFail?(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func stopDatabaseObservation(_ writerDB: Database) {
|
||||
writerDB.remove(transactionObserver: self)
|
||||
observationState = .notObserving
|
||||
lock.synchronized {
|
||||
databaseAccess = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ public struct ValueObservation<Reducer: ValueReducer> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures the tracked region
|
||||
enum ValueObservationTrackingMode {
|
||||
/// The tracked region is constant and explicit.
|
||||
///
|
||||
@@ -244,8 +245,8 @@ extension ValueObservation: Refinable {
|
||||
/// Returns the value.
|
||||
func fetchValue(_ db: Database) throws -> Reducer.Value {
|
||||
var reducer = makeReducer()
|
||||
guard let value = try reducer.fetchAndReduce(db) else {
|
||||
fatalError("Contract broken: reducer has no initial value")
|
||||
guard let value = try reducer._value(reducer._fetch(db)) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -401,11 +402,8 @@ extension ValueObservation {
|
||||
scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main))
|
||||
-> DatabasePublishers.Value<Reducer.Value>
|
||||
{
|
||||
DatabasePublishers.Value { [weak reader] (onError, onChange) in
|
||||
guard let reader = reader else {
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
}
|
||||
return self.start(
|
||||
DatabasePublishers.Value { (onError, onChange) in
|
||||
self.start(
|
||||
in: reader,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
@@ -471,8 +469,8 @@ extension DatabasePublishers {
|
||||
downstream: Downstream)
|
||||
{
|
||||
state = .waitingForDemand(WaitingForDemand(
|
||||
downstream: downstream,
|
||||
start: start))
|
||||
downstream: downstream,
|
||||
start: start))
|
||||
}
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
@@ -483,8 +481,8 @@ extension DatabasePublishers {
|
||||
return
|
||||
}
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
remainingDemand: demand))
|
||||
downstream: info.downstream,
|
||||
remainingDemand: demand))
|
||||
let cancellable = info.start(
|
||||
{ [weak self] error in self?.receiveCompletion(.failure(error)) },
|
||||
{ [weak self] value in self?.receive(value) })
|
||||
|
||||
@@ -14,6 +14,9 @@ public class ValueObservationScheduler {
|
||||
impl.schedule(action)
|
||||
}
|
||||
|
||||
/// Returns whether the initial value should be immediately notified.
|
||||
///
|
||||
/// If true, then this method was called on the main thread.
|
||||
func immediateInitialValue() -> Bool {
|
||||
impl.immediateInitialValue()
|
||||
}
|
||||
@@ -71,6 +74,10 @@ public class ValueObservationScheduler {
|
||||
|
||||
private protocol ValueObservationSchedulerImpl {
|
||||
func schedule(_ action: @escaping () -> Void)
|
||||
|
||||
/// Returns whether the initial value should be immediately notified.
|
||||
///
|
||||
/// If true, then this method was called on the main thread.
|
||||
func immediateInitialValue() -> Bool
|
||||
}
|
||||
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Support for ValueObservation.
|
||||
/// See DatabaseWriter.add(observation:onError:onChange:)
|
||||
final class ValueObserver<Reducer: ValueReducer> {
|
||||
var isCompleted: Bool { synchronized { _isCompleted } }
|
||||
let events: ValueObservationEvents
|
||||
let trackingMode: ValueObservationTrackingMode
|
||||
private var observedRegion: DatabaseRegion? {
|
||||
didSet {
|
||||
if let willTrackRegion = events.willTrackRegion,
|
||||
let region = observedRegion,
|
||||
region != oldValue
|
||||
{
|
||||
willTrackRegion(region)
|
||||
}
|
||||
}
|
||||
}
|
||||
private var _isCompleted = false
|
||||
private var reducer: Reducer
|
||||
private let requiresWriteAccess: Bool
|
||||
private weak var writer: DatabaseWriter?
|
||||
private let scheduler: ValueObservationScheduler
|
||||
private let reduceQueue: DispatchQueue
|
||||
private var isChanged = false
|
||||
private let onChange: (Reducer.Value) -> Void
|
||||
|
||||
// This lock protects `_isCompleted`.
|
||||
// It also protects `reducer` because of what is likely a compiler bug:
|
||||
// - <https://github.com/groue/GRDB.swift/issues/1026>
|
||||
// - <https://github.com/groue/GRDB.swift/pull/1025>
|
||||
private var lock = NSRecursiveLock() // protects _isCompleted and reducer
|
||||
|
||||
init(
|
||||
events: ValueObservationEvents,
|
||||
reducer: Reducer,
|
||||
requiresWriteAccess: Bool,
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
writer: DatabaseWriter,
|
||||
scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
self.events = events
|
||||
self.reducer = reducer
|
||||
self.requiresWriteAccess = requiresWriteAccess
|
||||
self.trackingMode = trackingMode
|
||||
self.writer = writer
|
||||
self.scheduler = scheduler
|
||||
self.reduceQueue = reduceQueue
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
convenience init(
|
||||
observation: ValueObservation<Reducer>,
|
||||
writer: DatabaseWriter,
|
||||
scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
self.init(
|
||||
events: observation.events,
|
||||
reducer: observation.makeReducer(),
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
trackingMode: observation.trackingMode,
|
||||
writer: writer,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: reduceQueue,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
extension ValueObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
assert(
|
||||
observedRegion != nil,
|
||||
"fetchInitialValue() was not called before ValueObserver was added as a transaction observer")
|
||||
return observedRegion!.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
assert(
|
||||
observedRegion != nil,
|
||||
"fetchInitialValue() was not called before ValueObserver was added as a transaction observer")
|
||||
if observedRegion!.isModified(by: event) {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ writerDB: Database) {
|
||||
guard isChanged else { return }
|
||||
isChanged = false
|
||||
if isCompleted { return }
|
||||
|
||||
events.databaseDidChange?()
|
||||
|
||||
guard let future = fetchFuture(writerDB) else {
|
||||
// Database connection closed: give up
|
||||
return
|
||||
}
|
||||
|
||||
reduce(future: future)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
isChanged = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
extension ValueObserver {
|
||||
/// Fetch the initial observed value, and moves the reducer forward.
|
||||
///
|
||||
/// This method must be called once, before the observer is added
|
||||
/// to the database writer.
|
||||
func fetchInitialValue(_ db: Database) throws -> Reducer.Value {
|
||||
guard let value = try fetchValue(db) else {
|
||||
fatalError("Contract broken: reducer has no initial value")
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/// Fetch an observed value, and moves the reducer forward.
|
||||
func fetchValue(_ db: Database) throws -> Reducer.Value? {
|
||||
try db.isolated(readOnly: !requiresWriteAccess) {
|
||||
try updatingObserverRegionIfNeeded(db) {
|
||||
try synchronized {
|
||||
try reducer.fetchAndReduce(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func complete() {
|
||||
synchronized {
|
||||
_isCompleted = true
|
||||
writer?.remove(transactionObserver: self)
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
synchronized {
|
||||
if _isCompleted { return }
|
||||
complete()
|
||||
events.didCancel?()
|
||||
}
|
||||
}
|
||||
|
||||
func notifyChange(_ value: Reducer.Value) {
|
||||
if isCompleted { return }
|
||||
scheduler.schedule {
|
||||
if self.isCompleted { return }
|
||||
self.onChange(value)
|
||||
}
|
||||
}
|
||||
|
||||
func notifyErrorAndComplete(_ error: Error) {
|
||||
if isCompleted { return }
|
||||
scheduler.schedule {
|
||||
let shouldNotify: Bool = self.synchronized {
|
||||
if self._isCompleted {
|
||||
return false
|
||||
} else {
|
||||
self.complete()
|
||||
return true
|
||||
}
|
||||
}
|
||||
if shouldNotify {
|
||||
self.events.didFail?(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
extension ValueObserver {
|
||||
/// Returns nil if the database was closed
|
||||
private func fetchFuture(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched>? {
|
||||
if requiresWriteAccess {
|
||||
// We obviously need to fetch from the writer connection
|
||||
return fetchFutureSync(writerDB)
|
||||
}
|
||||
|
||||
switch trackingMode {
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// When the tracked region is not constant, we must fetch from the
|
||||
// writer connection so that we do not miss future changes that
|
||||
// would modify the tracked region.
|
||||
return fetchFutureSync(writerDB)
|
||||
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
// When the tracked region is constant, we can fetch concurrently.
|
||||
return fetchFutureConcurrent(writerDB)
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchFutureSync(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched> {
|
||||
DatabaseFuture(Result {
|
||||
try writerDB.isolated(readOnly: !requiresWriteAccess) {
|
||||
try fetchUpdatingObserverRegionIfNeeded(writerDB)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns nil if the database was closed
|
||||
private func fetchFutureConcurrent(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched>? {
|
||||
guard let writer = writer else {
|
||||
// Database connection closed: give up
|
||||
return nil
|
||||
}
|
||||
return writer.concurrentRead { readerDB in
|
||||
try self.fetchUpdatingObserverRegionIfNeeded(readerDB)
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchUpdatingObserverRegionIfNeeded(_ db: Database) throws -> Reducer.Fetched {
|
||||
try updatingObserverRegionIfNeeded(db) {
|
||||
let reducer = synchronized { self.reducer }
|
||||
return try reducer._fetch(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func reduce(future: DatabaseFuture<Reducer.Fetched>) {
|
||||
// Wait for the future fetched value in reduceQueue. This guarantees:
|
||||
// - that notifications have the same ordering as transactions.
|
||||
// - that expensive reduce operations are computed without blocking
|
||||
// any database dispatch queue.
|
||||
reduceQueue.async {
|
||||
if self.isCompleted { return }
|
||||
do {
|
||||
let fetchedValue = try future.wait()
|
||||
if let value = self.synchronized({ self.reducer._value(fetchedValue) }) {
|
||||
self.notifyChange(value)
|
||||
}
|
||||
} catch {
|
||||
self.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func synchronized<T>(_ execute: () throws -> T) rethrows -> T {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return try execute()
|
||||
}
|
||||
|
||||
private func updatingObserverRegionIfNeeded<T>(
|
||||
_ db: Database,
|
||||
fetch: () throws -> T)
|
||||
throws -> T
|
||||
{
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
if observedRegion == nil {
|
||||
observedRegion = try DatabaseRegion.union(regions)(db)
|
||||
}
|
||||
return try fetch()
|
||||
case .constantRegionRecordedFromSelection:
|
||||
if observedRegion == nil {
|
||||
return try recordingSelectedRegion(db, fetch: fetch)
|
||||
} else {
|
||||
return try fetch()
|
||||
}
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
return try recordingSelectedRegion(db, fetch: fetch)
|
||||
}
|
||||
}
|
||||
|
||||
private func recordingSelectedRegion<T>(
|
||||
_ db: Database,
|
||||
fetch: () throws -> T)
|
||||
throws -> T
|
||||
{
|
||||
var region = DatabaseRegion()
|
||||
let result = try db.recordingSelection(®ion, fetch)
|
||||
observedRegion = try region.observableRegion(db)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -32,12 +32,6 @@ public protocol _ValueReducer {
|
||||
/// The `ValueReducer` protocol supports `ValueObservation`.
|
||||
public protocol ValueReducer: _ValueReducer { }
|
||||
|
||||
extension ValueReducer {
|
||||
mutating func fetchAndReduce(_ db: Database) throws -> Value? {
|
||||
try _value(_fetch(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// A namespace for types related to the `ValueReducer` protocol.
|
||||
public enum ValueReducers {
|
||||
// ValueReducers.Auto allows us to define ValueObservation factory methods.
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
import Foundation
|
||||
|
||||
/// `ValueWriteOnlyObserver` observes the database for `ValueObservation`.
|
||||
///
|
||||
/// It performs the following database observation cycle:
|
||||
///
|
||||
/// 1. Start observation or detect a database change
|
||||
/// 2. Fetch
|
||||
/// 3. Reduce
|
||||
/// 4. Notify
|
||||
///
|
||||
/// **Fetch** is always performed from the writer database connection (hence
|
||||
/// the name of this observer).
|
||||
///
|
||||
/// **Reduce** is the operation that turns the fetched database values into the
|
||||
/// observed values. Those are not the same. Consider, for example, the `map()`
|
||||
/// and `removeDuplicates()` operators: they perform their job during the
|
||||
/// reducing stage.
|
||||
///
|
||||
/// **Notify** is calling user callbacks, in case of database change or error.
|
||||
final class ValueWriteOnlyObserver<Writer: DatabaseWriter, Reducer: ValueReducer> {
|
||||
// MARK: - Configuration
|
||||
//
|
||||
// Configuration is not mutable.
|
||||
|
||||
/// How to schedule observed values and errors.
|
||||
private let scheduler: ValueObservationScheduler
|
||||
|
||||
/// If true, database values are fetched from a read-only access.
|
||||
private let readOnly: Bool
|
||||
|
||||
/// Configures the tracked database region.
|
||||
private let trackingMode: ValueObservationTrackingMode
|
||||
|
||||
// MARK: - Mutable State
|
||||
//
|
||||
// The observer has four distinct mutable states that evolve independently,
|
||||
// and are made thread-safe with various mechanisms:
|
||||
//
|
||||
// - A `DatabaseAccess`: ability to access the database. It is constant but
|
||||
// turns nil after the observation fails or is cancelled, in order to
|
||||
// release memory and resources when the observation completes. It is
|
||||
// guarded by `lock`, because observation can fail or be cancelled from
|
||||
// multiple threads.
|
||||
//
|
||||
// - A `NotificationCallbacks`: ability to notify observation events. It is
|
||||
// constant but turns nil when failure or cancellation is notified, in
|
||||
// order to release memory and resources when the observation completes.
|
||||
// It is guarded by `lock`, because observation can fail or be cancelled
|
||||
// from multiple threads.
|
||||
//
|
||||
// - An `ObservationState`: relationship with the `TransactionObserver`
|
||||
// protocol. It is only accessed from the serialized writer
|
||||
// dispatch queue.
|
||||
//
|
||||
// - A `Reducer`: the observation reducer, only accessed from the
|
||||
// serialized dispatch queue `reduceQueue`.
|
||||
//
|
||||
// The `reduceQueue` guarantees that fresh value notifications have the same
|
||||
// order as transactions. It is different from the serialized writer
|
||||
// dispatch queue because we do not want to lock the database as
|
||||
// computations (`map`, `removeDuplicates()`, etc.) are performed.
|
||||
//
|
||||
// Despite being protected by the same lock, `DatabaseAccess` and
|
||||
// `NotificationCallbacks` are not merged together. This is because the
|
||||
// observer does not lose `DatabaseAccess` at the same time it
|
||||
// looses `NotificationCallbacks`:
|
||||
//
|
||||
// - In case of cancellation, `NotificationCallbacks` is lost first, and
|
||||
// `DatabaseAccess` is lost asynchronously, after the observer could
|
||||
// resign as a transaction observer. See `cancel()`.
|
||||
//
|
||||
// - In case of error, `DatabaseAccess` is lost first, and
|
||||
// `NotificationCallbacks` is lost asynchronously, after the error could
|
||||
// be notified. See error catching clauses.
|
||||
|
||||
/// Ability to access the database
|
||||
private struct DatabaseAccess {
|
||||
/// The observed DatabaseWriter.
|
||||
let writer: Writer
|
||||
|
||||
/// The function that fetches database values.
|
||||
let fetch: (Database) throws -> Reducer.Fetched
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
let events: ValueObservationEvents
|
||||
let onChange: (Reducer.Value) -> Void
|
||||
}
|
||||
|
||||
/// Relationship with the `TransactionObserver` protocol
|
||||
private struct ObservationState {
|
||||
var region: DatabaseRegion?
|
||||
var isModified = false
|
||||
|
||||
static var notObserving: Self { .init(region: nil, isModified: false) }
|
||||
}
|
||||
|
||||
/// Protects `databaseAccess` and `notificationCallbacks`.
|
||||
private let lock = NSLock()
|
||||
|
||||
/// The dispatch queue where database values are reduced into observed
|
||||
/// values before being notified. Protects `reducer`.
|
||||
private let reduceQueue: DispatchQueue
|
||||
|
||||
/// Access to the database, protected by `lock`.
|
||||
private var databaseAccess: DatabaseAccess?
|
||||
|
||||
/// Ability to notify observation events, protected by `lock`.
|
||||
private var notificationCallbacks: NotificationCallbacks?
|
||||
|
||||
/// Support for `TransactionObserver`, protected by the serialized writer
|
||||
/// dispatch queue.
|
||||
private var observationState = ObservationState.notObserving
|
||||
|
||||
/// Protected by `reduceQueue`.
|
||||
private var reducer: Reducer
|
||||
|
||||
init(
|
||||
writer: Writer,
|
||||
scheduler: ValueObservationScheduler,
|
||||
readOnly: Bool,
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
reducer: Reducer,
|
||||
events: ValueObservationEvents,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
// Configuration
|
||||
self.scheduler = scheduler
|
||||
self.readOnly = readOnly
|
||||
self.trackingMode = trackingMode
|
||||
|
||||
// State
|
||||
self.databaseAccess = DatabaseAccess(
|
||||
writer: writer,
|
||||
// ValueReducer semantics guarantees that reducer._fetch
|
||||
// is independent from the reducer state
|
||||
fetch: reducer._fetch)
|
||||
self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange)
|
||||
self.reducer = reducer
|
||||
self.reduceQueue = writer.configuration.makeReaderDispatchQueue(label: writer.configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation"))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Starting the Observation
|
||||
|
||||
extension ValueWriteOnlyObserver {
|
||||
// Starts the observation
|
||||
func start() -> DatabaseCancellable {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let (notificationCallbacksOpt, databaseAccessOpt) = lock.synchronized {
|
||||
(self.notificationCallbacks, self.databaseAccess)
|
||||
}
|
||||
guard let notificationCallbacks = notificationCallbacksOpt, let writer = databaseAccessOpt?.writer else {
|
||||
// Likely a GRDB bug
|
||||
fatalError("can't start a cancelled or failed observation")
|
||||
}
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Start the observation in an synchronous way
|
||||
let initialValue = try syncStart(from: writer)
|
||||
|
||||
// Notify the initial value from the dispatch queue the
|
||||
// observation was started from
|
||||
notificationCallbacks.onChange(initialValue)
|
||||
} catch {
|
||||
// Notify error from the dispatch queue the observation
|
||||
// was started from.
|
||||
notificationCallbacks.events.didFail?(error)
|
||||
|
||||
// Early return!
|
||||
return AnyDatabaseCancellable { /* nothing to cancel */ }
|
||||
}
|
||||
} else {
|
||||
// Start the observation in an asynchronous way
|
||||
asyncStart(from: writer)
|
||||
}
|
||||
|
||||
// Make sure the returned cancellable cancels the observation
|
||||
// when deallocated. We can't relying on the deallocation of
|
||||
// self to trigger early cancellation, because self may be retained by
|
||||
// some closure waiting to run in some DispatchQueue.
|
||||
return AnyDatabaseCancellable(self)
|
||||
}
|
||||
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from writer: Writer) throws -> Reducer.Value {
|
||||
// Start from a write access, so that self can register as a
|
||||
// transaction observer.
|
||||
//
|
||||
// Start in a synchronous reentrant way, in case this method is called
|
||||
// from a database access.
|
||||
try writer.unsafeReentrantWrite { db in
|
||||
// Fetch & Start observing the database
|
||||
let fetchedValue = try fetchAndStartObservation(db)
|
||||
|
||||
// Reduce
|
||||
return reduceQueue.sync {
|
||||
guard let initialValue = reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
return initialValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from writer: Writer) {
|
||||
// Start from a write access, so that self can register as a
|
||||
// transaction observer.
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch & Start observing the database
|
||||
let fetchedValue = try self.fetchAndStartObservation(db)
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering
|
||||
// between transactions and notifications!
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
guard let initialValue = self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.stopDatabaseObservation(db)
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the initial value, and start observing the database.
|
||||
///
|
||||
/// By grouping the initial fetch and the beginning of observation in a
|
||||
/// single database access, we are sure that no concurrent write can happen
|
||||
/// during the initial fetch, and that we won't miss any future change.
|
||||
private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let (eventsOpt, fetchOpt) = lock.synchronized {
|
||||
(notificationCallbacks?.events, databaseAccess?.fetch)
|
||||
}
|
||||
guard let events = eventsOpt, let fetch = fetchOpt else {
|
||||
// Likely a GRDB bug
|
||||
fatalError("can't start a cancelled or failed observation")
|
||||
}
|
||||
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let observedRegion = try region.observableRegion(db)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
startObservation(db, observedRegion: observedRegion)
|
||||
return fetchedValue
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
let fetchedValue = try db.recordingSelection(®ion) {
|
||||
try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
}
|
||||
let observedRegion = try region.observableRegion(db)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
startObservation(db, observedRegion: observedRegion)
|
||||
return fetchedValue
|
||||
}
|
||||
}
|
||||
|
||||
private func startObservation(_ db: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
db.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
|
||||
extension ValueWriteOnlyObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if let region = observationState.region {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
// Ignore transaction unless database was modified
|
||||
guard observationState.isModified else { return }
|
||||
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Ignore transaction unless we are still notifying database events, and
|
||||
// we can still fetch fresh values.
|
||||
let (eventsOpt, fetchOpt) = lock.synchronized {
|
||||
(notificationCallbacks?.events, databaseAccess?.fetch)
|
||||
}
|
||||
guard let events = eventsOpt, let fetch = fetchOpt else { return /* Cancelled */ }
|
||||
|
||||
// Notify
|
||||
events.databaseDidChange?()
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
|
||||
switch trackingMode {
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
// Tracked region is already known. Fetch only.
|
||||
fetchedValue = try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// Fetch and update the tracked region.
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try db.recordingSelection(®ion) {
|
||||
try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
}
|
||||
|
||||
let observedRegion = try region.observableRegion(db)
|
||||
|
||||
// Don't spam the user with region tracking events: wait for an actual change
|
||||
if let willTrackRegion = events.willTrackRegion, observedRegion != observationState.region {
|
||||
willTrackRegion(observedRegion)
|
||||
}
|
||||
|
||||
observationState.region = observedRegion
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering between
|
||||
// transactions and notifications!
|
||||
reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify value
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
stopDatabaseObservation(db)
|
||||
notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Ending the Observation
|
||||
|
||||
extension ValueWriteOnlyObserver: DatabaseCancellable {
|
||||
func cancel() {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Notify cancellation
|
||||
let (eventsOpt, writerOpt): (ValueObservationEvents?, Writer?) = lock.synchronized {
|
||||
let events = notificationCallbacks?.events
|
||||
notificationCallbacks = nil
|
||||
return (events, databaseAccess?.writer)
|
||||
}
|
||||
|
||||
guard let events = eventsOpt else { return /* Cancelled or failed */ }
|
||||
events.didCancel?()
|
||||
|
||||
// Stop observing the database
|
||||
// Do it asynchronously, so that we do not block the current thread:
|
||||
// cancellation may be triggered while a long write access is executing.
|
||||
guard let writer = writerOpt else { return /* Failed */ }
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
self.stopDatabaseObservation(db)
|
||||
}
|
||||
}
|
||||
|
||||
func notifyError(_ error: Error) {
|
||||
scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt: ValueObservationEvents? = self.lock.synchronized {
|
||||
let events = self.notificationCallbacks?.events
|
||||
self.notificationCallbacks = nil
|
||||
return events
|
||||
}
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
events.didFail?(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func stopDatabaseObservation(_ db: Database) {
|
||||
db.remove(transactionObserver: self)
|
||||
observationState = .notObserving
|
||||
lock.synchronized {
|
||||
databaseAccess = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,8 +168,8 @@
|
||||
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
|
||||
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
|
||||
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
|
||||
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43D21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
@@ -360,6 +360,8 @@
|
||||
5676FBAB22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; };
|
||||
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533A27E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
@@ -886,7 +888,7 @@
|
||||
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -991,6 +993,7 @@
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = "<group>"; };
|
||||
@@ -1282,9 +1285,10 @@
|
||||
children = (
|
||||
563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233D027243A9100529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */,
|
||||
5613ED5921A95E6100DC7A68 /* ValueObservation.swift */,
|
||||
563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */,
|
||||
564CE43B21AA955B00652B19 /* ValueObserver.swift */,
|
||||
5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56C0538822ACEECD0029D27D /* ValueReducer */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
@@ -2045,9 +2049,9 @@
|
||||
buildConfigurationList = F3BA80031CFB25E4003DC1BA /* Build configuration list for PBXNativeTarget "GRDBiOS" */;
|
||||
buildPhases = (
|
||||
EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */,
|
||||
F3BA7FFB1CFB25E4003DC1BA /* Headers */,
|
||||
F3BA7FF91CFB25E4003DC1BA /* Sources */,
|
||||
F3BA7FFA1CFB25E4003DC1BA /* Frameworks */,
|
||||
F3BA7FFB1CFB25E4003DC1BA /* Headers */,
|
||||
F3BA7FFC1CFB25E4003DC1BA /* Resources */,
|
||||
56EB54FD22C9119B00850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2084,9 +2088,9 @@
|
||||
buildConfigurationList = F3BA805F1CFB2BB2003DC1BA /* Build configuration list for PBXNativeTarget "GRDBOSX" */;
|
||||
buildPhases = (
|
||||
EED476F51CFD1A610026A4EC /* Copy .example configuration files (if no USER customizations exist) */,
|
||||
F3BA80571CFB2BB2003DC1BA /* Headers */,
|
||||
F3BA80551CFB2BB2003DC1BA /* Sources */,
|
||||
F3BA80561CFB2BB2003DC1BA /* Frameworks */,
|
||||
F3BA80571CFB2BB2003DC1BA /* Headers */,
|
||||
F3BA80581CFB2BB2003DC1BA /* Resources */,
|
||||
56EB54FB22C9118600850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2298,6 +2302,7 @@
|
||||
files = (
|
||||
5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5679533A27E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2401,7 +2406,7 @@
|
||||
561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */,
|
||||
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED72210731100945324 /* SQLRequest.swift in Sources */,
|
||||
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43D21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
|
||||
@@ -2667,6 +2672,7 @@
|
||||
files = (
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2770,7 +2776,7 @@
|
||||
561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */,
|
||||
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
|
||||
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
|
||||
|
||||
@@ -50,7 +50,16 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
|
||||
# When adding support for an Xcode version, look for available devices with
|
||||
# `xcrun xctrace list devices` (or the deprecated `instruments -s devices`).
|
||||
ifeq ($(XCODEVERSION),13.2)
|
||||
ifeq ($(XCODEVERSION),13.3)
|
||||
MAX_SWIFT_VERSION = 5.6
|
||||
MIN_SWIFT_VERSION = 5.3
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.4"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4"
|
||||
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
|
||||
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks'
|
||||
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
|
||||
else ifeq ($(XCODEVERSION),13.2)
|
||||
MAX_SWIFT_VERSION = 5.5
|
||||
MIN_SWIFT_VERSION = 5.3
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.2"
|
||||
@@ -529,10 +538,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.21.0 \
|
||||
--module-version 5.21.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.22.0 \
|
||||
--module-version 5.22.0 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.21/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.22/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: February 6, 2022 • [version 5.21.0](https://github.com/groue/GRDB.swift/tree/v5.21.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
**Latest release**: March 22, 2022 • [version 5.22.0](https://github.com/groue/GRDB.swift/tree/v5.22.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.3+** | **v5.21.0** |
|
||||
| **Swift 5.3+** | **v5.22.0** |
|
||||
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
|
||||
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
@@ -318,7 +318,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.21/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.22/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -610,7 +610,7 @@ do {
|
||||
>
|
||||
> :warning: **Warning**: The SQLite version that ships with old operating systems (prior to OSX 10.12, tvOS 10.0, and watchOS 3.0) outputs statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag.
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.21/Structs/Configuration.html) for more details and configuration options.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.22/Structs/Configuration.html) for more details and configuration options.
|
||||
|
||||
|
||||
SQLite API
|
||||
@@ -667,7 +667,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
|
||||
|
||||
@@ -925,7 +925,7 @@ try dbQueue.read { db in
|
||||
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
```
|
||||
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.21/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.22/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
|
||||
```swift
|
||||
// Prints all Github links
|
||||
@@ -1004,7 +1004,7 @@ let rows = try Row.fetchAll(db,
|
||||
arguments: ["name": "Arthur"])
|
||||
```
|
||||
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
|
||||
|
||||
@@ -1289,7 +1289,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
|
||||
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1760,7 +1760,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
}
|
||||
```
|
||||
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.21/Structs/Configuration.html) configuration flag:
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.22/Structs/Configuration.html) configuration flag:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
@@ -1872,7 +1872,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -1955,7 +1955,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates)
|
||||
|
||||
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
|
||||
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.21/Classes/Statement.html).
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.22/Classes/Statement.html).
|
||||
|
||||
|
||||
### Prepared Statements Cache
|
||||
@@ -2698,7 +2698,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
|
||||
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
|
||||
|
||||
@@ -3138,7 +3138,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.21/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.21/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.22/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.22/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
|
||||
### Date and UUID Coding Strategies
|
||||
@@ -3160,7 +3160,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.21/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.21/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.21/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.22/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.22/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.22/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
|
||||
|
||||
@@ -4685,7 +4685,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.21/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.22/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -5591,7 +5591,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
|
||||
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
|
||||
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.21/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.22/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
|
||||
|
||||
## Joined Queries Support
|
||||
@@ -6135,10 +6135,10 @@ See the companion library [RxGRDB] for more information.
|
||||
- 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.
|
||||
- Starting an observation retains the database connection, until it is stopped. As long as the observation is active, the database connection won't be deallocated.
|
||||
- The database observation stops when any of those conditions is met:
|
||||
- The cancellable returned by the `start` method is cancelled or deinitialized.
|
||||
- An error occurs.
|
||||
- The database connection is closed.
|
||||
|
||||
Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation]. If you need to process uncommitted changes, see [TransactionObserver](#transactionobserver-protocol).
|
||||
|
||||
@@ -6408,19 +6408,15 @@ let sharedObservation = ValueObservation
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
```
|
||||
|
||||
> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there are a few differences you should be aware of:
|
||||
>
|
||||
> - `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may use Combine apis:
|
||||
>
|
||||
> ```swift
|
||||
> let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue)
|
||||
> let cancellable = try sharedObservation
|
||||
> .publisher() // Turn shared observation into a Combine Publisher
|
||||
> .map { ... } // The map operator from Combine
|
||||
> .sink(...)
|
||||
> ```
|
||||
>
|
||||
> - Unlike `ValueObservation`, `SharedValueObservation` retains the database connection. As long as there exists a `SharedValueObservation` instance, or an active suscription to a shared observation, the database connection won't be deinitialized.
|
||||
> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there is a difference you should be aware of. `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may, for example, use Combine apis:
|
||||
>
|
||||
> ```swift
|
||||
> let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue)
|
||||
> let cancellable = try sharedObservation
|
||||
> .publisher() // Turn shared observation into a Combine Publisher
|
||||
> .map { ... } // The map operator from Combine
|
||||
> .sink(...)
|
||||
> ```
|
||||
|
||||
|
||||
### Specifying the Region Tracked by ValueObservation
|
||||
@@ -6895,7 +6891,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch
|
||||
|
||||
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
|
||||
|
||||
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.21/Structs/DatabaseRegion.html).
|
||||
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.22/Structs/DatabaseRegion.html).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
@@ -8235,7 +8231,7 @@ When this is the case, there are two possible explanations:
|
||||
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
|
||||
```
|
||||
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.21/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.22/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
|
||||
|
||||
|
||||
@@ -8376,7 +8372,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots).
|
||||
|
||||
#### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.21/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.21/Protocols/DatabaseWriter.html).
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.22/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.22/Protocols/DatabaseWriter.html).
|
||||
|
||||
#### Asynchronous APIs
|
||||
|
||||
@@ -8429,7 +8425,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
|
||||
[Sharing a Database]: Documentation/SharingADatabase.md
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: #database-changes-observation
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.21/Structs/SQLRequest.html
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.22/Structs/SQLRequest.html
|
||||
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>5.21.0</string>
|
||||
<string>5.22.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
- [ ] Enhance the introduction to SQLRequest, based on the feedback in https://github.com/groue/GRDB.swift/issues/617
|
||||
- [ ] Association: document how to use aggregates with inner join (testAnnotatedWithHasManyDefaultMaxJoiningRequired)
|
||||
- [ ] Should we document that `PRAGMA locking_mode = EXCLUSIVE` improves performances? https://sqlite.org/forum/forumpost/866bf3407a
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
@@ -79,6 +79,91 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testMissingIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = A.orderByPrimaryKey()
|
||||
|
||||
do {
|
||||
struct Record: FetchableRecord, Decodable, Equatable {
|
||||
var a: A
|
||||
var bs: [B]? // Support for missing association
|
||||
}
|
||||
|
||||
// Record.fetchAll
|
||||
do {
|
||||
let records = try Record.fetchAll(db, request)
|
||||
XCTAssertEqual(records, [
|
||||
Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 2, "cola2": "a2"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 3, "cola2": "a3"]),
|
||||
bs: nil),
|
||||
])
|
||||
}
|
||||
|
||||
// Record.fetchOne
|
||||
do {
|
||||
let record = try Record.fetchOne(db, request)!
|
||||
XCTAssertEqual(record, Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil))
|
||||
}
|
||||
}
|
||||
|
||||
// Test container.decodeNil
|
||||
do {
|
||||
struct Record: FetchableRecord, Decodable, Equatable {
|
||||
var a: A
|
||||
var bs: [B]? // Support for missing association
|
||||
|
||||
init(a: A, bs: [B]?) {
|
||||
self.a = a
|
||||
self.bs = bs
|
||||
}
|
||||
|
||||
enum CodingKeys: CodingKey { case a, bs }
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
a = try container.decode(A.self, forKey: .a)
|
||||
if try container.decodeNil(forKey: .bs) {
|
||||
bs = nil
|
||||
} else {
|
||||
bs = []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Record.fetchAll
|
||||
do {
|
||||
let records = try Record.fetchAll(db, request)
|
||||
XCTAssertEqual(records, [
|
||||
Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 2, "cola2": "a2"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 3, "cola2": "a3"]),
|
||||
bs: nil),
|
||||
])
|
||||
}
|
||||
|
||||
// Record.fetchOne
|
||||
do {
|
||||
let record = try Record.fetchOne(db, request)!
|
||||
XCTAssertEqual(record, Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil))
|
||||
}
|
||||
} }
|
||||
}
|
||||
|
||||
func testIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -209,6 +294,62 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
// Test container.decodeNil
|
||||
do {
|
||||
struct Record: FetchableRecord, Decodable, Equatable {
|
||||
var a: A
|
||||
var bs: [B]
|
||||
|
||||
init(a: A, bs: [B]) {
|
||||
self.a = a
|
||||
self.bs = bs
|
||||
}
|
||||
|
||||
enum CodingKeys: CodingKey { case a, bs }
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
a = try container.decode(A.self, forKey: .a)
|
||||
if try container.decodeNil(forKey: .bs) {
|
||||
fatalError("Test failed")
|
||||
} else {
|
||||
bs = try container.decode([B].self, forKey: .bs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Record.fetchAll
|
||||
do {
|
||||
let records = try Record.fetchAll(db, request)
|
||||
XCTAssertEqual(records, [
|
||||
Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: [
|
||||
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
|
||||
B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]),
|
||||
]),
|
||||
Record(
|
||||
a: A(row: ["cola1": 2, "cola2": "a2"]),
|
||||
bs: [
|
||||
B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]),
|
||||
]),
|
||||
Record(
|
||||
a: A(row: ["cola1": 3, "cola2": "a3"]),
|
||||
bs: []),
|
||||
])
|
||||
}
|
||||
|
||||
// Record.fetchOne
|
||||
do {
|
||||
let record = try Record.fetchOne(db, request)!
|
||||
XCTAssertEqual(record, Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: [
|
||||
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
|
||||
B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]),
|
||||
]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
|
||||
@@ -226,6 +226,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(DatabaseError.errorDomain, "GRDB.DatabaseError")
|
||||
XCTAssertEqual(error.domain, DatabaseError.errorDomain)
|
||||
XCTAssertEqual(error.code, 787)
|
||||
XCTAssertNotNil(error.localizedFailureReason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
@@ -84,7 +84,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
@@ -155,7 +155,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
@@ -168,7 +168,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
@@ -212,7 +212,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
@@ -256,7 +256,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
@@ -342,7 +342,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
switch value {
|
||||
case 0:
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
case 1:
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 1"])
|
||||
case 2:
|
||||
@@ -432,7 +432,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
@@ -526,7 +526,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
@@ -582,7 +582,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
@@ -596,7 +596,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
fetchError = nil
|
||||
let recorder = publisher.record()
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 1", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 1"])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -186,8 +186,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings.prefix(7), [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"value: Optional(1)"])
|
||||
@@ -228,8 +228,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings.prefix(7), [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"value: Optional(1)"])
|
||||
@@ -325,8 +325,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"failure: SQLite error 1: no such table: player - while executing `SELECT MAX(id) FROM player`"])
|
||||
@@ -368,8 +368,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"failure: SQLite error 1: no such table: player - while executing `SELECT MAX(id) FROM player`"])
|
||||
@@ -422,9 +422,9 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil"])
|
||||
}
|
||||
}
|
||||
@@ -469,9 +469,9 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil"])
|
||||
}
|
||||
}
|
||||
@@ -520,8 +520,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings.prefix(11), [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegionA),choice(t)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"tracked region: \(expectedRegionB),choice(t)",
|
||||
@@ -555,13 +555,15 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(logger1.strings.prefix(3), [
|
||||
XCTAssertEqual(logger1.strings.prefix(4), [
|
||||
"start",
|
||||
"fetch",
|
||||
"tracked region: player(*)",
|
||||
"value: nil"])
|
||||
XCTAssertEqual(logger2.strings.prefix(3), [
|
||||
XCTAssertEqual(logger2.strings.prefix(4), [
|
||||
"log: start",
|
||||
"log: fetch",
|
||||
"log: tracked region: player(*)",
|
||||
"log: value: nil"])
|
||||
}
|
||||
}
|
||||
@@ -589,13 +591,15 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(logger1.strings.prefix(3), [
|
||||
XCTAssertEqual(logger1.strings.prefix(4), [
|
||||
"start",
|
||||
"fetch",
|
||||
"tracked region: player(*)",
|
||||
"value: nil"])
|
||||
XCTAssertEqual(logger2.strings.prefix(3), [
|
||||
XCTAssertEqual(logger2.strings.prefix(4), [
|
||||
"start",
|
||||
"fetch",
|
||||
"tracked region: player(*)",
|
||||
"value: foo"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,13 +228,13 @@ extension ValueObservation {
|
||||
let cancellable = start(
|
||||
in: reader,
|
||||
scheduling: scheduler,
|
||||
onError: {
|
||||
onError: { [weak recorder] in
|
||||
onError?($0)
|
||||
recorder.onError($0)
|
||||
recorder?.onError($0)
|
||||
},
|
||||
onChange: {
|
||||
onChange: { [weak recorder] in
|
||||
onChange?($0)
|
||||
recorder.onChange($0)
|
||||
recorder?.onChange($0)
|
||||
})
|
||||
recorder.receive(cancellable)
|
||||
return recorder
|
||||
|
||||
@@ -210,8 +210,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
wait(for: [expectation], timeout: 4)
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"tracked region: t(*)",
|
||||
"fetch",
|
||||
"tracked region: t(*)",
|
||||
"value: 0",
|
||||
"database did change",
|
||||
"fetch",
|
||||
@@ -254,8 +254,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
wait(for: [expectation], timeout: 4)
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"tracked region: other(*)",
|
||||
"fetch",
|
||||
"tracked region: other(*)",
|
||||
"value: 0",
|
||||
"database did change",
|
||||
"fetch",
|
||||
@@ -298,8 +298,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
wait(for: [expectation], timeout: 4)
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"tracked region: other(*),t(*)",
|
||||
"fetch",
|
||||
"tracked region: other(*),t(*)",
|
||||
"value: 0",
|
||||
"database did change",
|
||||
"fetch",
|
||||
|
||||
Reference in new issue
Block a user