Compare commits

...
Author SHA1 Message Date
Gwendal Roué a5dde62219 TODO 2024-03-17 18:28:45 +01:00
Gwendal Roué fbe937c4ed Fix ValueObservationRecorder compiler warnings 2024-02-19 17:46:02 +01:00
Gwendal Roué e309196781 Fix AnyValueReducer compiler warnings 2024-02-18 14:16:59 +01:00
Gwendal Roué 91b9b2311b Fix compiler warnings about databaseEncodingUserInfo 2024-02-18 14:14:33 +01:00
Gwendal Roué a0ad849724 Fix Var is not concurrency-safe because it is non-isolated global shared mutable state 2024-02-18 13:06:25 +01:00
Gwendal Roué 178173197c Fix Concurrently-executed local function must be marked as '@Sendable' 2024-02-18 13:04:20 +01:00
Gwendal Roué 6822e5bd62 Fix concurrency warning 2024-02-18 13:04:20 +01:00
Gwendal Roué 8e0f2b0c4b Tests of parallel blocks need @Sendable closures 2024-02-18 13:04:20 +01:00
Gwendal Roué 50006a6aaa Refactor tests that database accesses and statements do not retain database pool and queue 2024-02-18 13:04:20 +01:00
Gwendal Roué 9514c7c7c2 Fix warnings regarding mutation of mutating variable in concurrently-executing code 2024-02-18 13:04:20 +01:00
Gwendal Roué eebf8b1c20 waitForExpectations must be isolated to MainActor 2024-02-18 13:04:20 +01:00
Gwendal Roué 5fc36a0a1b Fix concurrency warning in the definition of a class that conforms to DatabaseValueConvertible 2024-02-18 13:04:20 +01:00
Gwendal Roué 71041b5085 Fix concurrency warnings in DatabaseAggregateTests 2024-02-18 12:41:35 +01:00
Gwendal Roué 5f95840c88 TODO 2024-02-18 12:41:34 +01:00
Gwendal Roué bb22d9eced Mute compiler warning until language is fixed
The wrong warning is "Converting non-sendable function value to '@Sendable (Database) throws -> Void' may introduce data races"

https://github.com/apple/swift/issues/71541
2024-02-18 12:41:34 +01:00
Gwendal Roué 22a50a027a Tests wait for expections on the MainActor 2024-02-18 12:41:34 +01:00
Gwendal Roué aadb76199b Sendable annotations for record coding strategies 2024-02-18 12:41:34 +01:00
Gwendal Roué 86ff859be5 Fix test compilation errors - MUTEEEEEX 2024-02-18 12:41:34 +01:00
Gwendal Roué 974fa54e1d [BREAKING] Remove AsyncValueObservation does not need any scheduler 2024-02-18 12:41:34 +01:00
Gwendal Roué 6ff88c6310 Tests need a Mutex in order to avoid sendability warnings 2024-02-18 12:41:34 +01:00
Gwendal Roué 0e1220b048 Remove useless test 2024-02-18 12:41:34 +01:00
Gwendal Roué fb0866c6fa Rename LockedBox to Mutex
Maybe we'll be able to plug in the standard one eventually: https://forums.swift.org/t/pitch-synchronous-mutual-exclusion-lock/69889
2024-02-18 12:41:34 +01:00
Gwendal Roué a00825c882 PersistenceConflictPolicy is Sendable 2024-02-18 12:41:34 +01:00
Gwendal Roué fc7ca13c04 Sendable annotations for DAO 2024-02-16 17:43:41 +01:00
Gwendal Roué 1af8a2256f Sendable annotations for associations 2024-02-16 17:43:41 +01:00
Gwendal Roué c76215ba70 Sendable annotations for query interface requests 2024-02-16 08:34:21 +01:00
Gwendal Roué ee444c1468 Sendable annotations for DatabaseDateComponents 2024-02-16 08:34:21 +01:00
Gwendal Roué 3ffaa1929d [BREAKING] NSData and NSString are no longer DatabaseValueConvertible 2024-02-16 08:34:21 +01:00
Gwendal Roué 705c95ee92 SQLExpressible, SQLOrderingTerm and SQLSelectable are Sendable 2024-02-16 08:34:21 +01:00
Gwendal Roué 57382f5d8c Sendable annotations for DatabaseMigrator 2024-02-16 08:34:21 +01:00
Gwendal Roué 7d379409f1 Sendable annotations for DatabaseRegionObservation 2024-02-16 08:34:21 +01:00
Gwendal Roué 1fe410de69 Sendable annotations for ValueObservation 2024-02-16 08:34:21 +01:00
Gwendal Roué 133cc2e6e9 Sendable annotations for ValueObservationScheduler 2024-02-11 16:56:21 +01:00
Gwendal Roué 81746c75ad Sendable annotations in DatabaseReader and DatabaseWriter
Also, we make sure to always resume UnsafeContinuation with Sendable values. See https://forums.swift.org/t/advice-regarding-sendable-constraints-on-generic-async-apis/69969/3
2024-02-11 16:56:21 +01:00
Gwendal Roué 896d14ca56 Sendable annotations for OnDemandFuture 2024-02-11 16:56:21 +01:00
Gwendal Roué 9a75127b15 Pool is Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué 7a4b8d7aa5 ReadWriteBox is Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué e26cceb4a9 _ValueReducer inputs are Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué 8271fd4f5a TODO 2024-02-11 16:56:21 +01:00
Gwendal Roué 75f4ce75b0 DatabaseCancellable is Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué 491ceca46c The default inflections are nonisolated 2024-02-11 16:56:21 +01:00
Gwendal Roué f48f0c132d Sendable annotations 2024-02-11 16:56:21 +01:00
Gwendal Roué 62e8769be6 DatabaseCollation is Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué 97719932f5 DatabaseFunction is Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué 022487d360 Sendable annotations 2024-02-11 16:56:21 +01:00
Gwendal Roué 9b93ef7907 DispatchSpecificKey are nonisolated 2024-02-11 16:56:21 +01:00
Gwendal Roué a3b5001fed Sendable annotations 2024-02-11 16:56:21 +01:00
Gwendal Roué e0cfb97796 The global SQLite error log is nonisolated 2024-02-11 16:56:21 +01:00
Gwendal Roué b0a94d16df Configuration is Sendable 2024-02-11 16:56:21 +01:00
Gwendal Roué b593135401 SWIFT_STRICT_CONCURRENCY = complete 2024-02-11 16:56:21 +01:00
Gwendal Roué a455120135 [BREAKING] insertAndFetch, saveAndFetch, and updateAndFetch no longer return optionals.
Those optionals were just an annoyance. Now, nil results are replaced with `RecordError.recordNotFound`. Such an error is only expected with the IGNORE conflict policy.
2024-02-11 16:56:21 +01:00
Gwendal Roué 1811a9b64b Remove ill-advised TODO
I wouldn't want to keep an invalid pointer. And C functions accept the optional just fine.
2024-02-11 14:05:35 +01:00
Gwendal Roué 4e1f8962a4 Remove ill-advised TODO
This would force users to force-unwrap their custom `ColumnType(rawValue: "WHATEVER")!`
2024-02-11 14:05:35 +01:00
Gwendal Roué 44cd5ad749 [BREAKING] Bump requirements: Swift 5.10, Xcode 15.3, iOS 12, tvOS 12 2024-02-11 14:05:35 +01:00
166 changed files with 2119 additions and 1847 deletions

No files matched your search

@@ -444,6 +444,7 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
};
name = Debug;
};
@@ -498,6 +499,7 @@
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -444,6 +444,7 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
};
name = Debug;
};
@@ -498,6 +499,7 @@
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -759,6 +759,7 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_VERSION = 5.0;
WATCHOS_DEPLOYMENT_TARGET = 8.0;
};
@@ -814,6 +815,7 @@
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
WATCHOS_DEPLOYMENT_TARGET = 8.0;
+1 -1
View File
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.swift_versions = ['5.7']
s.swift_versions = ['5.10']
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.13'
s.watchos.deployment_target = '4.0'
+10 -20
View File
@@ -27,7 +27,6 @@
5605F1631C672E4000235C62 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; };
5605F1651C672E4000235C62 /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1501C672E4000235C62 /* NSNull.swift */; };
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; };
5605F1691C672E4000235C62 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; };
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
@@ -161,7 +160,6 @@
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; };
5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
5657AB0F1D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4871EA8D94E004A4992 /* Utils.swift */; };
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; };
@@ -185,7 +183,7 @@
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
566BE71E2342542F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* Mutex.swift */; };
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
@@ -283,6 +281,7 @@
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA65C2B79246300B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA65B2B79246300B3A7F8 /* Mutex.swift */; };
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
@@ -309,11 +308,9 @@
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; };
56D496591D81304E008276D7 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */; };
56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; };
56D4965C1D81304E008276D7 /* FoundationNSNullTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB311D108BA9006283EF /* FoundationNSNullTests.swift */; };
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB321D108BA9006283EF /* FoundationNSNumberTests.swift */; };
56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */; };
56D4965F1D81304E008276D7 /* FoundationNSURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */; };
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */; };
56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; };
@@ -451,7 +448,6 @@
5605F14F1C672E4000235C62 /* Date.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Date.swift; sourceTree = "<group>"; };
5605F1501C672E4000235C62 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
5605F1511C672E4000235C62 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
@@ -590,13 +586,10 @@
5656A81D2295B12F001FF3FF /* SQLAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLAssociation.swift; sourceTree = "<group>"; };
5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+Association.swift"; sourceTree = "<group>"; };
5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = "<group>"; };
5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = "<group>"; };
5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDataTests.swift; sourceTree = "<group>"; };
5657AB311D108BA9006283EF /* FoundationNSNullTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSNullTests.swift; sourceTree = "<group>"; };
5657AB321D108BA9006283EF /* FoundationNSNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSNumberTests.swift; sourceTree = "<group>"; };
5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSStringTests.swift; sourceTree = "<group>"; };
5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSURLTests.swift; sourceTree = "<group>"; };
5657AB351D108BA9006283EF /* FoundationURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationURLTests.swift; sourceTree = "<group>"; };
5659F4871EA8D94E004A4992 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
@@ -627,7 +620,7 @@
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
566BE7172342542F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
566DDE0C288D763C0000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = "<group>"; };
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
@@ -782,6 +775,7 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA65B2B79246300B3A7F8 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
@@ -925,10 +919,8 @@
5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */,
5605F14F1C672E4000235C62 /* Date.swift */,
56894F94260657D600268F4D /* Decimal.swift */,
5657AAB81D107001006283EF /* NSData.swift */,
5605F1501C672E4000235C62 /* NSNull.swift */,
5605F1511C672E4000235C62 /* NSNumber.swift */,
5605F1521C672E4000235C62 /* NSString.swift */,
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */,
5657AB0E1D10899D006283EF /* URL.swift */,
56A8C22F1D1914540096E9D4 /* UUID.swift */,
@@ -1008,6 +1000,7 @@
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56BCA65B2B79246300B3A7F8 /* Mutex.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567B5BDA2AD3281B00629622 /* Dump */,
@@ -1316,7 +1309,7 @@
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */,
563EF4492161F179007DAACD /* Inflections.swift */,
569BBA482291707D00478429 /* Inflections+English.swift */,
566BE7172342542F00A8254B /* LockedBox.swift */,
566BE7172342542F00A8254B /* Mutex.swift */,
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */,
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
@@ -1674,12 +1667,10 @@
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */,
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */,
56894F742606576600268F4D /* FoundationDecimalTests.swift */,
5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */,
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */,
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */,
5657AB311D108BA9006283EF /* FoundationNSNullTests.swift */,
5657AB321D108BA9006283EF /* FoundationNSNumberTests.swift */,
5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */,
5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */,
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */,
5657AB351D108BA9006283EF /* FoundationURLTests.swift */,
@@ -1981,7 +1972,6 @@
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */,
5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */,
5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */,
@@ -2083,7 +2073,6 @@
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
563B5336267E2F90009549B5 /* TableTests.swift in Sources */,
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
@@ -2097,6 +2086,7 @@
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
56BCA65C2B79246300B3A7F8 /* Mutex.swift in Sources */,
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
@@ -2226,7 +2216,6 @@
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */,
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
@@ -2261,7 +2250,7 @@
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
566BE71E2342542F00A8254B /* Mutex.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
@@ -2310,7 +2299,6 @@
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */,
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
@@ -2444,6 +2432,7 @@
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
@@ -2495,6 +2484,7 @@
MTL_ENABLE_DEBUG_INFO = NO;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
+8 -7
View File
@@ -1,7 +1,8 @@
import Dispatch
import Foundation
public struct Configuration {
// TODO: remove @unchecked when DispatchQoS is Sendable
public struct Configuration: @unchecked Sendable {
// MARK: - Misc options
@@ -186,7 +187,7 @@ public struct Configuration {
// MARK: - Managing SQLite Connections
private var setups: [(Database) throws -> Void] = []
private var setups: [@Sendable (Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -223,7 +224,7 @@ public struct Configuration {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
setups.append(setup)
}
@@ -294,7 +295,7 @@ public struct Configuration {
/// connection is opened.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public enum JournalModeConfiguration {
public enum JournalModeConfiguration: Sendable {
/// The default setup has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool``
/// configure the database for the WAL mode (just like the
@@ -445,9 +446,9 @@ public struct Configuration {
/// through a `SerializedDatabase`.
var threadingMode = Database.ThreadingMode.default
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
var SQLiteConnectionDidOpen: (@Sendable () -> Void)?
var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (@Sendable () -> Void)?
var SQLiteOpenFlags: CInt {
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
if sqlite3_libversion_number() >= 3037000 {
+4 -4
View File
@@ -997,7 +997,7 @@ extension Database {
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord {
public struct ColumnInfo: FetchableRecord, Sendable {
let cid: Int
let hidden: Int?
@@ -1085,7 +1085,7 @@ public struct ColumnInfo: FetchableRecord {
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
public struct IndexInfo {
/// The origin of an index.
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
public var rawValue: String
public init(rawValue: String) {
@@ -1307,8 +1307,8 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo {
private enum Impl {
public struct PrimaryKeyInfo: Sendable {
private enum Impl: Sendable {
/// The hidden rowID.
case hiddenRowID
+1 -1
View File
@@ -533,7 +533,7 @@ struct StatementCache {
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
#else
let statement: Statement
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
if #available(macOS 10.14, watchOS 5, *) { // SQLite 3.20+
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
} else {
statement = try db.makeStatement(sql: sql)
+16 -19
View File
@@ -122,8 +122,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - SQLite C API
// TODO: make it non optional, since one can't get a `Database` instance
// after `close()`.
/// The raw SQLite connection, suitable for the SQLite C API.
///
/// The result is nil after the database has been successfully closed with
@@ -135,7 +133,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The error logging function.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
public static var logError: LogErrorFunction? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -283,7 +281,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
var isInsideTransactionBlock = false
/// Support for `checkForSuspensionViolation(from:)`
@LockedBox var isSuspended = false
@Mutex var isSuspended = false
/// Support for `checkForSuspensionViolation(from:)`
/// This cache is never cleared: we assume journal mode never changes.
@@ -1114,7 +1112,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// Suspension ends with `resume()`.
func suspend() {
$isSuspended.update { isSuspended in
$isSuspended.withLock { isSuspended in
if isSuspended {
return
}
@@ -1171,7 +1169,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
func checkForSuspensionViolation(from statement: Statement) throws {
try $isSuspended.read { isSuspended in
try $isSuspended.withLock { isSuspended in
guard isSuspended else {
return
}
@@ -1808,7 +1806,7 @@ extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
/// to access the database while it is locked by another connection.
@@ -1836,7 +1834,7 @@ extension Database {
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
public enum BusyMode {
public enum BusyMode: Sendable {
/// The `SQLITE_BUSY` error is immediately returned to the connection
/// that tries to access the locked database.
case immediateError
@@ -1854,7 +1852,7 @@ extension Database {
/// The available checkpoint modes.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
public enum CheckpointMode: CInt {
public enum CheckpointMode: CInt, Sendable {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
case passive = 0
@@ -1873,7 +1871,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable, Sendable {
public let rawValue: String
/// Creates a collation name.
@@ -1910,11 +1908,10 @@ extension Database {
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct ColumnType: RawRepresentable, Hashable {
public struct ColumnType: RawRepresentable, Hashable, Sendable {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
// TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank).
/// Creates an SQL column type.
public init(rawValue: String) {
self.rawValue = rawValue
@@ -1962,7 +1959,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String {
public enum ConflictResolution: String, Sendable {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
@@ -1982,7 +1979,7 @@ extension Database {
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String {
public enum ForeignKeyAction: String, Sendable {
/// The `CASCADE` foreign key action.
case cascade = "CASCADE"
@@ -1997,7 +1994,7 @@ extension Database {
}
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void
/// An option for the SQLite tracing feature.
///
@@ -2005,7 +2002,7 @@ extension Database {
/// ``Database/trace(options:_:)`` method.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
public struct TracingOptions: OptionSet {
public struct TracingOptions: OptionSet, Sendable {
/// The raw trace event code.
public let rawValue: CInt
@@ -2138,7 +2135,7 @@ extension Database {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion {
public enum TransactionCompletion: Sendable {
case commit
case rollback
}
@@ -2146,7 +2143,7 @@ extension Database {
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String {
public enum TransactionKind: String, Sendable {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
@@ -2162,7 +2159,7 @@ extension Database {
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
/// supported, since all <doc:DatabaseConnections> access SQLite connections
/// through a `SerializedDatabase`.
enum ThreadingMode {
enum ThreadingMode: Sendable {
case `default`
case multiThread
case serialized
+3 -3
View File
@@ -20,10 +20,10 @@ import Foundation
/// - ``localizedCompare``
/// - ``localizedStandardCompare``
/// - ``unicodeCompare``
public final class DatabaseCollation {
public final class DatabaseCollation: Sendable {
/// The name of the collation.
public let name: String
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -40,7 +40,7 @@ public final class DatabaseCollation {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
+4
View File
@@ -406,6 +406,10 @@ extension DatabaseError {
static func connectionIsClosed() -> Self {
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
}
static func snapshotIsLost() -> Self {
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
+6 -6
View File
@@ -20,7 +20,7 @@
/// - ``localizedUppercase``
/// - ``lowercase``
/// - ``uppercase``
public final class DatabaseFunction: Hashable {
public final class DatabaseFunction: Hashable, Sendable {
// SQLite identifies functions by (name + argument count)
private struct Identity: Hashable {
let name: String
@@ -73,11 +73,11 @@ public final class DatabaseFunction: Hashable {
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function{ (argc, argv) in
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
@@ -265,12 +265,12 @@ public final class DatabaseFunction: Hashable {
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind {
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(() -> any DatabaseAggregate)
case aggregate(@Sendable () -> any DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
+25 -30
View File
@@ -11,7 +11,7 @@ public final class DatabasePool {
/// It is constant, until close() sets it to nil.
private var readerPool: Pool<SerializedDatabase>?
@LockedBox var databaseSnapshotCount = 0
@Mutex var databaseSnapshotCount = 0
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
@@ -62,17 +62,15 @@ public final class DatabasePool {
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [readerConfiguration] index in
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
purpose: "reader.\(index)")
})
// Set up journal mode unless readonly
@@ -357,7 +355,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -401,7 +399,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -446,25 +444,22 @@ extension DatabasePool: DatabaseReader {
}
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T, Error>? = nil
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
let builder = UnsafeDatabaseFutureBuilder<T>()
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
let result = dbResult.flatMap { db in
Result {
try value(db)
}
}
builder.setResultAndReleaseFuture(result)
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
return builder.makeFuture()
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncConcurrentRead(value)
}
@@ -505,7 +500,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -644,8 +639,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
guard let readerPool else {
@@ -665,7 +659,9 @@ extension DatabasePool: DatabaseReader {
///
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
func asyncWALSnapshotTransaction(
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -691,7 +687,7 @@ extension DatabasePool: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if configuration.readonly {
@@ -722,7 +718,7 @@ extension DatabasePool: DatabaseReader {
private func _addConcurrent<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
@@ -756,7 +752,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -809,7 +805,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
@@ -870,8 +866,7 @@ extension DatabasePool {
purpose: "snapshot.\($databaseSnapshotCount.increment())")
}
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// Creates a database snapshot that allows concurrent accesses to an
/// unchanging database content, as it exists at the moment the snapshot
/// is created.
+7 -7
View File
@@ -233,7 +233,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -258,7 +258,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -266,7 +266,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
public func concurrentRead<T>(_ value: (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(Result {
@@ -279,7 +279,7 @@ extension DatabaseQueue: DatabaseReader {
})
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -309,7 +309,7 @@ extension DatabaseQueue: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if configuration.readonly {
@@ -379,7 +379,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -425,7 +425,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+23 -23
View File
@@ -22,14 +22,14 @@ import Dispatch
/// ### Reading from the Database
///
/// - ``read(_:)-3806d``
/// - ``read(_:)-4w6gy``
/// - ``read(_:)-7a20l``
/// - ``readPublisher(receiveOn:value:)``
/// - ``asyncRead(_:)``
///
/// ### Unsafe Methods
///
/// - ``unsafeRead(_:)-5i7tf``
/// - ``unsafeRead(_:)-11mk0``
/// - ``unsafeRead(_:)-3arn0``
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
@@ -213,7 +213,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -284,7 +284,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -342,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
}
@@ -458,7 +458,7 @@ extension DatabaseReader {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func read<T: Sendable>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
@@ -504,7 +504,7 @@ extension DatabaseReader {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func unsafeRead<T: Sendable>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
@@ -549,18 +549,18 @@ extension DatabaseReader {
/// - parameter scheduler: A Combine Scheduler.
/// - parameter value: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func readPublisher<Output>(
public func readPublisher<Output: Sendable>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
value: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
// We don't want users to process emitted values on a
// database dispatch queue.
.receiveValues(on: scheduler)
.eraseToReadPublisher()
}
@@ -601,7 +601,7 @@ extension DatabaseReader {
func _addReadOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if scheduler.immediateInitialValue() {
@@ -619,16 +619,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
var isCancelled = false
let cancellable = AnyDatabaseCancellable { }
asyncRead { dbResult in
guard !isCancelled else { return }
if cancellable.isCancelled { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
guard !isCancelled else { return }
if cancellable.isCancelled { return }
do {
try onChange(result.get())
} catch {
@@ -636,7 +636,7 @@ extension DatabaseReader {
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
return cancellable
}
}
}
@@ -677,7 +677,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -686,7 +686,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -697,7 +697,7 @@ extension AnyDatabaseReader: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
base._add(
@@ -757,7 +757,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncRead(value)
}
}
+6 -5
View File
@@ -40,7 +40,7 @@
///
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion {
public struct DatabaseRegion: Sendable {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
@@ -416,7 +416,7 @@ private struct TableRegion: Equatable {
/// ### Supporting Types
///
/// - ``AnyDatabaseRegionConvertible``
public protocol DatabaseRegionConvertible {
public protocol DatabaseRegionConvertible: Sendable {
/// Returns a database region.
///
/// - parameter db: A database connection.
@@ -437,14 +437,15 @@ extension DatabaseRegion: DatabaseRegionConvertible {
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: (Database) throws -> DatabaseRegion
let _region: @Sendable (Database) throws -> DatabaseRegion
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
_region = region
}
public init(_ region: some DatabaseRegionConvertible) {
_region = region.databaseRegion
// https://github.com/apple/swift/issues/71541
_region = { try region.databaseRegion($0) }
}
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
+13 -9
View File
@@ -43,7 +43,9 @@ extension DatabaseRegionObservation {
extension DatabaseRegionObservation {
/// The state of a started DatabaseRegionObservation
private enum ObservationState {
private enum ObservationState: @unchecked Sendable {
// @unchecked because we don't use DatabaseRegionObserver outside of
// the writer dispatch queue.
case cancelled
case pending
case started(DatabaseRegionObserver)
@@ -85,20 +87,20 @@ extension DatabaseRegionObservation {
/// - returns: A DatabaseCancellable that can stop the observation.
public func start(
in writer: some DatabaseWriter,
onError: @escaping (Error) -> Void,
onChange: @escaping (Database) -> Void)
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Database) -> Void)
-> AnyDatabaseCancellable
{
@LockedBox var state = ObservationState.pending
let state = Mutex(ObservationState.pending)
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
writer.unsafeReentrantWrite { db in
do {
let region = try observedRegion(db).observableRegion(db)
$state.update {
state.withLock {
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = state {
if case .cancelled = state.wrappedValue {
return
}
onChange($0)
@@ -122,7 +124,7 @@ extension DatabaseRegionObservation {
// Deallocates the transaction observer. This makes sure that the
// `onChange` callback will never be called again, because the
// observation was started with the `.observerLifetime` extent.
state = .cancelled
state.wrappedValue = .cancelled
}
}
}
@@ -152,7 +154,7 @@ private class DatabaseRegionObserver: TransactionObserver {
let onChange: (Database) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
self.region = region
self.onChange = onChange
}
@@ -212,9 +214,11 @@ extension DatabasePublishers {
}
}
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
where Downstream.Failure == Error, Downstream.Input == Database
{
// @unchecked because `cancellable` and `state` are protected by `lock`.
private struct WaitingForDemand {
let downstream: Downstream
let writer: any DatabaseWriter
+3 -3
View File
@@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
_addReadOnly(
+11 -15
View File
@@ -1,5 +1,4 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
///
@@ -122,6 +121,7 @@ public final class DatabaseSnapshotPool {
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
// Acquire and hold WAL snapshot
@@ -130,7 +130,7 @@ public final class DatabaseSnapshotPool {
}
var holderConfig = Configuration()
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
@@ -150,20 +150,18 @@ public final class DatabaseSnapshotPool {
}
self.configuration = configuration
self.path = db.path
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: db.path,
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -211,17 +209,15 @@ public final class DatabaseSnapshotPool {
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -292,7 +288,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -330,7 +326,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
public func _add<Reducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable where Reducer: ValueReducer
{
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
+53 -29
View File
@@ -22,18 +22,18 @@ import Dispatch
/// ### Writing into the Database
///
/// - ``write(_:)-76inz``
/// - ``write(_:)-88g7e``
/// - ``write(_:)-3db50``
/// - ``writePublisher(receiveOn:updates:)``
/// - ``writePublisher(receiveOn:updates:thenRead:)``
/// - ``writeWithoutTransaction(_:)-4qh1w``
/// - ``writeWithoutTransaction(_:)-tckw``
/// - ``writeWithoutTransaction(_:)-5h4vs``
/// - ``asyncWrite(_:completion:)``
/// - ``asyncWriteWithoutTransaction(_:)``
///
/// ### Exclusive Access to the Database
///
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
/// - ``barrierWriteWithoutTransaction(_:)-7u4xw``
/// - ``barrierWriteWithoutTransaction(_:)-1ctl7``
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
///
/// ### Reading from the Latest Committed Database State
@@ -181,7 +181,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
@@ -340,7 +340,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
}
extension DatabaseWriter {
@@ -426,8 +426,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -557,7 +557,7 @@ extension DatabaseWriter {
func _addWriteOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
@@ -608,7 +608,7 @@ extension DatabaseWriter {
/// would happen while establishing the database access or committing
/// the transaction.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func write<T: Sendable>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
@@ -646,7 +646,9 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
@@ -698,8 +700,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T)
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
@@ -801,9 +803,9 @@ extension DatabaseWriter {
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<Output>(
public func writePublisher<Output: Sendable>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping (Database) throws -> Output)
updates: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -868,10 +870,10 @@ extension DatabaseWriter {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
where S: Scheduler, T: Sendable, Output: Sendable
{
OnDemandFuture { fulfill in
self.asyncWriteWithoutTransaction { db in
@@ -885,7 +887,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
self.spawnConcurrentRead { [updatesValue] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -941,11 +943,11 @@ extension Publisher where Failure == Error {
///
/// let count: Int = try futureCount.wait()
/// ```
public class DatabaseFuture<Value> {
public class DatabaseFuture<Value: Sendable> {
private var consumed = false
private let _wait: () throws -> Value
init(_ wait: @escaping () throws -> Value) {
init(_ wait: @escaping @Sendable () throws -> Value) {
_wait = wait
}
@@ -967,6 +969,28 @@ public class DatabaseFuture<Value> {
}
}
/// A helper class that builds a DatabaseFuture without compiler errors
/// regarding concurrency.
final class UnsafeDatabaseFutureBuilder<T: Sendable>: @unchecked Sendable {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<T, Error>? = nil
/// - precondition: MUST be called once.
func setResultAndReleaseFuture(_ result: Result<T, Error>) {
self.result = result
semaphore.signal()
}
/// - precondition: MUST be called once.
func makeFuture() -> DatabaseFuture<T> {
DatabaseFuture { [self] in
// Block the future until results are fetched
_ = semaphore.wait(timeout: .distantFuture)
return try result!.get()
}
}
}
/// A type-erased database writer.
///
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
@@ -1003,7 +1027,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -1012,7 +1036,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -1023,7 +1047,7 @@ extension AnyDatabaseWriter: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
base._add(
@@ -1044,11 +1068,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -1056,11 +1080,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
+6 -4
View File
@@ -166,7 +166,9 @@ extension FetchRequest {
///
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
public func adapted(
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
}
@@ -176,11 +178,11 @@ extension FetchRequest {
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: (Database) throws -> any RowAdapter
let adapter: @Sendable (Database) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
@@ -269,7 +271,7 @@ extension AnyFetchRequest: FetchRequest {
}
// Class-based type erasure, so that we preserve full type information.
private class FetchRequestEraser: FetchRequest {
private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
typealias RowDecoder = Void
var sqlSubquery: SQLSubquery {
+3 -3
View File
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
/// - ``RenameColumnAdapter``
/// - ``ScopeAdapter``
/// - ``SuffixRowAdapter``
public protocol RowAdapter {
public protocol RowAdapter: Sendable {
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
/// print(Array(adaptedRow.columnNames))
/// ```
public struct RenameColumnAdapter: RowAdapter {
let transform: (String) -> String
let transform: @Sendable (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping (String) -> String) {
public init(_ transform: @escaping @Sendable (String) -> String) {
self.transform = transform
}
+2 -1
View File
@@ -22,7 +22,8 @@ import Dispatch
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
// TODO: remove nonisolated(unsafe) when DispatchSpecificKey is Sendable.
nonisolated(unsafe) private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
+1 -1
View File
@@ -223,7 +223,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping (Database) -> Void) {
func async(_ block: @escaping @Sendable (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+1 -1
View File
@@ -137,7 +137,7 @@ public final class Statement {
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
#else
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
if #available(macOS 10.14, watchOS 5, *) { // SQLite 3.20+
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
@@ -4,7 +4,7 @@ import Foundation
public struct DatabaseDateComponents {
/// The SQLite formats for date components.
public enum Format: String {
public enum Format: String, Sendable {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
-27
View File
@@ -1,27 +0,0 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
extension NSData: DatabaseValueConvertible {
/// Returns a BLOB database value.
public var databaseValue: DatabaseValue {
(self as Data).databaseValue
}
/// Returns a `NSData` from the specified database value.
///
/// If the database value contains a data blob, returns it.
///
/// If the database value contains a string, returns this string converted
/// to UTF8 data.
///
/// Otherwise, returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let data = Data.fromDatabaseValue(dbValue) else {
return nil
}
return cast(data)
}
}
#endif
@@ -1,27 +0,0 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
extension NSString: DatabaseValueConvertible {
/// Returns a TEXT database value.
public var databaseValue: DatabaseValue {
(self as String).databaseValue
}
/// Returns a `NSString` from the specified database value.
///
/// If the database value contains a string, returns it.
///
/// If the database value contains a data blob, parses this data as an
/// UTF8 string.
///
/// Otherwise, returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(dbValue) else {
return nil
}
return self.init(string: string)
}
}
#endif
+1 -1
View File
@@ -8,7 +8,7 @@ extension NSUUID: DatabaseValueConvertible {
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
getBytes(buffer.baseAddress!)
return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
return Data(bytes: buffer.baseAddress!, count: 16).databaseValue
}
}
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock {
public protocol TransactionClock: Sendable {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: (Database) throws -> Date
let _now: @Sendable (Database) throws -> Date
public init(_ now: @escaping (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
self._now = now
}
+4 -3
View File
@@ -1,5 +1,4 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
@@ -21,7 +20,9 @@
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: Sendable {
final class WALSnapshot: @unchecked Sendable {
// Unchecked because of `sqliteSnapshot`.
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
+57 -26
View File
@@ -1,12 +1,30 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
class WALSnapshotTransaction {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
final class WALSnapshotTransaction: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected its mutex.
private struct DatabaseAccess {
let reader: SerializedDatabase
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
func commitAndRelease() {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
}
}
// TODO: consider using the serialized DispatchQueue of reader instead of a lock.
/// nil when closed
@Mutex private var databaseAccess: DatabaseAccess?
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -37,10 +55,11 @@ class WALSnapshotTransaction {
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping (_ isInsideTransaction: Bool) -> Void)
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
assert(reader.configuration.readonly)
let databaseAccess = DatabaseAccess(reader: reader, release: release)
do {
// Open a long-lived transaction, and enter snapshot isolation
@@ -49,44 +68,56 @@ class WALSnapshotTransaction {
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
return try WALSnapshot(db)
}
self.reader = reader
self.release = release
self.databaseAccess = databaseAccess
} catch {
// self is not initialized, so deinit will not run.
Self.commitAndRelease(reader: reader, release: release)
databaseAccess.commitAndRelease()
throw error
}
}
deinit {
Self.commitAndRelease(reader: reader, release: release)
close()
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
try reader.sync(value)
func read<T>(_ value: (Database) throws -> T) throws -> T {
try $databaseAccess.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
return try databaseAccess.reader.sync(value)
}
}
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping (Database) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
$databaseAccess.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
databaseAccess.reader.async { db in
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
// At least check if self was closed:
if self.databaseAccess == nil {
value(.failure(DatabaseError.snapshotIsLost()))
}
value(.success(db))
}
}
}
private static func commitAndRelease(
reader: SerializedDatabase,
release: (_ isInsideTransaction: Bool) -> Void)
{
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
func close() {
$databaseAccess.withLock { databaseAccess in
databaseAccess?.commitAndRelease()
databaseAccess = nil
}
release(isInsideTransaction)
}
}
#endif
+1 -1
View File
@@ -99,7 +99,7 @@ try dbQueue.write { db in
}
```
See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``.
See ``DatabaseReader/read(_:)-7a20l`` and ``DatabaseWriter/write(_:)-3db50``.
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
@@ -260,7 +260,7 @@ When needed, you can help GRDB optimize observations and reduce database content
- ``publisher(in:scheduling:)``
- ``start(in:scheduling:onError:onChange:)``
- ``values(in:scheduling:bufferingPolicy:)``
- ``values(in:bufferingPolicy:)``
- ``DatabaseCancellable``
- ``ValueObservationScheduler``
+1 -1
View File
@@ -20,7 +20,7 @@
/// - ``simple``
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
/// - ``FTS3/Diacritics``
public struct FTS3TokenizerDescriptor {
public struct FTS3TokenizerDescriptor: Sendable {
let name: String
let arguments: [String]
+1 -1
View File
@@ -121,7 +121,7 @@ public struct FTS5 {
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
if #available(macOS 10.14, watchOS 5, *) { // SQLite 3.20+
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
return api_v1(db)
+1 -1
View File
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
/// The reason why FTS5 is requesting tokenization.
///
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5Tokenization: OptionSet {
public struct FTS5Tokenization: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -4,7 +4,7 @@ import Foundation
/// Flags that tell SQLite how to register a token.
///
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5TokenFlags: OptionSet {
public struct FTS5TokenFlags: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+3 -3
View File
@@ -40,7 +40,7 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks {
/// The migration runs with disabled foreign keys.
@@ -207,7 +207,7 @@ public struct DatabaseMigrator {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping (Database) throws -> Void)
migrate: @escaping @Sendable (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -264,7 +264,7 @@ public struct DatabaseMigrator {
/// from succeeding.
public func asyncMigrate(
_ writer: some DatabaseWriter,
completion: @escaping (Result<Database, Error>) -> Void)
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
+2 -2
View File
@@ -1,5 +1,5 @@
/// An internal struct that defines a migration.
struct Migration {
struct Migration: Sendable {
enum ForeignKeyChecks {
case deferred
case immediate
@@ -8,7 +8,7 @@ struct Migration {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: (Database) throws -> Void
let migrate: @Sendable (Database) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
+1 -1
View File
@@ -80,7 +80,7 @@
/// using: Book.translatorForeignKey)
/// }
/// ```
public struct ForeignKey: Equatable {
public struct ForeignKey: Equatable, Sendable {
var originColumns: [String]
var destinationColumns: [String]?
@@ -33,7 +33,7 @@ import Foundation
///
/// - ``ForeignKey``
/// - ``Inflections``
public protocol Association: DerivableRequest {
public protocol Association: DerivableRequest, Sendable {
// OriginRowDecoder and RowDecoder inherited from DerivableRequest provide
// type safety:
//
@@ -173,7 +173,9 @@ extension Association {
// SelectionRequest conformance
extension Association {
public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.selectWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -181,7 +183,9 @@ extension Association {
}
}
public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.annotatedWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -192,7 +196,9 @@ extension Association {
// FilteredRequest conformance
extension Association {
public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.filterWhenConnected { db in
try predicate(db).sqlExpression
@@ -203,7 +209,9 @@ extension Association {
// OrderedRequest conformance
extension Association {
public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self {
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
) -> Self {
withDestinationRelation { relation in
relation = relation.orderWhenConnected { db in
try orderings(db).map(\.sqlOrdering)
@@ -239,7 +247,9 @@ extension Association {
// AggregatingRequest conformance
extension Association {
public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self {
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]
) -> Self {
withDestinationRelation { relation in
relation = relation.groupWhenConnected { db in
try expressions(db).map(\.sqlExpression)
@@ -247,7 +257,9 @@ extension Association {
}
}
public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.havingWhenConnected { db in
try predicate(db).sqlExpression
@@ -385,7 +385,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -421,7 +421,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Destination.Type,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
@@ -458,7 +458,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Table<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -117,7 +117,7 @@ extension QueryInterfaceRequest: FetchRequest {
extension QueryInterfaceRequest: SelectionRequest {
public func selectWhenConnected(
_ selection: @escaping (Database) throws -> [any SQLSelectable])
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -281,7 +281,7 @@ extension QueryInterfaceRequest: SelectionRequest {
}
public func annotatedWhenConnected(
with selection: @escaping (Database) throws -> [any SQLSelectable])
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -294,7 +294,7 @@ extension QueryInterfaceRequest: SelectionRequest {
extension QueryInterfaceRequest: FilteredRequest {
public func filterWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -307,7 +307,7 @@ extension QueryInterfaceRequest: FilteredRequest {
extension QueryInterfaceRequest: OrderedRequest {
public func orderWhenConnected(
_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm])
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
-> Self
{
with {
@@ -354,7 +354,7 @@ extension QueryInterfaceRequest: OrderedRequest {
extension QueryInterfaceRequest: AggregatingRequest {
public func groupWhenConnected(
_ expressions: @escaping (Database) throws -> [any SQLExpressible])
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
-> Self
{
with {
@@ -365,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
public func havingWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -58,7 +58,7 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
/// Appends result columns to the selected columns.
///
@@ -78,7 +78,7 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
}
extension SelectionRequest {
@@ -240,7 +240,7 @@ public protocol FilteredRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
}
extension FilteredRequest {
@@ -729,7 +729,7 @@ public protocol AggregatingRequest {
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self
/// Filters the aggregated groups with a boolean SQL expression.
///
@@ -753,7 +753,7 @@ public protocol AggregatingRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
}
extension AggregatingRequest {
@@ -934,7 +934,7 @@ public protocol OrderedRequest {
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self
/// Returns a request with reversed ordering.
///
@@ -21,9 +21,9 @@
///
/// Such late computations are backed by DatabasePromise. In our example,
/// see SQLRelation.filterPromise.
struct DatabasePromise<T> {
struct DatabasePromise<T: Sendable> {
/// Returns the resolved value.
let resolve: (Database) throws -> T
let resolve: @Sendable (Database) throws -> T
/// Creates a promise that resolves to a value.
init(value: T) {
@@ -31,12 +31,12 @@ struct DatabasePromise<T> {
}
/// Creates a promise from a closure.
init(_ resolve: @escaping (Database) throws -> T) {
init(_ resolve: @escaping @Sendable (Database) throws -> T) {
self.resolve = resolve
}
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
func map<U>(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(resolve(db))
}
+1 -1
View File
@@ -49,7 +49,7 @@
/// through: Pivot1.hasMany(Pivot2.self),
/// via: Pivot2.belongsTo(Destination.self)))
/// Origin.including(required: association)
public struct _SQLAssociation {
public struct _SQLAssociation: Sendable {
// All steps, from pivot to destination. Never empty.
private(set) var steps: [SQLAssociationStep]
var keyPath: [String] { steps.map(\.keyName) }
+3 -3
View File
@@ -57,7 +57,7 @@ public struct SQLExpression {
var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite
/// The private implementation of the public `SQLExpression`.
private enum Impl {
private enum Impl: Sendable {
/// A column.
///
/// id
@@ -315,7 +315,7 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
public struct AssociativeBinaryOperator: Hashable {
public struct AssociativeBinaryOperator: Hashable, Sendable {
/// The SQL operator
let sql: String
@@ -2109,7 +2109,7 @@ extension SQLExpression {
/// A type that can be used as an SQL expression.
///
/// Related SQLite documentation <https://www.sqlite.org/syntax/expr.html>
public protocol SQLExpressible {
public protocol SQLExpressible: Sendable {
/// Returns an SQL expression.
var sqlExpression: SQLExpression { get }
}
+1 -1
View File
@@ -138,7 +138,7 @@ extension SQLOrdering {
/// ### Supporting Type
///
/// - ``SQLOrdering``
public protocol SQLOrderingTerm {
public protocol SQLOrderingTerm: Sendable {
/// Returns an SQL ordering.
var sqlOrdering: SQLOrdering { get }
}
+11 -11
View File
@@ -90,7 +90,7 @@
/// // JOIN passport ON passport.citizenId = citizens.id
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...);
/// Country.including(all: Country.citizens)
struct SQLRelation {
struct SQLRelation: Sendable {
struct Child: Refinable {
enum Kind {
// Record.including(optional: association)
@@ -187,7 +187,7 @@ extension SQLRelation {
/// Convenience factory methods which selects all rows from a table.
static func all(
fromTable tableName: String,
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
@@ -691,7 +691,7 @@ struct SQLSource {
extension SQLRelation {
/// SQLRelation.Ordering provides the order clause to SQLRelation.
struct Ordering {
struct Ordering: Sendable {
private enum Element {
case terms(DatabasePromise<[SQLOrdering]>)
case ordering(SQLRelation.Ordering)
@@ -740,7 +740,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping (Database) throws -> [SQLOrdering]) {
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
self.init(
elements: [.terms(DatabasePromise(orderings))],
isReversed: false)
@@ -814,7 +814,7 @@ enum SQLAssociationCondition {
/// player[Column("id")] == bonus[Column("playerID")]
/// })
/// Player.with(bonus).joining(required: association)
case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
/// The condition that does not constrain the two associated tables
/// in any way.
+1 -1
View File
@@ -301,7 +301,7 @@ enum SQLCount {
///
/// - ``AllColumns``
/// - ``SQLSelection``
public protocol SQLSelectable {
public protocol SQLSelectable: Sendable {
/// Returns an SQL selection.
var sqlSelection: SQLSelection { get }
}
+1 -1
View File
@@ -1297,7 +1297,7 @@ extension Table {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -172,11 +172,12 @@ class StatementArgumentsSink {
private(set) var arguments: StatementArguments
private let rawSQL: Bool
// It's ok no make it nonisolated, because the instance is never modified.
/// A sink which turns all argument values into SQL literals.
///
/// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the
/// `WHERE name = 'O''Brien'` SQL.
static let literalValues = StatementArgumentsSink(rawSQL: true)
nonisolated(unsafe) static let literalValues = StatementArgumentsSink(rawSQL: true)
private init(rawSQL: Bool) {
self.arguments = []
@@ -515,6 +516,9 @@ extension TableAlias: Hashable {
}
}
// TODO: make it really Sendable.
extension TableAlias: @unchecked Sendable { }
extension [TableAlias] {
/// Resolve ambiguities in aliases' names.
fileprivate var resolvedNames: [TableAlias: String] {
@@ -547,7 +547,7 @@ struct SQLQueryGenerator: Refinable {
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
private struct SQLQualifiedRelation {
private struct SQLQualifiedRelation: Sendable {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
joins.reduce(into: [source.alias].compactMap { $0 }) {
@@ -681,7 +681,7 @@ extension Database {
}
/// View creation options
public struct ViewOptions: OptionSet {
public struct ViewOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -7,7 +7,7 @@ struct IndexDefinition {
}
/// Index creation options
public struct IndexOptions: OptionSet {
public struct IndexOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -1,5 +1,5 @@
/// Table creation options.
public struct TableOptions: OptionSet {
public struct TableOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -339,7 +339,7 @@ extension TableRecord {
/// - returns: An association to the common table expression.
public static func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<Self, Destination>
{
JoinAssociation(
@@ -559,7 +559,7 @@ extension TableRecord where Self: EncodableRecord {
/// ```
public func request<A: Association>(for association: A)
-> QueryInterfaceRequest<A.RowDecoder>
where A.OriginRowDecoder == Self
where A.OriginRowDecoder == Self, Self: Sendable
{
switch association._sqlAssociation.pivot.condition {
case .expression:
+10 -8
View File
@@ -89,7 +89,9 @@ public protocol EncodableRecord {
///
/// struct Player: PersistableRecord, Encodable {
/// // Customize the encoder name when encoding a database row
/// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
/// static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] {
/// [encoderName: "Database"]
/// }
///
/// func encode(to encoder: Encoder) throws {
/// // Print the encoder name
@@ -466,7 +468,7 @@ extension Row {
/// var jsonData: Data
/// }
/// ```
public enum DatabaseDataEncodingStrategy {
public enum DatabaseDataEncodingStrategy: Sendable {
/// Encodes `Data` columns as SQL blob.
case deferredToData
@@ -474,7 +476,7 @@ public enum DatabaseDataEncodingStrategy {
case text
/// Encodes `Data` column as the result of the user-provided function.
case custom((Data) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) -> DatabaseValue {
switch self {
@@ -508,7 +510,7 @@ public enum DatabaseDataEncodingStrategy {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy {
public enum DatabaseDateEncodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
@@ -538,7 +540,7 @@ public enum DatabaseDateEncodingStrategy {
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?)
private static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
@@ -585,7 +587,7 @@ public enum DatabaseDateEncodingStrategy {
/// var uuid: UUID
/// }
/// ```
public enum DatabaseUUIDEncodingStrategy {
public enum DatabaseUUIDEncodingStrategy: Sendable {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
@@ -626,7 +628,7 @@ public enum DatabaseUUIDEncodingStrategy {
/// var playerID: String
/// }
/// ```
public enum DatabaseColumnEncodingStrategy {
public enum DatabaseColumnEncodingStrategy: Sendable {
/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
@@ -634,7 +636,7 @@ public enum DatabaseColumnEncodingStrategy {
case convertToSnakeCase
/// A key encoding strategy defined by the closure you supply.
case custom((any CodingKey) -> String)
case custom(@Sendable (any CodingKey) -> String)
func column(forKey key: some CodingKey) -> String {
switch self {
+6 -6
View File
@@ -875,7 +875,7 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
/// var myData: Data
/// }
/// ```
public enum DatabaseDataDecodingStrategy {
public enum DatabaseDataDecodingStrategy: Sendable {
/// Decodes `Data` columns from SQL blobs and UTF8 text.
case deferredToData
@@ -884,7 +884,7 @@ public enum DatabaseDataDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Data?)
case custom(@Sendable (DatabaseValue) -> Data?)
}
// MARK: - DatabaseDateDecodingStrategy
@@ -901,7 +901,7 @@ public enum DatabaseDataDecodingStrategy {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy {
public enum DatabaseDateDecodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
@@ -942,7 +942,7 @@ public enum DatabaseDateDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Date?)
case custom(@Sendable (DatabaseValue) -> Date?)
}
// MARK: - DatabaseColumnDecodingStrategy
@@ -959,7 +959,7 @@ public enum DatabaseDateDecodingStrategy {
/// // Decoded from the player_id column
/// var playerID: Int
/// }
public enum DatabaseColumnDecodingStrategy {
public enum DatabaseColumnDecodingStrategy: Sendable {
/// A key decoding strategy that doesn’t change key names during decoding.
case useDefaultKeys
@@ -967,7 +967,7 @@ public enum DatabaseColumnDecodingStrategy {
case convertFromSnakeCase
/// A key decoding strategy defined by the closure you supply.
case custom((String) -> CodingKey)
case custom(@Sendable (String) -> CodingKey)
func key<K: CodingKey>(forColumn column: String) -> K? {
switch self {
@@ -266,16 +266,17 @@ final class DAO<Record: MutablePersistableRecord> {
// MARK: - InsertQuery
private struct InsertQuery: Hashable {
private struct InsertQuery: Hashable, Sendable {
let onConflict: Database.ConflictResolution
let tableName: String
let insertedColumns: [String]
}
extension InsertQuery {
@ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:]
private static let cache: ReadWriteBox<[InsertQuery: String]> = ReadWriteBox(wrappedValue: [:])
var sql: String {
if let sql = Self.sqlCache[self] {
if let sql = Self.cache.wrappedValue[self] {
return sql
}
let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")
@@ -294,7 +295,7 @@ extension InsertQuery {
VALUES (\(valuesSQL))
"""
}
Self.sqlCache[self] = sql
Self.cache.update { $0[self] = sql }
return sql
}
}
@@ -309,9 +310,10 @@ private struct UpdateQuery: Hashable {
}
extension UpdateQuery {
@ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:]
private static let cache: ReadWriteBox<[UpdateQuery: String]> = ReadWriteBox(wrappedValue: [:])
var sql: String {
if let sql = Self.sqlCache[self] {
if let sql = Self.cache.wrappedValue[self] {
return sql
}
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ")
@@ -331,7 +333,7 @@ extension UpdateQuery {
WHERE \(whereSQL)
"""
}
Self.sqlCache[self] = sql
Self.cache.update { $0[self] = sql }
return sql
}
}
@@ -91,7 +91,6 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -108,22 +107,22 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The inserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -161,11 +160,10 @@ extension MutablePersistableRecord {
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -174,19 +172,24 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
let record = self
return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
}
}
@@ -266,7 +269,6 @@ extension MutablePersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -283,23 +285,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The inserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -337,11 +339,10 @@ extension MutablePersistableRecord {
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -350,20 +351,25 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
let record = self
return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
}
}
+28 -20
View File
@@ -87,7 +87,6 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -107,22 +106,22 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The saved record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -135,26 +134,31 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
let record = self
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
})
return success!.saved
}
@@ -211,7 +215,6 @@ extension MutablePersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -231,23 +234,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The saved record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -260,27 +263,32 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
let record = self
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
})
return success!.saved
}
@@ -218,7 +218,6 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -226,23 +225,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The updated record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -251,25 +250,28 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -280,12 +282,13 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change, or
/// in case of a failed update due to the `IGNORE` conflict policy.
/// - returns: An updated record, or nil if the record has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch(
_ db: Database,
@@ -297,7 +300,6 @@ extension MutablePersistableRecord {
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -310,12 +312,13 @@ extension MutablePersistableRecord {
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
@@ -324,10 +327,16 @@ extension MutablePersistableRecord {
modify: (inout Self) throws -> Void)
throws -> T?
{
try updateChangesAndFetch(
let record = self
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: { try T.fetchOne($0) },
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
modify: modify)
}
@@ -482,7 +491,6 @@ extension MutablePersistableRecord {
fetch: fetch)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -495,7 +503,8 @@ extension MutablePersistableRecord {
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function.
/// - returns: The result of the `fetch` function, or nil if the record
/// has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
@@ -506,7 +515,7 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?,
fetch: (Statement) throws -> T,
modify: (inout Self) throws -> Void)
throws -> T?
{
@@ -519,7 +528,6 @@ extension MutablePersistableRecord {
fetch: fetch)
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -527,18 +535,19 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The updated record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
@@ -552,26 +561,29 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -582,12 +594,13 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change, or
/// in case of a failed update due to the `IGNORE` conflict policy.
/// - returns: An updated record, or nil if the record has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch(
@@ -600,7 +613,6 @@ extension MutablePersistableRecord {
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -613,12 +625,13 @@ extension MutablePersistableRecord {
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
@@ -628,10 +641,16 @@ extension MutablePersistableRecord {
modify: (inout Self) throws -> Void)
throws -> T?
{
try updateChangesAndFetch(
let record = self
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: { try T.fetchOne($0) },
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
modify: modify)
}
@@ -789,7 +808,6 @@ extension MutablePersistableRecord {
fetch: fetch)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -802,7 +820,8 @@ extension MutablePersistableRecord {
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function.
/// - returns: The result of the `fetch` function, or nil if the record
/// has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
@@ -814,7 +833,7 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?,
fetch: (Statement) throws -> T,
modify: (inout Self) throws -> Void)
throws -> T?
{
@@ -839,7 +858,7 @@ extension MutablePersistableRecord {
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?)
fetch: (Statement) throws -> T)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
@@ -861,7 +880,7 @@ extension MutablePersistableRecord {
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?)
fetch: (Statement) throws -> T)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
+1 -1
View File
@@ -348,7 +348,7 @@ extension MutablePersistableRecord {
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
///
/// See <https://www.sqlite.org/lang_conflict.html>
public struct PersistenceConflictPolicy {
public struct PersistenceConflictPolicy: Sendable {
/// The conflict resolution algorithm for insertions
public let conflictResolutionForInsert: Database.ConflictResolution
+24 -20
View File
@@ -56,7 +56,6 @@ extension PersistableRecord {
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -94,11 +93,10 @@ extension PersistableRecord {
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -107,19 +105,23 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
@@ -199,7 +201,6 @@ extension PersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -237,11 +238,10 @@ extension PersistableRecord {
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -250,20 +250,24 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
+18 -12
View File
@@ -39,7 +39,6 @@ extension PersistableRecord {
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -52,26 +51,30 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
})
return success!.saved
}
@@ -128,7 +131,6 @@ extension PersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -141,27 +143,31 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
})
return success!.saved
}
+34
View File
@@ -29,6 +29,7 @@ import Foundation
/// - ``exists(_:id:)``
/// - ``exists(_:key:)-60hf2``
/// - ``exists(_:key:)-6ha6``
/// - ``recordNotFound(_:)``
///
/// ### Throwing Record Not Found Errors
///
@@ -697,6 +698,15 @@ extension TableRecord {
public enum RecordError: Error {
/// A record does not exist in the database.
///
/// This error can be thrown from methods that update, such as
/// ``MutablePersistableRecord/update(_:onConflict:)``. In this case,
/// the error means that the database was not changed.
///
/// It can also be thrown from methods that inserts or update with a
/// `RETURNING` clause, and the `IGNORE` conflict policy. In this case,
/// the error notifies that a conflict has prevented the change from
/// being applied.
///
/// - parameters:
/// - databaseTableName: The table of the missing record.
/// - key: The key of the missing record (column and values).
@@ -740,6 +750,30 @@ extension TableRecord {
}
}
extension TableRecord where Self: EncodableRecord {
/// Returns an error that tells that the record does not exist in
/// the database.
///
/// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or
/// any error that prevented the `RecordError` from being constructed.
public func recordNotFound(_ db: Database) -> any Error {
do {
let databaseTableName = type(of: self).databaseTableName
let primaryKey = try db.primaryKey(databaseTableName)
let container = try PersistenceContainer(db, self)
let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map {
($0, container[caseInsensitive: $0]?.databaseValue ?? .null)
})
return RecordError.recordNotFound(
databaseTableName: databaseTableName,
key: key)
} catch {
return error
}
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns an error for a record that does not exist in the database.
+1 -1
View File
@@ -44,7 +44,7 @@
extension Inflections {
/// The default inflections
public static var `default`: Inflections = {
nonisolated(unsafe) public static var `default`: Inflections = {
// Defines the standard inflection rules. These are the starting point
// for new projects and are not considered complete. The current set of
// inflection rules is frozen. This means, we do not change them to
+1 -1
View File
@@ -31,7 +31,7 @@ extension String {
/// A type that controls GRDB string inflections.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public struct Inflections {
public struct Inflections: Sendable {
private var pluralizeRules: [(NSRegularExpression, String)] = []
private var singularizeRules: [(NSRegularExpression, String)] = []
private var uncountablesRegularExpressions: [String: NSRegularExpression] = [:]
-72
View File
@@ -1,72 +0,0 @@
import Foundation
/// A LockedBox protects a value with an NSLock.
@propertyWrapper
final class LockedBox<T> {
private var _wrappedValue: T
private var lock = NSLock()
var wrappedValue: T {
get { read { $0 } }
set { update { $0 = newValue } }
}
var projectedValue: LockedBox<T> { self }
init(wrappedValue: T) {
_wrappedValue = wrappedValue
}
/// Runs the provided closure while holding a lock on the value.
///
/// For example:
///
/// // Prints "0"
/// @LockedBox var count = 0
/// $count.read { print($0) }
///
/// - parameter block: A closure that accepts the value.
@inline(__always)
@usableFromInline
func read<U>(_ block: (T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try block(_wrappedValue)
}
/// Runs the provided closure while holding a lock on the value.
///
/// For example:
///
/// // Prints "1"
/// @LockedBox var count = 0
/// $count.update { $0 += 1 }
/// print(count)
///
/// - parameter block: A closure that can modify the value.
func update<U>(_ block: (inout T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try block(&_wrappedValue)
}
}
extension LockedBox where T: Numeric {
@discardableResult
func increment() -> T {
update { n in
n += 1
return n
}
}
@discardableResult
func decrement() -> T {
update { n in
n -= 1
return n
}
}
}
extension LockedBox: @unchecked Sendable where T: Sendable { }
+59
View File
@@ -0,0 +1,59 @@
import Foundation
/// A Mutex protects a value with an NSLock.
@propertyWrapper
final class Mutex<T> {
private var _wrappedValue: T
private var lock = NSLock()
var wrappedValue: T {
get { withLock { $0 } }
set { withLock { $0 = newValue } }
}
var projectedValue: Mutex<T> { self }
init(wrappedValue: T) {
_wrappedValue = wrappedValue
}
init(_ value: T) {
_wrappedValue = value
}
/// Runs the provided closure while holding a lock on the value.
///
/// For example:
///
/// // Prints "1"
/// @Mutex var count = 0
/// $count.withLock { $0 += 1 }
/// print(count)
///
/// - parameter block: A closure that can modify the value.
func withLock<U>(_ body: (inout T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try body(&_wrappedValue)
}
}
extension Mutex where T: Numeric {
@discardableResult
func increment() -> T {
withLock { n in
n += 1
return n
}
}
@discardableResult
func decrement() -> T {
withLock { n in
n -= 1
return n
}
}
}
extension Mutex: @unchecked Sendable where T: Sendable { }
+8 -4
View File
@@ -14,9 +14,12 @@ import Foundation
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
///
/// OnDemandFuture also adds Sendable requirements that avoid
/// compiler warnings.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = (Result<Output, Failure>) -> Void
struct OnDemandFuture<Output: Sendable, Failure: Error>: Publisher {
typealias Promise = @Sendable (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
@@ -34,8 +37,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
+2
View File
@@ -207,6 +207,8 @@ extension OrderedDictionary: CustomStringConvertible {
}
}
extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable { }
extension Dictionary {
init(_ orderedDictionary: OrderedDictionary<Key, Value>) {
self = orderedDictionary.dictionary
+33 -19
View File
@@ -35,8 +35,9 @@ import Dispatch
/// got 2
/// got 1
/// got 3
final class Pool<T> {
private class Item {
final class Pool<T: Sendable>: Sendable {
private class Item: @unchecked Sendable {
// @unchecked because `isAvailable` is protected by `content`.
let element: T
var isAvailable: Bool
@@ -46,8 +47,19 @@ final class Pool<T> {
}
}
private let makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private struct Content {
var items: [Item]
/// The number of created items. May become greater than the number
/// of elements in items, as some items are destroyed and other
/// are created.
var createdCount = 0
}
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
private let makeElement: @Sendable (Int) throws -> T
private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0))
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
@@ -59,11 +71,12 @@ final class Pool<T> {
/// - maximumCount: The maximum number of elements.
/// - qos: The quality of service of asynchronous accesses.
/// - makeElement: A function that creates an element. It is called
/// on demand.
/// on demand. Its argument is the index of the created elements
/// (1, then 2, etc).
init(
maximumCount: Int,
qos: DispatchQoS = .unspecified,
makeElement: @escaping () throws -> T)
makeElement: @escaping @Sendable (_ index: Int) throws -> T)
{
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
@@ -75,19 +88,20 @@ final class Pool<T> {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
func get() throws -> ElementAndRelease {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
let item = try content.update { content -> Item in
if let item = content.items.first(where: \.isAvailable) {
item.isAvailable = false
return item
} else {
let element = try makeElement()
content.createdCount += 1
let element = try makeElement(content.createdCount)
let item = Item(element: element, isAvailable: false)
items.append(item)
content.items.append(item)
return item
}
}
@@ -107,7 +121,7 @@ final class Pool<T> {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -128,7 +142,7 @@ final class Pool<T> {
}
private func release(_ item: Item, completion: PoolCompletion) {
$items.update { items in
content.update { content in
switch completion {
case .reuse:
// This is why Item is a class, not a struct: so that we can
@@ -136,8 +150,8 @@ final class Pool<T> {
item.isAvailable = true
case .discard:
// Discard should be rare: perform lookup.
if let index = items.firstIndex(where: { $0 === item }) {
items.remove(at: index)
if let index = content.items.firstIndex(where: { $0 === item }) {
content.items.remove(at: index)
}
}
}
@@ -148,8 +162,8 @@ final class Pool<T> {
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
try $items.read { items in
for item in items {
try content.read { content in
for item in content.items {
try body(item.element)
}
}
@@ -158,7 +172,7 @@ final class Pool<T> {
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
items = []
content.update { $0.items.removeAll() }
}
/// Blocks until no element is used, and runs the `barrier` function before
@@ -172,7 +186,7 @@ final class Pool<T> {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
+2 -1
View File
@@ -3,7 +3,8 @@ import Dispatch
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a
/// value. It is backed by a concurrent DispatchQueue.
@propertyWrapper
final class ReadWriteBox<T> {
final class ReadWriteBox<T: Sendable>: @unchecked Sendable {
// @unchecked because `_wrappedValue` is protected by `queue`
private var _wrappedValue: T
private var queue: DispatchQueue
+6 -6
View File
@@ -67,7 +67,7 @@ extension Dictionary {
}
extension DispatchQueue {
private static var mainKey: DispatchSpecificKey<()> = {
nonisolated(unsafe) private static let mainKey: DispatchSpecificKey<()> = {
let key = DispatchSpecificKey<()>()
DispatchQueue.main.setSpecific(key: key, value: ())
return key
@@ -118,14 +118,14 @@ func throwingFirstError<T>(execute: () throws -> T, finally: () throws -> Void)
return result!
}
struct PrintOutputStream: TextOutputStream {
struct PrintOutputStream: TextOutputStream, Sendable {
func write(_ string: String) {
Swift.print(string)
}
}
/// Concatenates two functions
func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
/// Concatenates two @Sendable functions
func concat(_ rhs: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (@Sendable () -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
@@ -139,8 +139,8 @@ func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
}
}
/// Concatenates two functions
func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
/// Concatenates two @Sendable functions
func concat<T>(_ rhs: (@Sendable (T) -> Void)?, _ lhs: (@Sendable (T) -> Void)?) -> (@Sendable (T) -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
+18 -11
View File
@@ -1,3 +1,5 @@
import Foundation
/// A protocol indicating that an activity or action supports cancellation.
///
/// ## Topics
@@ -5,7 +7,7 @@
/// ### Supporting Types
///
/// - ``AnyDatabaseCancellable``
public protocol DatabaseCancellable {
public protocol DatabaseCancellable: Sendable {
/// Cancel the activity.
func cancel()
}
@@ -15,31 +17,36 @@ public protocol DatabaseCancellable {
///
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized.
public class AnyDatabaseCancellable: DatabaseCancellable {
private var _cancel: (() -> Void)?
public final class AnyDatabaseCancellable: DatabaseCancellable, @unchecked Sendable {
// @unchecked Sendable due to `_cancel`, which is protected by `lock`.
private let lock = NSLock()
private var _cancel: (@Sendable () -> Void)?
var isCancelled: Bool {
lock.withLock { _cancel == nil }
}
/// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping () -> Void) {
public init(cancel: @escaping @Sendable () -> Void) {
_cancel = cancel
}
/// Creates a cancellable object that forwards cancellation to `base`.
public convenience init(_ base: some DatabaseCancellable) {
var cancellable = Optional.some(base)
self.init {
cancellable?.cancel()
cancellable = nil // Release memory
base.cancel()
}
}
deinit {
_cancel?()
cancel()
}
public func cancel() {
// Don't prevent multiple concurrent calls to _cancel, because it is
// pointless. But release memory!
_cancel?()
lock.lock()
let cancel = _cancel
_cancel = nil
lock.unlock()
cancel?()
}
}
@@ -18,7 +18,10 @@ import Foundation
/// reducing stage.
///
/// **Notify** is calling user callbacks, in case of database change or error.
final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObservationScheduler> {
final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObservationScheduler>: @unchecked Sendable {
// @unchecked because mutable state is protected by various locks and
// serial dispatch queues. See "Mutable State" below.
// MARK: - Configuration
//
// Configuration is not mutable.
@@ -72,7 +75,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
// be notified. See error catching clauses.
/// Ability to access the database
private struct DatabaseAccess {
private struct DatabaseAccess: Sendable {
/// The observed DatabasePool.
let dbPool: DatabasePool
@@ -102,7 +105,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
}
/// The fetching state for observation of constant regions.
enum FetchingState {
enum FetchingState: Sendable {
/// No need to fetch.
case idle
@@ -115,13 +118,13 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
}
/// Ability to notify observation events
private struct NotificationCallbacks {
private struct NotificationCallbacks: Sendable {
let events: ValueObservationEvents
let onChange: (Reducer.Value) -> Void
let onChange: @Sendable (Reducer.Value) -> Void
}
/// Relationship with the `TransactionObserver` protocol
private struct ObservationState {
private struct ObservationState: Sendable {
var region: DatabaseRegion?
var isModified = false
@@ -146,7 +149,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
private var notificationCallbacks: NotificationCallbacks?
/// The fetching state for observation of constant regions.
@LockedBox private var fetchingState = FetchingState.idle
@Mutex private var fetchingState = FetchingState.idle
/// Support for `TransactionObserver`, protected by the serialized writer
/// dispatch queue.
@@ -161,7 +164,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
trackingMode: ValueObservationTrackingMode,
reducer: Reducer,
events: ValueObservationEvents,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
{
// Configuration
self.scheduler = scheduler
@@ -273,8 +276,7 @@ extension ValueConcurrentObserver {
}
}
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
extension ValueConcurrentObserver {
/// Synchronously starts the observation, and returns the initial value.
///
@@ -353,10 +355,11 @@ extension ValueConcurrentObserver {
let initialFetchTransaction = try result.get()
// Second async jump because that's how
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
initialFetchTransaction.asyncRead { db in
initialFetchTransaction.asyncRead { dbResult in
do {
let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion
let db = try dbResult.get()
switch self.trackingMode {
case let .constantRegion(regions):
@@ -430,11 +433,9 @@ extension ValueConcurrentObserver {
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// However, we want to close `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
// available for other reads.
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
let events = self.lock.synchronized { self.notificationCallbacks?.events }
@@ -447,7 +448,7 @@ extension ValueConcurrentObserver {
// Was the database modified since the initial fetch?
let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering")
isModified = ordering < 0
} else {
@@ -455,9 +456,9 @@ extension ValueConcurrentObserver {
isModified = true
}
// Comparison done: end the WAL snapshot transaction
// Comparison done: close the WAL snapshot transaction
// and release its reader connection.
initialFetchTransaction = nil
initialFetchTransaction.close()
if isModified {
events.databaseDidChange?()
@@ -781,7 +782,7 @@ extension ValueConcurrentObserver: TransactionObserver {
}
private func setNeedsFetching(databaseAccess: DatabaseAccess) {
$fetchingState.update { state in
$fetchingState.withLock { state in
switch state {
case .idle:
state = .fetching
@@ -807,7 +808,7 @@ extension ValueConcurrentObserver: TransactionObserver {
self.reduce(fetchResult)
$fetchingState.update { state in
$fetchingState.withLock { state in
switch state {
case .idle:
// GRDB bug
@@ -21,8 +21,11 @@ import Foundation
final class ValueWriteOnlyObserver<
Writer: DatabaseWriter,
Reducer: ValueReducer,
Scheduler: ValueObservationScheduler>
Scheduler: ValueObservationScheduler>: @unchecked Sendable
{
// @unchecked because mutable state is protected by various locks and
// serial dispatch queues. See "Mutable State" below.
// MARK: - Configuration
//
// Configuration is not mutable.
@@ -76,7 +79,7 @@ final class ValueWriteOnlyObserver<
// be notified. See error catching clauses.
/// Ability to access the database
private struct DatabaseAccess {
private struct DatabaseAccess: Sendable {
/// The observed DatabaseWriter.
let writer: Writer
@@ -110,13 +113,13 @@ final class ValueWriteOnlyObserver<
}
/// Ability to notify observation events
private struct NotificationCallbacks {
private struct NotificationCallbacks: Sendable {
let events: ValueObservationEvents
let onChange: (Reducer.Value) -> Void
let onChange: @Sendable (Reducer.Value) -> Void
}
/// Relationship with the `TransactionObserver` protocol
private struct ObservationState {
private struct ObservationState: Sendable {
var region: DatabaseRegion?
var isModified = false
@@ -150,7 +153,7 @@ final class ValueWriteOnlyObserver<
trackingMode: ValueObservationTrackingMode,
reducer: Reducer,
events: ValueObservationEvents,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
{
// Configuration
self.scheduler = scheduler
+3 -3
View File
@@ -1,10 +1,10 @@
extension ValueReducers {
/// A `ValueReducer` that perform database fetches.
public struct Fetch<Value>: ValueReducer {
private let __fetch: (Database) throws -> Value
public struct Fetch<Value: Sendable>: ValueReducer {
private let __fetch: @Sendable (Database) throws -> Value
/// Creates a reducer which passes raw fetched values through.
init(fetch: @escaping (Database) throws -> Value) {
init(fetch: @escaping @Sendable (Database) throws -> Value) {
self.__fetch = fetch
}
+4 -4
View File
@@ -18,7 +18,7 @@ extension ValueObservation {
///
/// - parameter transform: A closure that takes one value as its parameter
/// and returns a new value.
public func map<T>(_ transform: @escaping (Reducer.Value) throws -> T)
public func map<T>(_ transform: @escaping @Sendable (Reducer.Value) throws -> T)
-> ValueObservation<ValueReducers.Map<Reducer, T>>
{
mapReducer { ValueReducers.Map($0, transform) }
@@ -30,11 +30,11 @@ extension ValueReducers {
/// passed through a transform function.
///
/// See ``ValueObservation/map(_:)``.
public struct Map<Base: _ValueReducer, Value>: _ValueReducer {
public struct Map<Base: _ValueReducer, Value: Sendable>: _ValueReducer {
private var base: Base
private let transform: (Base.Value) throws -> Value
private let transform: @Sendable (Base.Value) throws -> Value
init(_ base: Base, _ transform: @escaping (Base.Value) throws -> Value) {
init(_ base: Base, _ transform: @escaping @Sendable (Base.Value) throws -> Value) {
self.base = base
self.transform = transform
}
@@ -5,7 +5,7 @@ extension ValueObservation {
/// - parameter predicate: A closure to evaluate whether two values are
/// equivalent, for purposes of filtering. Return true from this closure
/// to indicate that the second element is a duplicate of the first.
public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool)
public func removeDuplicates(by predicate: @escaping @Sendable (Reducer.Value, Reducer.Value) -> Bool)
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) }
@@ -58,7 +58,10 @@ extension ValueObservation where Reducer.Value: Equatable {
public func removeDuplicates()
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: ==) }
mapReducer { base in
// https://github.com/apple/swift/issues/71541
ValueReducers.RemoveDuplicates(base, predicate: { $0 == $1 })
}
}
}
@@ -70,9 +73,9 @@ extension ValueReducers {
public struct RemoveDuplicates<Base: _ValueReducer>: _ValueReducer {
private var base: Base
private var previousValue: Base.Value?
private var predicate: (Base.Value, Base.Value) -> Bool
private var predicate: @Sendable (Base.Value, Base.Value) -> Bool
init(_ base: Base, predicate: @escaping (Base.Value, Base.Value) -> Bool) {
init(_ base: Base, predicate: @escaping @Sendable (Base.Value, Base.Value) -> Bool) {
self.base = base
self.predicate = predicate
}
+2 -2
View File
@@ -6,8 +6,8 @@ extension ValueReducers {
/// and ``ValueObservation/print(_:to:)``.
public struct Trace<Base: _ValueReducer>: _ValueReducer {
var base: Base
let willFetch: () -> Void
let didReceiveValue: (Base.Value) -> Void
let willFetch: @Sendable () -> Void
let didReceiveValue: @Sendable (Base.Value) -> Void
public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? {
guard let value = try base._value(fetched) else {
@@ -1,10 +1,15 @@
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer {
/// The type of fetched database values
associatedtype Fetched
// Sendable because fetched values will asynchronously jump from a
// database access dispatch queue to a reducer dispatch queue.
/// The type of fetched database values.
associatedtype Fetched: Sendable
/// The type of observed values
associatedtype Value
// Sendable because reduced values will asynchronously jump from a
// reducer dispatch queue to a user-provided queue (the main queue,
// most frequently).
/// The type of observed values.
associatedtype Value: Sendable
/// Transforms a fetched value into an eventual observed value. Returns nil
/// when observer should not be notified.
@@ -31,7 +36,7 @@ public protocol _ValueReducer {
/// ### Support
///
/// - ``ValueReducers``
public protocol ValueReducer: _ValueReducer {
public protocol ValueReducer: _ValueReducer, Sendable {
/// Fetches database values upon changes in an observed database region.
///
/// This method must does not depend on the state of the reducer.
@@ -1,7 +1,7 @@
import Foundation
/// The extent of the shared subscription to a ``SharedValueObservation``.
public enum SharedValueObservationExtent {
public enum SharedValueObservationExtent: Sendable {
/// The ``SharedValueObservation`` starts a single database observation,
/// which stops when the `SharedValueObservation` is deallocated and all
/// subscriptions terminated.
@@ -167,7 +167,8 @@ extension ValueObservation {
/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// ```
public final class SharedValueObservation<Element> {
public final class SharedValueObservation<Element: Sendable>: @unchecked Sendable {
// @unchecked because `clients` is protected by `lock`.
private let scheduler: any ValueObservationScheduler
private let extent: SharedValueObservationExtent
private let startObservation: ValueObservationStart<Element>
@@ -179,11 +180,11 @@ public final class SharedValueObservation<Element> {
private var cancellable: AnyDatabaseCancellable?
private var lastResult: Result<Element, Error>?
private final class Client {
var onError: (Error) -> Void
var onChange: (Element) -> Void
private final class Client: Sendable {
let onError: @Sendable (Error) -> Void
let onChange: @Sendable (Element) -> Void
init(onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) {
init(onError: @escaping @Sendable (Error) -> Void, onChange: @escaping @Sendable (Element) -> Void) {
self.onError = onError
self.onChange = onChange
}
@@ -224,8 +225,8 @@ public final class SharedValueObservation<Element> {
/// fresh value.
/// - returns: A DatabaseCancellable that can stop the observation.
public func start(
onError: @escaping (Error) -> Void,
onChange: @escaping (Element) -> Void)
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Element) -> Void)
-> AnyDatabaseCancellable
{
synchronized {
+89 -56
View File
@@ -4,7 +4,7 @@ import Combine
import Dispatch
import Foundation
public struct ValueObservation<Reducer: _ValueReducer> {
public struct ValueObservation<Reducer: _ValueReducer>: Sendable {
var events = ValueObservationEvents()
/// A boolean value indicating whether the observation requires write access
@@ -30,10 +30,10 @@ public struct ValueObservation<Reducer: _ValueReducer> {
/// The reducer is created when observation starts, and is triggered upon
/// each database change.
var makeReducer: () -> Reducer
var makeReducer: @Sendable () -> Reducer
/// Returns a ValueObservation with a transformed reducer.
func mapReducer<R>(_ transform: @escaping (Reducer) -> R) -> ValueObservation<R> {
func mapReducer<R>(_ transform: @escaping @Sendable (Reducer) -> R) -> ValueObservation<R> {
let makeReducer = self.makeReducer
return ValueObservation<R>(
events: events,
@@ -44,7 +44,7 @@ public struct ValueObservation<Reducer: _ValueReducer> {
}
/// Configures the tracked region
enum ValueObservationTrackingMode {
enum ValueObservationTrackingMode: Sendable {
/// The tracked region is constant and explicit.
///
/// Use case:
@@ -73,17 +73,17 @@ enum ValueObservationTrackingMode {
case nonConstantRegionRecordedFromSelection
}
struct ValueObservationEvents: Refinable {
var willStart: (() -> Void)?
var willTrackRegion: ((DatabaseRegion) -> Void)?
var databaseDidChange: (() -> Void)?
var didFail: ((Error) -> Void)?
var didCancel: (() -> Void)?
struct ValueObservationEvents: Refinable, Sendable {
var willStart: (@Sendable () -> Void)?
var willTrackRegion: (@Sendable (DatabaseRegion) -> Void)?
var databaseDidChange: (@Sendable () -> Void)?
var didFail: (@Sendable (Error) -> Void)?
var didCancel: (@Sendable () -> Void)?
}
typealias ValueObservationStart<T> = (
_ onError: @escaping (Error) -> Void,
_ onChange: @escaping (T) -> Void)
typealias ValueObservationStart<T: Sendable> = @Sendable (
_ onError: @escaping @Sendable (Error) -> Void,
_ onChange: @escaping @Sendable (T) -> Void)
-> AnyDatabaseCancellable
extension ValueObservation: Refinable {
@@ -138,8 +138,8 @@ extension ValueObservation: Refinable {
public func start(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
where Reducer: ValueReducer
{
@@ -175,13 +175,13 @@ extension ValueObservation: Refinable {
/// - returns: A `ValueObservation` that performs the specified closures
/// when ValueObservation events occur.
public func handleEvents(
willStart: (() -> Void)? = nil,
willFetch: (() -> Void)? = nil,
willTrackRegion: ((DatabaseRegion) -> Void)? = nil,
databaseDidChange: (() -> Void)? = nil,
didReceiveValue: ((Reducer.Value) -> Void)? = nil,
didFail: ((Error) -> Void)? = nil,
didCancel: (() -> Void)? = nil)
willStart: (@Sendable () -> Void)? = nil,
willFetch: (@Sendable () -> Void)? = nil,
willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? = nil,
databaseDidChange: (@Sendable () -> Void)? = nil,
didReceiveValue: (@Sendable (Reducer.Value) -> Void)? = nil,
didFail: (@Sendable (Error) -> Void)? = nil,
didCancel: (@Sendable () -> Void)? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
self
@@ -229,36 +229,66 @@ extension ValueObservation: Refinable {
/// - parameter stream: A stream for text output that receives messages, and
/// which directs output to the console by default. A custom stream can be
/// used to log messages to other destinations.
public func print(
_ prefix: String = "",
to stream: TextOutputStream? = nil)
public func print(_ prefix: String = "")
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
let lock = NSLock()
print(prefix, to: PrintOutputStream())
}
/// Prints log messages for all observation events.
///
/// For example:
///
/// ```swift
/// let cancellable = ValueObservation
/// .tracking(Player.fetchCount)
/// .print("Observe player count")
/// .start(in: dbQueue, onError: { _ in }, onChange: { _ in })
///
/// // Prints:
/// // Observe player count: start
/// // Observe player count: fetch
/// // Observe player count: tracked region: player(*)
/// // Observe player count: value: 0
/// // Observe player count: database did change
/// // Observe player count: fetch
/// // Observe player count: value: 1
/// ```
///
/// - parameter prefix: A string —- which defaults to empty -— with which to
/// prefix all log messages.
/// - parameter stream: A stream for text output that receives messages, and
/// which directs output to the console by default. A custom stream can be
/// used to log messages to other destinations.
public func print<Stream: TextOutputStream & Sendable>(
_ prefix: String = "",
to stream: Stream)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
let stream = Mutex(stream)
let prefix = prefix.isEmpty ? "" : "\(prefix): "
var stream = stream ?? PrintOutputStream()
return handleEvents(
willStart: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)start") },
stream.withLock { $0.write("\(prefix)start") }
},
willFetch: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)fetch") },
willTrackRegion: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)tracked region: \($0)") },
stream.withLock { $0.write("\(prefix)fetch") }
},
willTrackRegion: { region in
stream.withLock { $0.write("\(prefix)tracked region: \(region)") }
},
databaseDidChange: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)database did change") },
didReceiveValue: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)value: \($0)") },
didFail: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)failure: \($0)") },
stream.withLock { $0.write("\(prefix)database did change") }
},
didReceiveValue: { value in
stream.withLock { $0.write("\(prefix)value: \(value)") }
},
didFail: { error in
stream.withLock { $0.write("\(prefix)failure: \(error)") }
},
didCancel: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)cancel") })
stream.withLock { $0.write("\(prefix)cancel") }
})
}
// MARK: - Fetching Values
@@ -294,18 +324,19 @@ extension ValueObservation {
/// ```
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A ValueObservationScheduler. By default, fresh
/// values are dispatched asynchronously on the main dispatch queue.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func values(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
bufferingPolicy: AsyncValueObservation<Reducer.Value>.BufferingPolicy = .unbounded)
-> AsyncValueObservation<Reducer.Value>
where Reducer: ValueReducer
{
AsyncValueObservation(bufferingPolicy: bufferingPolicy) { onError, onChange in
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
self.start(
in: reader,
scheduling: .async(onQueue: .main),
onError: onError,
onChange: onChange)
}
}
}
@@ -333,7 +364,7 @@ extension ValueObservation {
/// You build an `AsyncValueObservation` from ``ValueObservation`` or
/// ``SharedValueObservation``.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public struct AsyncValueObservation<Element>: AsyncSequence {
public struct AsyncValueObservation<Element: Sendable>: AsyncSequence {
public typealias BufferingPolicy = AsyncThrowingStream<Element, Error>.Continuation.BufferingPolicy
public typealias AsyncIterator = Iterator
@@ -457,7 +488,7 @@ extension DatabasePublishers {
///
/// You build such a publisher from ``ValueObservation``
/// or ``SharedValueObservation``.
public struct Value<Output>: Publisher {
public struct Value<Output: Sendable>: Publisher {
public typealias Failure = Error
private let start: ValueObservationStart<Output>
@@ -473,9 +504,11 @@ extension DatabasePublishers {
}
}
private class ValueSubscription<Downstream: Subscriber>: Subscription
where Downstream.Failure == Error
private final class ValueSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
where Downstream.Input: Sendable, Downstream.Failure == Error
{
// @unchecked because `cancellable` and `state` are protected by `lock`.
private struct WaitingForDemand {
let downstream: Downstream
let start: ValueObservationStart<Downstream.Input>
@@ -704,7 +737,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func trackingConstantRegion<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -765,7 +798,7 @@ extension ValueObservation {
public static func tracking<Value>(
region: any DatabaseRegionConvertible,
_ otherRegions: any DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -821,7 +854,7 @@ extension ValueObservation {
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
regions: [any DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -878,7 +911,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -11,17 +11,17 @@ import Foundation
/// - ``immediate``
/// - ``AsyncValueObservationScheduler``
/// - ``ImmediateValueObservationScheduler``
public protocol ValueObservationScheduler {
public protocol ValueObservationScheduler: Sendable {
/// Returns whether the initial value should be immediately notified.
///
/// If the result is true, then this method was called on the main thread.
func immediateInitialValue() -> Bool
func schedule(_ action: @escaping () -> Void)
func schedule(_ action: @escaping @Sendable () -> Void)
}
extension ValueObservationScheduler {
func scheduleInitial(_ action: @escaping () -> Void) {
func scheduleInitial(_ action: @escaping @Sendable () -> Void) {
if immediateInitialValue() {
action()
} else {
@@ -42,7 +42,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler {
public func immediateInitialValue() -> Bool { false }
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
queue.async(execute: action)
}
}
@@ -86,7 +86,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
return true
}
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
+8 -20
View File
@@ -156,13 +156,10 @@
5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; };
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
5657AB391D108BA9006283EF /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */; };
5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB311D108BA9006283EF /* FoundationNSNullTests.swift */; };
5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB321D108BA9006283EF /* FoundationNSNumberTests.swift */; };
5657AB591D108BA9006283EF /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */; };
5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */; };
5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB351D108BA9006283EF /* FoundationURLTests.swift */; };
5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4871EA8D94E004A4992 /* Utils.swift */; };
@@ -185,7 +182,7 @@
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */; };
566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */; };
566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; };
566BE7152342541F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* Mutex.swift */; };
566DDE12288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; };
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
@@ -276,6 +273,7 @@
56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */; };
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; };
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA65F2B79247000B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA65D2B79247000B3A7F8 /* Mutex.swift */; };
56BF22882417821F003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF22862417821F003D86EB /* UtilsTests.swift */; };
56C0539322ACEECD0029D27D /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538A22ACEECD0029D27D /* Fetch.swift */; };
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; };
@@ -353,7 +351,6 @@
F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; };
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1501C672E4000235C62 /* NSNull.swift */; };
F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; };
F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; };
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
@@ -468,7 +465,6 @@
5605F14F1C672E4000235C62 /* Date.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Date.swift; sourceTree = "<group>"; };
5605F1501C672E4000235C62 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
5605F1511C672E4000235C62 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
@@ -621,13 +617,10 @@
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = "<group>"; };
5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = "<group>"; };
5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDataTests.swift; sourceTree = "<group>"; };
5657AB311D108BA9006283EF /* FoundationNSNullTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSNullTests.swift; sourceTree = "<group>"; };
5657AB321D108BA9006283EF /* FoundationNSNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSNumberTests.swift; sourceTree = "<group>"; };
5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSStringTests.swift; sourceTree = "<group>"; };
5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSURLTests.swift; sourceTree = "<group>"; };
5657AB351D108BA9006283EF /* FoundationURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationURLTests.swift; sourceTree = "<group>"; };
5659F4871EA8D94E004A4992 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
@@ -654,7 +647,7 @@
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
566BE7132342541F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
566DDE11288D76400000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = "<group>"; };
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
@@ -793,6 +786,7 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA65D2B79247000B3A7F8 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
56BF22862417821F003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C0538A22ACEECD0029D27D /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
56C0538C22ACEECD0029D27D /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
@@ -940,10 +934,8 @@
5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */,
5605F14F1C672E4000235C62 /* Date.swift */,
56894FA0260657F600268F4D /* Decimal.swift */,
5657AAB81D107001006283EF /* NSData.swift */,
5605F1501C672E4000235C62 /* NSNull.swift */,
5605F1511C672E4000235C62 /* NSNumber.swift */,
5605F1521C672E4000235C62 /* NSString.swift */,
567071F2208A00BE006AD95A /* SQLiteDateParser.swift */,
5657AB0E1D10899D006283EF /* URL.swift */,
56A8C22F1D1914540096E9D4 /* UUID.swift */,
@@ -1030,6 +1022,7 @@
children = (
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56BCA65D2B79247000B3A7F8 /* Mutex.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567B5BFC2AD3285C00629622 /* Dump */,
@@ -1337,7 +1330,7 @@
564D4F91261E1D3300F55856 /* CaseInsensitiveIdentifier.swift */,
563EF44C2161F196007DAACD /* Inflections.swift */,
569BBA4B229170B300478429 /* Inflections+English.swift */,
566BE7132342541F00A8254B /* LockedBox.swift */,
566BE7132342541F00A8254B /* Mutex.swift */,
563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */,
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
@@ -1680,12 +1673,10 @@
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */,
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */,
56894FF1260658E600268F4D /* FoundationDecimalTests.swift */,
5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */,
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */,
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */,
5657AB311D108BA9006283EF /* FoundationNSNullTests.swift */,
5657AB321D108BA9006283EF /* FoundationNSNumberTests.swift */,
5657AB331D108BA9006283EF /* FoundationNSStringTests.swift */,
5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */,
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */,
5657AB351D108BA9006283EF /* FoundationURLTests.swift */,
@@ -2083,7 +2074,6 @@
5656A8572295BD56001FF3FF /* SQLQueryGenerator.swift in Sources */,
5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */,
5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */,
F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */,
56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */,
56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */,
5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */,
@@ -2094,7 +2084,7 @@
5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */,
5656A86D2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */,
56894FE3260658A400268F4D /* Decimal.swift in Sources */,
566BE7152342541F00A8254B /* LockedBox.swift in Sources */,
566BE7152342541F00A8254B /* Mutex.swift in Sources */,
F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */,
F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */,
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
@@ -2134,7 +2124,6 @@
567B5BF82AD3285100629622 /* QuoteDumpFormat.swift in Sources */,
56F89E082A57EBA7002FE2AA /* Database+SchemaDefinition.swift in Sources */,
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
5657AABB1D107001006283EF /* NSData.swift in Sources */,
56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */,
567B5BF62AD3285100629622 /* DatabaseReader+dump.swift in Sources */,
5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -2160,7 +2149,6 @@
563EF45621631E3F007DAACD /* QueryInterfacePromiseTests.swift in Sources */,
56DF0015228DDB8300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */,
56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */,
5657AB591D108BA9006283EF /* FoundationNSStringTests.swift in Sources */,
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
5698ACCB1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */,
56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
@@ -2236,7 +2224,6 @@
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */,
56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */,
56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */,
562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
@@ -2341,6 +2328,7 @@
562393631DEE06D300A6B01F /* CursorTests.swift in Sources */,
563B06D52185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */,
562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */,
56BCA65F2B79247000B3A7F8 /* Mutex.swift in Sources */,
565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */,
F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */,
+6 -3
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.7
// swift-tools-version:5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.
import Foundation
@@ -6,6 +6,8 @@ import PackageDescription
var swiftSettings: [SwiftSetting] = [
.define("SQLITE_ENABLE_FTS5"),
// <https://github.com/apple/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md>
.enableExperimentalFeature("StrictConcurrency"),
]
var cSettings: [CSetting] = []
var dependencies: [PackageDescription.Package.Dependency] = []
@@ -34,9 +36,10 @@ let package = Package(
name: "GRDB",
defaultLocalization: "en", // for tests
platforms: [
.iOS(.v11),
.iOS(.v12),
.macOS(.v10_13),
.tvOS(.v11),
.tvOS(.v12),
.visionOS(.v1),
.watchOS(.v4),
],
products: [
+26 -13
View File
@@ -10,14 +10,14 @@
</p>
<p align="center">
<a href="https://developer.apple.com/swift/"><img alt="Swift 5.7" src="https://img.shields.io/badge/swift-5.7-orange.svg?style=flat"></a>
<a href="https://developer.apple.com/swift/"><img alt="Swift 5.10" src="https://img.shields.io/badge/swift-5.10-orange.svg?style=flat"></a>
<a href="https://github.com/groue/GRDB.swift/blob/master/LICENSE"><img alt="License" src="https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000"></a>
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: January 21, 2024 • [version 6.24.2](https://github.com/groue/GRDB.swift/tree/v6.24.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 14+
**Requirements**: iOS 12.0+ / macOS 10.13+ / tvOS 12.0+ / visionOS 1.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 15.3+
**Contact**:
@@ -1078,7 +1078,7 @@ GRDB ships with built-in support for the following value types:
- **Swift Standard Library**: Bool, Double, Float, all signed and unsigned integer types, String, [Swift enums](#swift-enums).
- **Foundation**: [Data](#data-and-memory-savings), [Date](#date-and-datecomponents), [DateComponents](#date-and-datecomponents), [Decimal](#nsnumber-nsdecimalnumber-and-decimal), NSNull, [NSNumber](#nsnumber-nsdecimalnumber-and-decimal), NSString, URL, [UUID](#uuid).
- **Foundation**: [Data](#data-and-memory-savings), [Date](#date-and-datecomponents), [DateComponents](#date-and-datecomponents), [Decimal](#nsnumber-nsdecimalnumber-and-decimal), NSNull, [NSNumber](#nsnumber-nsdecimalnumber-and-decimal), URL, [UUID](#uuid).
- **CoreGraphics**: CGFloat.
@@ -2310,11 +2310,10 @@ try dbQueue.write { db in
let partialPlayer = PartialPlayer(name: "Alice")
// INSERT INTO player (name) VALUES ('Alice') RETURNING *
if let player = try partialPlayer.insertAndFetch(db, as: Player.self) {
print(player.id) // The inserted id
print(player.name) // The inserted name
print(player.score) // The default score
}
let player = try partialPlayer.insertAndFetch(db, as: Player.self)
print(player.id) // The inserted id
print(player.name) // The inserted name
print(player.score) // The default score
}
```
@@ -2776,7 +2775,9 @@ let player = try decoder.decode(Player.self, from: jsonData)
```swift
extension Player: FetchableRecord {
static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "database row"]
static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] {
[decoderName: "database row"]
}
}
// prints "Decoded from database row"
@@ -2784,6 +2785,17 @@ let player = try Player.fetchOne(db, ...)
```
> **Note**: make sure the `databaseDecodingUserInfo` and `databaseEncodingUserInfo` properties are explicitly declared as `[CodingUserInfoKey: Any]`. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo.
>
> If the compiler emits a warning about the static property 'databaseEncodingUserInfo' being concurrency-unsafe, turn the stored (`static let`) property into a computed (`static var`) one:
>
> ```swift
> extension Player: FetchableRecord {
> // No concurrency warning with a computed property:
> static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] {
> [decoderName: "database row"]
> }
> }
> ```
### Tip: Derive Columns from Coding Keys
@@ -3088,15 +3100,16 @@ struct Player : MutablePersistableRecord {
try player.insert(db)
```
> **Note**: If you specify the `ignore` policy for inserts, the [`didInsert` callback](#persistence-callbacks) will be called with some random id in case of failed insert. You can detect failed insertions with `insertAndFetch`:
> **Note**: If you specify the `ignore` policy for inserts, the [`didInsert` callback](#persistence-callbacks) will be called with some random id in case of failed insert. You can detect failed insertions with `insertAndFetch`:
>
> ```swift
> // How to detect failed `INSERT OR IGNORE`:
> // INSERT OR IGNORE INTO player ... RETURNING *
> if let insertedPlayer = try player.insertAndFetch(db) {
> do {
> let insertedPlayer = try player.insertAndFetch(db) {
> // Succesful insertion
> } else {
> // Ignored failure
> catch RecordError.recordNotFound {
> // Failed insertion due to IGNORE policy
> }
> ```
>
+5 -2
View File
@@ -1,4 +1,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 11.0
IPHONEOS_DEPLOYMENT_TARGET = 12.0
MACOSX_DEPLOYMENT_TARGET = 10.13
TVOS_DEPLOYMENT_TARGET = 11.0
TVOS_DEPLOYMENT_TARGET = 12.0
WATCHOS_DEPLOYMENT_TARGET = 4.0
XROS_DEPLOYMENT_TARGET = 1.0
SWIFT_STRICT_CONCURRENCY = complete
+4 -6
View File
@@ -1,14 +1,12 @@
IPHONEOS_DEPLOYMENT_TARGET = 11.0
IPHONEOS_DEPLOYMENT_TARGET = 12.0
MACOSX_DEPLOYMENT_TARGET = 10.13
TVOS_DEPLOYMENT_TARGET = 11.0
TVOS_DEPLOYMENT_TARGET = 12.0
WATCHOS_DEPLOYMENT_TARGET = 4.0
XROS_DEPLOYMENT_TARGET = 1.0
OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5
//// Compile with all opt-in APIs
//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1
//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK
// Enable concurrency warning in Swift 5.5
// https://twitter.com/olebegemann/status/1421144304127463427?lang=en
// Those as commented out by default, until minimum support Xcode version can handle them.
// OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks
SWIFT_STRICT_CONCURRENCY = complete
+87
View File
@@ -84,6 +84,93 @@
- [ ] Check https://sqlite.org/sqlar.html
- [ ] More schema alterations
- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool?
- [ ] GRDB7/concurrency
- migrations
- AsyncValueObservation
- [ ] GRDB7 JSONB https://hachyderm.io/@jason_abbott/111908186742242971#.
- [ ] GRDB7: stop exporting CSQLite https://github.com/groue/GRDB.swift/issues/642#issuecomment-1937347696
- [ ] GRDB7: AsyncValueObservation: experiment with an immediate scheduler that does not hop to the main queue.
- [ ] GRDB7: Question Sendability of SQLExpressible et al. If we can copy Sendable representations in requests, it's not needed.
- [ ] GRDB7: Raise the minimum watchOS target https://github.com/groue/GRDB.swift/issues/1472#issuecomment-1960696836
- [ ] GRDB7: Consider putting a Task cancellation handler on async methods.
- [ ] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553
- [ ] GRDB7: Sendable conformances
- [ ] anydatabasecancellable
- [ ] anydatabaseregionconvertible
- [ ] anyfetchrequest
- [ ] anysqljsonexpressible
- [ ] association
- [ ] associationaggregate
- [ ] associationtomany
- [ ] asyncvalueobservation
- [ ] asyncvalueobservation/iterator
- [ ] asyncvalueobservationscheduler
- [ ] belongstoassociation
- [ ] columnexpression
- [ ] commontableexpression
- [ ] configuration
- [ ] customtransactionclock
- [ ] database/busymode
- [ ] databaseaggregate
- [ ] databasecancellable
- [ ] databasecollation
- [ ] databasecolumndecodingstrategy
- [ ] databasecolumnencodingstrategy
- [ ] databasedatadecodingstrategy
- [ ] databasedataencodingstrategy
- [ ] databasedatedecodingstrategy
- [ ] databasedateencodingstrategy
- [ ] databasefunction
- [ ] databasefuture
- [ ] databasemigrator
- [ ] databasepublishers/databaseregion
- [ ] databasepublishers/migrate
- [ ] databasepublishers/read
- [ ] databasepublishers/value
- [ ] databasepublishers/write
- [ ] databaseregionobservation
- [ ] databaseuuidencodingstrategy
- [ ] defaulttransactionclock
- [ ] fetchablerecorddecoder
- [ ] fetchrequest
- [ ] filtercursor
- [ ] fts5customtokenizer
- [ ] fts5tokenizer
- [ ] fts5wrappertokenizer
- [ ] hasmanyassociation
- [ ] hasmanythroughassociation
- [ ] hasoneassociation
- [ ] hasonethroughassociation
- [ ] insertionsuccess
- [ ] joinassociation
- [ ] persistencecontainer
- [ ] persistencesuccess
- [ ] queryinterfacerequest
- [ ] record
- [ ] renamecolumnadapter
- [ ] row/prefetchedrowsview
- [ ] row/scopestreeview
- [ ] row/scopesview
- [ ] rowadapter
- [ ] scopeadapter
- [ ] sharedvalueobservation
- [ ] sql
- [ ] sqlexpressible
- [ ] sqlexpression
- [ ] sqlinterpolation
- [ ] sqljsonexpressible
- [ ] sqlordering
- [ ] sqlorderingterm
- [ ] sqlrequest
- [ ] sqlselectable
- [ ] sqlselection
- [ ] sqlspecificexpressible
- [ ] sqlsubquery
- [ ] sqlsubqueryable
- [ ] tablealias
- [ ] transactionclock
- [ ] valueobservation
- [ ] valueobservationscheduler
## Unsure if necessary
@@ -251,7 +251,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -301,7 +301,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -318,7 +318,7 @@
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
INFOPLIST_FILE = Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -335,7 +335,7 @@
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
INFOPLIST_FILE = Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -232,7 +232,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -282,7 +282,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -299,6 +299,7 @@
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
INFOPLIST_FILE = Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -315,6 +316,7 @@
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
INFOPLIST_FILE = Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -187,8 +187,6 @@
56419E1024A54062004967E1 /* InflectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF024A54059004967E1 /* InflectionsTests.swift */; };
56419E1124A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF124A54059004967E1 /* ForeignKeyInfoTests.swift */; };
56419E1224A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF124A54059004967E1 /* ForeignKeyInfoTests.swift */; };
56419E1324A54062004967E1 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF224A54059004967E1 /* FoundationNSStringTests.swift */; };
56419E1424A54062004967E1 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF224A54059004967E1 /* FoundationNSStringTests.swift */; };
56419E1524A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF324A54059004967E1 /* AssociationChainRowScopesTests.swift */; };
56419E1624A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF324A54059004967E1 /* AssociationChainRowScopesTests.swift */; };
56419E1724A54062004967E1 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CF424A54059004967E1 /* PoolTests.swift */; };
@@ -411,8 +409,6 @@
56419EF024A54063004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6024A54061004967E1 /* RecordPrimaryKeyNoneTests.swift */; };
56419EF124A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6124A54062004967E1 /* StatementColumnConvertibleFetchTests.swift */; };
56419EF224A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6124A54062004967E1 /* StatementColumnConvertibleFetchTests.swift */; };
56419EF324A54063004967E1 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6224A54062004967E1 /* FoundationNSDataTests.swift */; };
56419EF424A54063004967E1 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6224A54062004967E1 /* FoundationNSDataTests.swift */; };
56419EF524A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */; };
56419EF624A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */; };
56419EF724A54063004967E1 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D6424A54062004967E1 /* ValueObservationCountTests.swift */; };
@@ -491,6 +487,8 @@
568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; };
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
56BCA6642B79249800B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA6632B79249800B3A7F8 /* Mutex.swift */; };
56BCA6652B79249800B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA6632B79249800B3A7F8 /* Mutex.swift */; };
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
@@ -591,7 +589,6 @@
56419CEF24A54059004967E1 /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = "<group>"; };
56419CF024A54059004967E1 /* InflectionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InflectionsTests.swift; sourceTree = "<group>"; };
56419CF124A54059004967E1 /* ForeignKeyInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyInfoTests.swift; sourceTree = "<group>"; };
56419CF224A54059004967E1 /* FoundationNSStringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSStringTests.swift; sourceTree = "<group>"; };
56419CF324A54059004967E1 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = "<group>"; };
56419CF424A54059004967E1 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
56419CF524A54059004967E1 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = "<group>"; };
@@ -703,7 +700,6 @@
56419D5F24A54061004967E1 /* RecordSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordSubClassTests.swift; sourceTree = "<group>"; };
56419D6024A54061004967E1 /* RecordPrimaryKeyNoneTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeyNoneTests.swift; sourceTree = "<group>"; };
56419D6124A54062004967E1 /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = "<group>"; };
56419D6224A54062004967E1 /* FoundationNSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDataTests.swift; sourceTree = "<group>"; };
56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = "<group>"; };
56419D6424A54062004967E1 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = "<group>"; };
56419D6524A54062004967E1 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = "<group>"; };
@@ -746,6 +742,7 @@
567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56BCA6632B79249800B3A7F8 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F61DEF283D484700AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
@@ -960,12 +957,10 @@
56419D6624A54062004967E1 /* FoundationDateComponentsTests.swift */,
56419D3424A5405E004967E1 /* FoundationDateTests.swift */,
567B5C242AD32A2D00629622 /* FoundationDecimalTests.swift */,
56419D6224A54062004967E1 /* FoundationNSDataTests.swift */,
56419CC924A54056004967E1 /* FoundationNSDateTests.swift */,
56419D0F24A5405B004967E1 /* FoundationNSDecimalNumberTests.swift */,
56419CE124A54058004967E1 /* FoundationNSNullTests.swift */,
56419CA924A54054004967E1 /* FoundationNSNumberTests.swift */,
56419CF224A54059004967E1 /* FoundationNSStringTests.swift */,
56419CEE24A54059004967E1 /* FoundationNSURLTests.swift */,
56419D5924A54061004967E1 /* FoundationNSUUIDTests.swift */,
56419CFC24A5405A004967E1 /* FoundationURLTests.swift */,
@@ -993,6 +988,7 @@
56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */,
56419D4424A5405F004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */,
56BCA6632B79249800B3A7F8 /* Mutex.swift */,
56419CFD24A5405A004967E1 /* NumericOverflowTests.swift */,
56419D4F24A54060004967E1 /* OrderedDictionaryTests.swift */,
56419D4524A5405F004967E1 /* PersistableRecordTests.swift */,
@@ -1326,7 +1322,6 @@
56419EEB24A54063004967E1 /* RecordPersistenceConflictPolicy.swift in Sources */,
56419E8124A54063004967E1 /* DatabaseReaderTests.swift in Sources */,
56419EDD24A54063004967E1 /* TableDefinitionTests.swift in Sources */,
56419E1324A54062004967E1 /* FoundationNSStringTests.swift in Sources */,
56419EB124A54063004967E1 /* DatabasePoolCollationTests.swift in Sources */,
56419DBF24A54062004967E1 /* UtilsTests.swift in Sources */,
56419E4324A54062004967E1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
@@ -1394,7 +1389,6 @@
56419E7B24A54062004967E1 /* DatabaseRegionTests.swift in Sources */,
56419DCD24A54062004967E1 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56419E6524A54062004967E1 /* FoundationUUIDTests.swift in Sources */,
56419EF324A54063004967E1 /* FoundationNSDataTests.swift in Sources */,
56419EC324A54063004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
5641A1AE24A540D6004967E1 /* Finished.swift in Sources */,
56419EF924A54063004967E1 /* AssociationBelongsToRowScopeTests.swift in Sources */,
@@ -1474,6 +1468,7 @@
56419D6F24A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */,
56419E7324A54062004967E1 /* TruncateOptimizationTests.swift in Sources */,
56419E4724A54062004967E1 /* RecordEditedTests.swift in Sources */,
56BCA6642B79249800B3A7F8 /* Mutex.swift in Sources */,
56419EEF24A54063004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */,
56419EA724A54063004967E1 /* CursorTests.swift in Sources */,
56419E0D24A54062004967E1 /* DatabaseQueueSchemaCacheTests.swift in Sources */,
@@ -1573,7 +1568,6 @@
56419EEC24A54063004967E1 /* RecordPersistenceConflictPolicy.swift in Sources */,
56419E8224A54063004967E1 /* DatabaseReaderTests.swift in Sources */,
56419EDE24A54063004967E1 /* TableDefinitionTests.swift in Sources */,
56419E1424A54062004967E1 /* FoundationNSStringTests.swift in Sources */,
56419EB224A54063004967E1 /* DatabasePoolCollationTests.swift in Sources */,
56419DC024A54062004967E1 /* UtilsTests.swift in Sources */,
56419E4424A54062004967E1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
@@ -1641,7 +1635,6 @@
56419E7C24A54063004967E1 /* DatabaseRegionTests.swift in Sources */,
56419DCE24A54062004967E1 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56419E6624A54062004967E1 /* FoundationUUIDTests.swift in Sources */,
56419EF424A54063004967E1 /* FoundationNSDataTests.swift in Sources */,
56419EC424A54063004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
5641A1AF24A540D6004967E1 /* Finished.swift in Sources */,
56419EFA24A54063004967E1 /* AssociationBelongsToRowScopeTests.swift in Sources */,
@@ -1721,6 +1714,7 @@
56419D7024A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */,
56419E7424A54062004967E1 /* TruncateOptimizationTests.swift in Sources */,
56419E4824A54062004967E1 /* RecordEditedTests.swift in Sources */,
56BCA6652B79249800B3A7F8 /* Mutex.swift in Sources */,
56419EF024A54063004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */,
56419EA824A54063004967E1 /* CursorTests.swift in Sources */,
56419E0E24A54062004967E1 /* DatabaseQueueSchemaCacheTests.swift in Sources */,
@@ -147,8 +147,6 @@
5641A04724A540A1004967E1 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3C24A54096004967E1 /* PoolTests.swift */; };
5641A04824A540A1004967E1 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3D24A54096004967E1 /* DatabaseValueConversionTests.swift */; };
5641A04924A540A1004967E1 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3D24A54096004967E1 /* DatabaseValueConversionTests.swift */; };
5641A04A24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3E24A54097004967E1 /* FoundationNSStringTests.swift */; };
5641A04B24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3E24A54097004967E1 /* FoundationNSStringTests.swift */; };
5641A04C24A540A1004967E1 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3F24A54097004967E1 /* AssociationHasManyThroughRowScopeTests.swift */; };
5641A04D24A540A1004967E1 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3F24A54097004967E1 /* AssociationHasManyThroughRowScopeTests.swift */; };
5641A04E24A540A1004967E1 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F4024A54097004967E1 /* RecordUniqueIndexTests.swift */; };
@@ -341,8 +339,6 @@
5641A10924A540A1004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F9D24A5409D004967E1 /* DatabaseAfterNextTransactionCommitTests.swift */; };
5641A10A24A540A1004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */; };
5641A10B24A540A1004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */; };
5641A10C24A540A1004967E1 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */; };
5641A10D24A540A1004967E1 /* FoundationNSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */; };
5641A10E24A540A1004967E1 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA024A5409E004967E1 /* AssociationParallelDecodableRecordTests.swift */; };
5641A10F24A540A1004967E1 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA024A5409E004967E1 /* AssociationParallelDecodableRecordTests.swift */; };
5641A11024A540A1004967E1 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419FA124A5409E004967E1 /* Row+FoundationTests.swift */; };
@@ -493,6 +489,8 @@
568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
56BCA6612B79248B00B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA6602B79248B00B3A7F8 /* Mutex.swift */; };
56BCA6622B79248B00B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA6602B79248B00B3A7F8 /* Mutex.swift */; };
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
@@ -573,7 +571,6 @@
56419F3B24A54096004967E1 /* FTS3TokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerTests.swift; sourceTree = "<group>"; };
56419F3C24A54096004967E1 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
56419F3D24A54096004967E1 /* DatabaseValueConversionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionTests.swift; sourceTree = "<group>"; };
56419F3E24A54097004967E1 /* FoundationNSStringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSStringTests.swift; sourceTree = "<group>"; };
56419F3F24A54097004967E1 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
56419F4024A54097004967E1 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
56419F4124A54097004967E1 /* FTS3PatternTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3PatternTests.swift; sourceTree = "<group>"; };
@@ -670,7 +667,6 @@
56419F9C24A5409D004967E1 /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = "<group>"; };
56419F9D24A5409D004967E1 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = "<group>"; };
56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDataTests.swift; sourceTree = "<group>"; };
56419FA024A5409E004967E1 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = "<group>"; };
56419FA124A5409E004967E1 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = "<group>"; };
56419FA324A5409E004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
@@ -749,6 +745,7 @@
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56BCA6602B79248B00B3A7F8 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F61DF5283D4AB100AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
@@ -964,12 +961,10 @@
56419F2524A54095004967E1 /* FoundationDateComponentsTests.swift */,
56419F1124A54093004967E1 /* FoundationDateTests.swift */,
568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */,
56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */,
56419FB224A5409F004967E1 /* FoundationNSDateTests.swift */,
56419F8124A5409B004967E1 /* FoundationNSDecimalNumberTests.swift */,
56419F5224A54098004967E1 /* FoundationNSNullTests.swift */,
56419F2624A54095004967E1 /* FoundationNSNumberTests.swift */,
56419F3E24A54097004967E1 /* FoundationNSStringTests.swift */,
56419FB524A5409F004967E1 /* FoundationNSURLTests.swift */,
56419F7D24A5409B004967E1 /* FoundationNSUUIDTests.swift */,
56419FB824A5409F004967E1 /* FoundationURLTests.swift */,
@@ -997,6 +992,7 @@
56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */,
56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */,
56BCA6602B79248B00B3A7F8 /* Mutex.swift */,
56419F0824A54093004967E1 /* NumericOverflowTests.swift */,
56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */,
56419F1A24A54094004967E1 /* PersistableRecordTests.swift */,
@@ -1345,7 +1341,6 @@
5641A18C24A540C7004967E1 /* ValueObservationPublisherTests.swift in Sources */,
5641A13624A540A1004967E1 /* DatabaseSnapshotTests.swift in Sources */,
56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */,
5641A04A24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */,
5641A17824A540C7004967E1 /* Next.swift in Sources */,
5691D97227257C930021D540 /* AvailableElements.swift in Sources */,
5641A09624A540A1004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
@@ -1479,6 +1474,7 @@
5641A14E24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */,
5641A0C024A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */,
5641A08024A540A1004967E1 /* ResultCodeTests.swift in Sources */,
56BCA6612B79248B00B3A7F8 /* Mutex.swift in Sources */,
5641A12C24A540A1004967E1 /* FTS3TableBuilderTests.swift in Sources */,
5641A07424A540A1004967E1 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
5641A0DA24A540A1004967E1 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
@@ -1505,7 +1501,6 @@
5641A15C24A540A2004967E1 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
5641A03024A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
5641A00224A540A1004967E1 /* PersistableRecordTests.swift in Sources */,
5641A10C24A540A1004967E1 /* FoundationNSDataTests.swift in Sources */,
5641A14224A540A2004967E1 /* DatabasePoolReadOnlyTests.swift in Sources */,
5641A10824A540A1004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
5641A11C24A540A1004967E1 /* RowCopiedFromStatementTests.swift in Sources */,
@@ -1592,7 +1587,6 @@
5641A18D24A540C7004967E1 /* ValueObservationPublisherTests.swift in Sources */,
5641A13724A540A2004967E1 /* DatabaseSnapshotTests.swift in Sources */,
56419FCB24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */,
5641A04B24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */,
5641A17924A540C7004967E1 /* Next.swift in Sources */,
5691D97327257C930021D540 /* AvailableElements.swift in Sources */,
5641A09724A540A1004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
@@ -1726,6 +1720,7 @@
5641A14F24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */,
5641A0C124A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */,
5641A08124A540A1004967E1 /* ResultCodeTests.swift in Sources */,
56BCA6622B79248B00B3A7F8 /* Mutex.swift in Sources */,
5641A12D24A540A1004967E1 /* FTS3TableBuilderTests.swift in Sources */,
5641A07524A540A1004967E1 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
5641A0DB24A540A1004967E1 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
@@ -1752,7 +1747,6 @@
5641A15D24A540A2004967E1 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
5641A03124A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
5641A00324A540A1004967E1 /* PersistableRecordTests.swift in Sources */,
5641A10D24A540A1004967E1 /* FoundationNSDataTests.swift in Sources */,
5641A14324A540A2004967E1 /* DatabasePoolReadOnlyTests.swift in Sources */,
5641A10924A540A1004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
5641A11D24A540A1004967E1 /* RowCopiedFromStatementTests.swift in Sources */,
@@ -21,6 +21,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
// MARK: -
@MainActor
func testReadPublisher() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -44,7 +45,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
@@ -127,6 +128,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
// frame #70: 0x0000000100002f07 xctest`main + 210
// frame #71: 0x00007fff72311cc9 libdyld.dylib`start + 1
// frame #72: 0x00007fff72311cc9 libdyld.dylib`start + 1
@MainActor
func testReadPublisherError() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -149,13 +151,14 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() }
#endif
}
// MARK: -
@MainActor
func testReadPublisherIsAsynchronous() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -189,13 +192,14 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
// MARK: -
@MainActor
func testReadPublisherDefaultScheduler() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -229,13 +233,14 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
// MARK: -
@MainActor
func testReadPublisherCustomScheduler() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -270,13 +275,14 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
// MARK: -
@MainActor
func testReadPublisherIsReadonly() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -298,7 +304,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() }
#endif
}
@@ -19,6 +19,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord {
class DatabaseRegionObservationPublisherTests : XCTestCase {
@MainActor
func testChangesNotifications() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
@@ -60,6 +61,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase {
//
// TODO: do the same, but asynchronously. If this is too hard, update the
// public API so that users can easily do it.
@MainActor
func testPrependInitialDatabaseSync() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Combine is not available")
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more