Compare commits

...
Author SHA1 Message Date
Gwendal Roué 7ac91619cb [BREAKING] databaseDateDecodingStrategy depends on the column 2024-07-30 08:43:28 +02:00
Gwendal Roué 8a680a9719 [BREAKING] databaseDataDecodingStrategy depends on the column 2024-07-30 08:43:28 +02:00
Gwendal Roué 919dad7ac1 [BREAKING] databaseUUIDEncodingStrategy depends on the column 2024-07-30 08:43:28 +02:00
Gwendal Roué fba8f86914 [BREAKING] databaseDateEncodingStrategy depends on the column 2024-07-30 08:43:28 +02:00
Gwendal Roué 2767dd5456 [BREAKING] databaseDataEncodingStrategy depends on the column 2024-07-30 08:43:28 +02:00
Gwendal Roué 662daabc32 Redo the watchOS demo with SwiftUI 2024-07-28 13:59:38 +02:00
Gwendal Roué e3009b1555 Fix compiler warnings in demo app 2024-07-28 13:59:38 +02:00
Gwendal Roué 78c794e140 Fix compiler warnings
Workaround https://github.com/swiftlang/swift/issues/75522
2024-07-28 13:59:38 +02:00
Gwendal Roué a2aac03510 Fix compiler warnings
Workaround https://github.com/swiftlang/swift/issues/75521
2024-07-28 13:59:38 +02:00
Gwendal Roué a6e05817b6 Enable InferSendableFromCaptures in tests 2024-07-28 13:59:38 +02:00
Gwendal Roué 738da3852c Fix concurrency warnings 2024-07-28 13:59:38 +02:00
Gwendal Roué 5cf3b5d44b ValueObservation requires Sendable values
This is required for handleEvents to do whatever it wants with observed values.
2024-07-28 13:59:38 +02:00
Gwendal Roué 7b075e6b3a DispatchQueue.asyncSending 2024-07-28 13:59:38 +02:00
Gwendal Roué f900990c5a TODO 2024-07-28 13:59:38 +02:00
Gwendal Roué b4ff52fb7d DatabaseRegionObservation is Sendable 2024-07-28 13:59:38 +02:00
Gwendal Roué ce63cdfa60 AsyncValueObservation is Sendable 2024-07-28 13:59:38 +02:00
Gwendal Roué 48ad10aea8 AssociationAggregate is Sendable 2024-07-28 13:59:38 +02:00
Gwendal Roué b60da6b8c7 Delete obsolete Xcode/SPM file
It refers to CSQLite, and I could not have Xcode refresh it after I renamed CSQLite to GRDBSQLite: this file is obsolete.
2024-07-28 13:59:38 +02:00
Gwendal Roué bf211e9ae3 Rename CSQLite to GRDBSQLite
Fix #1528
2024-07-28 13:59:38 +02:00
Gwendal Roué 94127bdca2 Disable Swiftlint rule non_optional_string_data_conversion, too many false positives 2024-07-28 13:59:38 +02:00
Gwendal Roué 19c3de96dd Fix Swiftlint warnings 2024-07-28 13:59:38 +02:00
Gwendal Roué 8df18fb82b Document that async methods can throw CancellationError 2024-07-28 13:59:38 +02:00
Gwendal Roué 5fad4fe028 Fix DocC warnings 2024-07-28 13:59:38 +02:00
Gwendal Roué dcdcbf39e0 TODO 2024-07-28 13:59:38 +02:00
Gwendal Roué 3f1e37e3a6 Fix Xcode 15.4 compilation error 2024-07-28 13:59:38 +02:00
Gwendal Roué 0d989fa96e TODO 2024-07-28 13:59:38 +02:00
Gwendal Roué 10c9d31149 DatabaseReader async methods support Task cancellation 2024-07-28 13:59:38 +02:00
Gwendal Roué a52265016a DatabaseWriter async methods support Task cancellation 2024-07-28 13:59:38 +02:00
Gwendal Roué 737cb14996 SerializedDatabase support for async db access with support for Task cancellation 2024-07-28 13:59:38 +02:00
Gwendal Roué 4ddf4bca5f Database support for cancellation 2024-07-27 16:37:34 +02:00
Gwendal Roué fa92ba6cd5 Vendor AsyncSemaphore
Source: https://github.com/groue/Semaphore/blob/0.0.8/Sources/Semaphore/AsyncSemaphore.swift
2024-07-27 16:37:34 +02:00
Gwendal Roué 9692c4458d TODO 2024-07-27 16:37:34 +02:00
Gwendal Roué 43d163abe5 [BREAKING] Reorganize ValueObservation schedulers
# Conflicts:
#	GRDB/ValueObservation/ValueObservationScheduler.swift
2024-07-27 16:37:33 +02:00
Gwendal Roué 08733108b4 ValueObservation a ValueReducer, not a _ValueReducer 2024-07-27 16:37:33 +02:00
Gwendal Roué 668cbc2281 Swiftlint: disable the colon rule that can't deal properly with the ternary operator 2024-07-27 16:37:33 +02:00
Gwendal Roué 5701bef497 Enable SE-0418 in demo apps 2024-07-27 16:37:33 +02:00
Gwendal Roué db6da72bec Xcode 15.4 recommended settings, fix ENABLE_MODULE_VERIFIER errors 2024-07-27 16:37:33 +02:00
Gwendal Roué c508729dde TODO 2024-07-27 16:37:33 +02:00
Gwendal Roué e950955b25 StrictConcurrency/tests: upgrade demo apps for strict concurrency 2024-07-27 16:37:33 +02:00
Gwendal Roué f4d9c97478 StrictConcurrency/tests: enable strict concurrency checks in other test projects 2024-07-27 16:37:33 +02:00
Gwendal Roué 0e18dae266 StrictConcurrency/tests: enable strict concurrency checks in SQLCipher tests 2024-07-27 16:37:33 +02:00
Gwendal Roué 7e2d096dca StrictConcurrency: enable strict concurrency checks in demo apps 2024-07-27 16:37:33 +02:00
Gwendal Roué c1de146a57 StrictConcurrency/tests: avoid warning about non-Sendable DispatchSpecificKey 🙄 2024-07-27 16:37:33 +02:00
Gwendal Roué a12211bc28 StrictConcurrency/tests: fix ValueObservationRecorder warnings 2024-07-27 16:37:33 +02:00
Gwendal Roué a45ba5a6e0 StrictConcurrency/tests: refactor busy handler tests 2024-07-27 16:37:33 +02:00
Gwendal Roué 3e57ce9e98 StrictConcurrency/tests: capture values instead of non-Sendable self 2024-07-27 16:37:33 +02:00
Gwendal Roué 2e10969634 StrictConcurrency/tests: introduce TestDatabaseBuilder that can connect from Sendable closures 2024-07-27 16:37:33 +02:00
Gwendal Roué afcac0102f ⚠️ EXPERIMENTAL - SE-0430 sending parameter and result values 2024-07-27 16:37:33 +02:00
Gwendal Roué bbb1a73672 StrictConcurrency/tests: use a single and Sendable test TextOutputStream 2024-07-27 16:37:33 +02:00
Gwendal Roué 5f8b39b7e6 StrictConcurrency: ValueObservation.print cautiously uses its stream argument 2024-07-27 16:37:33 +02:00
Gwendal Roué 2947b3d78b StrictConcurrency/tests: ValueObservationRecorder is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué c3dab1c2da StrictConcurrency: databaseDecodingUserInfo and databaseEncodingUserInfo must be declared as a computed property 2024-07-27 16:37:33 +02:00
Gwendal Roué 1544bd1158 StrictConcurrency: FetchableRecord.databaseDecodingUserInfo must be declared as a computed property 2024-07-27 16:37:33 +02:00
Gwendal Roué c4dfa3d2ab StrictConcurrency/tests: fix warning about mutable state 2024-07-27 16:37:33 +02:00
Gwendal Roué b06aaee438 Association is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 09182b2ad7 StrictConcurrency/tests: fix warnings about concurrently-executed functions 2024-07-27 16:37:33 +02:00
Gwendal Roué 24d232aafd StrictConcurrency: TableRecord.databaseSelection must be declared as a computed property
An alternative would have been to make SQLSelectable conform to Sendable. But this makes it harder for users to provide SQLSelectable types.
2024-07-27 16:37:33 +02:00
Gwendal Roué 1291bd7dea StrictConcurrency/tests: fix warnings about mutable state 2024-07-27 16:37:33 +02:00
Gwendal Roué cd73fdc7c3 ⚠️ Enable SE-0418
TODO: Check if this works with Xcode 15.4?
2024-07-27 16:37:33 +02:00
Gwendal Roué f175e3f384 StrictConcurrency/tests: Use a mutex for tracing allocations and deallocations 2024-07-27 16:37:33 +02:00
Gwendal Roué 45fd17028c StrictConcurrency/tests: DispatchQueue.concurrentPerform wants Sendable closures 2024-07-27 16:37:33 +02:00
Gwendal Roué e28558334f StrictConcurrency/tests: XCTestCase.waitForExpectations is main-actor isolated 2024-07-27 16:37:33 +02:00
Gwendal Roué 75f67949ea StrictConcurrency/tests: cleanup test SQL traces 2024-07-27 16:37:33 +02:00
Gwendal Roué 9e3e4158ff StrictConcurrency/tests: fix warning in CombineExpectations 2024-07-27 16:37:33 +02:00
Gwendal Roué 0f840e0413 Document TOOLCHAIN usage 2024-07-27 16:37:33 +02:00
Gwendal Roué 6536ba404f TODO 2024-07-27 16:37:33 +02:00
Gwendal Roué 5f26a7ac01 Replace Mutex.value with load() and store(_:)
... and fix logic bugs on the way.

Inspired by https://forums.swift.org/t/se-0433-synchronous-mutual-exclusion-lock/71174/58

Fixed bugs follow this pattern: https://forums.swift.org/t/se-0433-synchronous-mutual-exclusion-lock/71174/77
2024-07-27 16:37:33 +02:00
Gwendal Roué dd47a7b8b3 Extract PersistenceContainer in its own file 2024-07-27 16:37:33 +02:00
Gwendal Roué d5c0044342 StrictConcurrency: fix warning in TableRecord.request(for:) 2024-07-27 16:37:33 +02:00
Gwendal Roué 50eefa8c0f [BREAKING] PersistenceContainer is Sendable
The breaking change is that the container now only stores DatabaseValue: user can't extract the value that was previously stored.
2024-07-27 16:37:33 +02:00
Gwendal Roué c0838cf90f Improve CaseInsensitiveIdentifier documentation 2024-07-27 16:37:33 +02:00
Gwendal Roué 372affbe5b StrictConcurrency: SQLQualifiedRelation is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 91e1ca4bae Prefer Data over NSData 2024-07-27 16:37:33 +02:00
Gwendal Roué 3f61908e7e StrictConcurrency: Convert non-sendable to Sendable values before building database promises
🥳 We don't need SQLSelectable, SQLExpressible and SQLOrderingTerm to be Sendable. This is important because it allows non-Sendable types to be used in request definitions. For example: NSData, NSString (not expected to be used frequently, but users are wild).
2024-07-27 16:37:33 +02:00
Gwendal Roué 57516c5e38 StrictConcurrency: SQLAssociationCondition is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 5d66407368 StrictConcurrency: fix warning about ISO8601DateFormatter 2024-07-27 16:37:33 +02:00
Gwendal Roué 20d948b4d2 StrictConcurrency: fix warning about defaultDatabaseTableNameCache 2024-07-27 16:37:33 +02:00
Gwendal Roué 8346e69757 StrictConcurrency: ValueObservation.map requires a Sendable closure 2024-07-27 16:37:33 +02:00
Gwendal Roué 135de3c56e ⚠️ StrictConcurrency: fix warnings about the transfer of non-sendable values
We use unsafe constructs that we'll be able to replace with transferring parameters when the feature ships in the language: https://forums.swift.org/t/how-can-i-use-region-based-isolation/71426/5
2024-07-27 16:37:33 +02:00
Gwendal Roué 87fb90ef97 StrictConcurrency: FetchRequestEraser is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 6898d8c915 StrictConcurrency: AdaptedFetchRequest.adapter is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué aad170330a StrictConcurrency: SharedValueObservation is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 8b49360af1 StrictConcurrency: ValueObservation change callback is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 93f6f98261 StrictConcurrency: ValueObservation is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 67473154f9 StrictConcurrency: DatabasePublishers.ValueSubscription is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 8d137a2d16 StrictConcurrency: ValueObservation requires Sendable fetching closures 2024-07-27 16:37:33 +02:00
Gwendal Roué 45539583a8 Mutex.wasNeeded convenience 2024-07-27 16:37:33 +02:00
Gwendal Roué 87b9db65d1 StrictConcurrency: ValueConcurrentObserver is Sendable
Required for DatabaseCancellable conformance
2024-07-27 16:37:33 +02:00
Gwendal Roué 5465d056ab StrictConcurrency: refactor ValueReducer and extract its Sendable fetching facet 2024-07-27 16:37:33 +02:00
Gwendal Roué ff2a75489d StrictConcurrency: ValueWriteOnlyObserver is Sendable
Required for DatabaseCancellable conformance
2024-07-27 16:37:33 +02:00
Gwendal Roué b4677dede4 StrictConcurrency: DatabaseRegionConvertible is Sendable
A ValueObservation will use such an object from database readers, writers, and the main thread: they must support all isolation domains.
2024-07-27 16:37:33 +02:00
Gwendal Roué 8f486a5e41 StrictConcurrency: fix warning about AnyDatabaseCancellable initializer 2024-07-27 16:37:33 +02:00
Gwendal Roué 484224c654 StrictConcurrency: fix warning about Inflections.default 2024-07-27 16:37:33 +02:00
Gwendal Roué 7f5205ef8c Rename ReadWriteBox to ReadWriteLock
... and make it conditionally Sendable, and it is no longer a property wrapper.

It is conditionally Sendable because we can't use the techniques of the future standard Mutex (SE-0433 Synchronous Mutual Exclusion Lock, https://github.com/apple/swift-evolution/blob/main/proposals/0433-mutex.md).

It is no longer a property wrapper because the Swift compiler can perform strict concurrency checks through a `var` property.
2024-07-27 16:37:33 +02:00
Gwendal Roué 99715892e7 StrictConcurrency: fix warning about StatementArgumentsSink.literalValues 2024-07-27 16:37:33 +02:00
Gwendal Roué e022c35b49 StrictConcurrency: OrderedDictionary is conditionally Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 5a2c15b82e StrictConcurrency: DatabasePromise initializer requires a Sendable value 2024-07-27 16:37:33 +02:00
Gwendal Roué 88539df543 StrictConcurrency: use a Sendable strong reference 2024-07-27 16:37:33 +02:00
Gwendal Roué 991d2c8bbc StrictConcurrency: UIApplication is MainActor-isolated 2024-07-27 16:37:33 +02:00
Gwendal Roué 3995bfdbec StrictConcurrency: workaround warning about UIApplication.xxxNotification 2024-07-27 16:37:33 +02:00
Gwendal Roué 6aa43ded3c Enable strict concurrency checks 2024-07-27 16:37:33 +02:00
Gwendal Roué b11c5dd25b DatabaseCursor has a primary associated type 2024-07-27 16:37:33 +02:00
Gwendal Roué a474a674b4 Project organization 2024-07-27 16:37:33 +02:00
Gwendal Roué 6c73b1c5c8 Cleanup ValueReducer 2024-07-27 16:37:33 +02:00
Gwendal Roué 2ce8a6191d Split Row.swift into focused files 2024-07-27 16:37:33 +02:00
Gwendal Roué eed2ae03ae TODO 2024-07-27 16:37:33 +02:00
Gwendal Roué ac33856f31 SQL is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 9545bf70e2 SQLRelation is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué f2b0b1869c ⚠️ Make TableAlias Sendable even if it is not yet. 2024-07-27 16:37:33 +02:00
Gwendal Roué 05899228fd DatabasePromise is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 735175e902 FTS5 tokenizers don't need to be Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 9b2466c2aa Fix a concurrency warning 2024-07-27 16:37:33 +02:00
Gwendal Roué cfd4a71efa writePublisher(updates:thenRead:) requires a Sendable Value
... But I don't know if region-based isolation and SE-0430 can relax this constraint or not.
2024-07-27 16:37:33 +02:00
Gwendal Roué e6a7d7dad4 Fix concurrency warning on SQLITE_TRANSIENT 2024-07-27 16:37:33 +02:00
Gwendal Roué 3b593d7649 ValueObservation.handleEvents accept Sendable closures 2024-07-27 16:37:33 +02:00
Gwendal Roué 3476b6348a ValueObservationScheduler async access requires a Sendable closure 2024-07-27 16:37:33 +02:00
Gwendal Roué 7d7dc8ea72 SerializedDatabase async access requires a Sendable closure 2024-07-27 16:37:33 +02:00
Gwendal Roué 7fd34012b4 WALSnapshotTransaction is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 2aabc4c10e OnDemandFuture fulfill is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué f13b2d2eb4 Pool is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 57a86a0e2a ReadWriteBox is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 40090dbe00 Fix concurrency warnings with DispatchSpecificKey 2024-07-27 16:37:33 +02:00
Gwendal Roué f362518dd6 LogErrorFunction is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 4d9d67dd67 DatabaseCollation is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 8429eb68dd ValueObservationScheduler is Sendable 2024-07-27 16:37:33 +02:00
Gwendal Roué 50285f4832 Record can't be made Sendable
... so that subclasses do not have to be sendable
2024-07-27 16:37:32 +02:00
Gwendal Roué d138af2637 RowAdapter is Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué b26e9709e7 FilterCursor can't be made Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué dc0be3a10d Database publishers can't be made Sendable
... because they wrap base publishers that are not :-/
2024-07-27 16:37:32 +02:00
Gwendal Roué 22114ad433 DatabaseMigrator is Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué 6e691fe71d DatabaseFunction is Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué 05f7d3c8d4 [BREAKING] Remove DatabaseFuture and concurrentRead
That's one less DispatchSemaphore. We don't need this method anymore.
2024-07-27 16:37:32 +02:00
Gwendal Roué 264d7fb52e Coding strategies are Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué 54ffb21fb8 Configuration is Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué f7dc72a5f3 TransactionClock is Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué e0d8e20bef BusyCallback and BusyMode are Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué 04d8c357b5 Tests need a Mutex too 2024-07-27 16:37:32 +02:00
Gwendal Roué 00ccab06bd 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-07-27 16:37:32 +02:00
Gwendal Roué 2f93f00b41 DatabaseCancellable is Sendable 2024-07-27 16:37:32 +02:00
Gwendal Roué 2661ff4690 [BREAKING] Remove Configuration.defaultTransactionKind
GRDB know defaults read-only transactions to DEFERRED, and write transactions to IMMEDIATE. See https://github.com/groue/GRDB.swift/issues/1483 for some context.
2024-07-27 16:37:32 +02:00
Gwendal Roué 2297c8f432 [BREAKING] Bump requirements: watchOS 7
Rationale: https://github.com/groue/GRDB.swift/issues/1472#issuecomment-1960696836
2024-07-27 16:37:32 +02:00
Gwendal Roué 679d6463fd [BREAKING] Stop exporting SQLite 2024-07-27 16:37:32 +02:00
Gwendal Roué 62b4477490 TODO 2024-07-27 16:37:32 +02:00
Gwendal Roué 83c0e6432b [BREAKING] Remove AsyncValueObservation does not need any scheduler 2024-07-27 16:37:32 +02:00
Gwendal Roué 32f41472b6 [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-07-27 16:37:32 +02:00
Gwendal Roué 3685d6d505 Remove ill-advised TODO
This would force users to force-unwrap their custom `ColumnType(rawValue: "WHATEVER")!`
2024-07-27 16:37:32 +02:00
Gwendal Roué 5ab166b9c3 [BREAKING] Bump requirements: Swift 5.10, Xcode 15.3, iOS 12, tvOS 12 2024-07-27 16:37:32 +02:00
327 changed files with 10722 additions and 8614 deletions

No files matched your search

@@ -1,134 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1410"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB_GRDBTests"
BuildableName = "GRDB_GRDBTests"
BlueprintName = "GRDB_GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB"
BuildableName = "GRDB"
BlueprintName = "GRDB"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB-dynamic"
BuildableName = "GRDB-dynamic"
BlueprintName = "GRDB-dynamic"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDBTests"
BuildableName = "GRDBTests"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CSQLite"
BuildableName = "CSQLite"
BlueprintName = "CSQLite"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDBTests"
BuildableName = "GRDBTests"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB_GRDBTests"
BuildableName = "GRDB_GRDBTests"
BlueprintName = "GRDB_GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -232,7 +232,7 @@
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 1250;
LastUpgradeCheck = 1200;
LastUpgradeCheck = 1540;
TargetAttributes = {
56026C9725B8A7D000D1DF3F = {
CreatedOnToolsVersion = 12.3;
@@ -425,6 +425,7 @@
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -446,6 +447,8 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES;
};
name = Debug;
};
@@ -486,6 +489,7 @@
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -500,6 +504,8 @@
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "1540"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
import Foundation
import GRDB
import os.log
@preconcurrency import os.log
/// A database of players.
///
@@ -232,7 +232,7 @@
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 1250;
LastUpgradeCheck = 1200;
LastUpgradeCheck = 1540;
TargetAttributes = {
56026C9725B8A7D000D1DF3F = {
CreatedOnToolsVersion = 12.3;
@@ -425,6 +425,7 @@
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -446,6 +447,8 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES;
};
name = Debug;
};
@@ -486,6 +489,7 @@
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -500,6 +504,8 @@
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "1540"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -41,7 +41,7 @@ struct AppDatabase {
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
private static let sqlLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
@@ -62,12 +62,12 @@ extension AppDatabase {
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
db.trace { event in
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
sqlLogger.debug("\(String(describing: event))")
}
}
}
@@ -83,6 +83,9 @@ extension AppDatabase {
}
}
// Safe according to <https://forums.developer.apple.com/forums/thread/747816>
extension Logger: @unchecked Sendable { }
// MARK: - Database Migrations
extension AppDatabase {
@@ -17,11 +17,6 @@ extension AppDatabase {
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
@@ -34,18 +29,7 @@ extension AppDatabase {
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Prepare the database with test fixtures if requested
if CommandLine.arguments.contains("-fixedTestData") {
try appDatabase.createPlayersForUITests()
} else {
// Otherwise, populate the database if it is empty, for better
// demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
}
return appDatabase
return try AppDatabase(dbPool)
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
@@ -1,18 +0,0 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1,28 +0,0 @@
{
"assets" : [
{
"idiom" : "watch",
"filename" : "Circular.imageset",
"role" : "circular"
},
{
"idiom" : "watch",
"filename" : "Extra Large.imageset",
"role" : "extra-large"
},
{
"idiom" : "watch",
"filename" : "Modular.imageset",
"role" : "modular"
},
{
"idiom" : "watch",
"filename" : "Utilitarian.imageset",
"role" : "utilitarian"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1,18 +0,0 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1,18 +0,0 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1,18 +0,0 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1,48 +0,0 @@
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompletedWithSnapshot(false)
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
@@ -1,36 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>GRDBDemoWatchOS Extension</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
</dict>
<key>WKExtensionDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).ExtensionDelegate</string>
</dict>
</plist>
@@ -1,15 +0,0 @@
import WatchKit
import Foundation
import GRDB
class InterfaceController: WKInterfaceController {
@IBOutlet var versionLabel: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
let sqliteVersion = String(cString: sqlite3_libversion(), encoding: .utf8)
versionLabel.setText(sqliteVersion)
}
}
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,13 @@
{
"images" : [
{
"idiom" : "universal",
"platform" : "watchos",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,29 @@
import SwiftUI
import GRDB
struct ContentView: View {
@State var sqliteVersion = ""
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("SQLite Version")
Text(sqliteVersion)
}
.padding()
.onAppear {
do {
sqliteVersion = try DatabaseQueue().read { db in
try String.fetchOne(db, sql: "SELECT SQLITE_VERSION()")!
}
} catch {
sqliteVersion = String(describing: error)
}
}
}
}
#Preview {
ContentView()
}
@@ -0,0 +1,10 @@
import SwiftUI
@main
struct GRDBDemoWatchOS_Watch_AppApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,55 +0,0 @@
{
"images" : [
{
"size" : "24x24",
"idiom" : "watch",
"scale" : "2x",
"role" : "notificationCenter",
"subtype" : "38mm"
},
{
"size" : "27.5x27.5",
"idiom" : "watch",
"scale" : "2x",
"role" : "notificationCenter",
"subtype" : "42mm"
},
{
"size" : "29x29",
"idiom" : "watch",
"role" : "companionSettings",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "watch",
"role" : "companionSettings",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "watch",
"scale" : "2x",
"role" : "appLauncher",
"subtype" : "38mm"
},
{
"size" : "86x86",
"idiom" : "watch",
"scale" : "2x",
"role" : "quickLook",
"subtype" : "38mm"
},
{
"size" : "98x98",
"idiom" : "watch",
"scale" : "2x",
"role" : "quickLook",
"subtype" : "42mm"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="12118" systemVersion="16E195" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="AgC-eL-Hgc">
<device id="watch38" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="watchOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="12029"/>
</dependencies>
<scenes>
<!--Interface Controller-->
<scene sceneID="aou-V4-d1y">
<objects>
<controller id="AgC-eL-Hgc" customClass="InterfaceController" customModule="GRDBDemoWatchOS" customModuleProvider="target">
<items>
<group width="1" alignment="left" verticalAlignment="center" layout="vertical" id="tkk-aG-QQF">
<items>
<label alignment="center" text="SQLite version" id="dGA-xX-x8V"/>
<label alignment="center" text="Label" id="whi-N6-h8U"/>
</items>
</group>
</items>
<connections>
<outlet property="versionLabel" destination="whi-N6-h8U" id="5xN-Gj-yNt"/>
</connections>
</controller>
</objects>
</scene>
</scenes>
</document>
@@ -1,33 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>GRDBDemoiOS</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
</plist>
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objectVersion = 70;
objects = {
/* Begin PBXBuildFile section */
@@ -12,15 +12,6 @@
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; };
567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD01E926430002582E0 /* InterfaceController.swift */; };
568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; };
568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; };
568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */; };
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */; };
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
@@ -29,6 +20,8 @@
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; };
56F1E5782C55338D00E5C801 /* GRDBDemoWatchOS Watch App.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 56F1E56A2C55338C00E5C801 /* GRDBDemoWatchOS Watch App.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
56F1E57F2C553C6500E5C801 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */; };
/* End PBXBuildFile section */
@@ -47,13 +40,6 @@
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDB;
};
5642253329A2391900D714BF /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDB;
};
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
@@ -68,56 +54,23 @@
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
56F1E5752C55338D00E5C801 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 568E5FCA1E926430002582E0;
remoteInfo = "GRDBDemoWatchOS Extension";
remoteGlobalIDString = 56F1E5692C55338C00E5C801;
remoteInfo = "GRDBDemoWatchOS Watch App";
};
568E5FD71E926430002582E0 /* PBXContainerItemProxy */ = {
56F1E57D2C553C5F00E5C801 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 568E5FBE1E926430002582E0;
remoteInfo = GRDBDemoWatchOS;
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDB;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
568E5FE11E926430002582E0 /* Embed Watch Content */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "$(CONTENTS_FOLDER_PATH)/Watch";
dstSubfolderSpec = 16;
files = (
568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */,
);
name = "Embed Watch Content";
runOnlyForDeploymentPostprocessing = 0;
};
568E5FE81E926547002582E0 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
56B036621E8D9FB1003B6DA4 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
@@ -129,6 +82,17 @@
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
56F1E5772C55338D00E5C801 /* Embed Watch Content */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "$(CONTENTS_FOLDER_PATH)/Watch";
dstSubfolderSpec = 16;
files = (
56F1E5782C55338D00E5C801 /* GRDBDemoWatchOS Watch App.app in Embed Watch Content */,
);
name = "Embed Watch Content";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
@@ -137,15 +101,6 @@
56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
56185BF425B80B8900B9C30F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56185C0625B80CEC00B9C30F /* PlayerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
568E5FC61E926430002582E0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "GRDBDemoWatchOS Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
568E5FD01E926430002582E0 /* InterfaceController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InterfaceController.swift; sourceTree = "<group>"; };
568E5FD21E926430002582E0 /* ExtensionDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExtensionDelegate.swift; sourceTree = "<group>"; };
568E5FD41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
568E5FD61E926430002582E0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoiOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
56B0360B1E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
@@ -157,9 +112,14 @@
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
56F1E56A2C55338C00E5C801 /* GRDBDemoWatchOS Watch App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "GRDBDemoWatchOS Watch App.app"; sourceTree = BUILT_PRODUCTS_DIR; };
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
56F1E56B2C55338C00E5C801 /* GRDBDemoWatchOS Watch App */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = "GRDBDemoWatchOS Watch App"; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
56185BED25B80B8900B9C30F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
@@ -168,14 +128,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FC81E926430002582E0 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56B036001E8D9EBE003B6DA4 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -184,6 +136,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
56F1E5672C55338C00E5C801 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56F1E57F2C553C6500E5C801 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -213,35 +173,13 @@
name = Frameworks;
sourceTree = "<group>";
};
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
isa = PBXGroup;
children = (
568E5FC11E926430002582E0 /* Interface.storyboard */,
568E5FC41E926430002582E0 /* Assets.xcassets */,
568E5FC61E926430002582E0 /* Info.plist */,
);
path = GRDBDemoWatchOS;
sourceTree = "<group>";
};
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */ = {
isa = PBXGroup;
children = (
568E5FD01E926430002582E0 /* InterfaceController.swift */,
568E5FD21E926430002582E0 /* ExtensionDelegate.swift */,
568E5FD41E926430002582E0 /* Assets.xcassets */,
568E5FD61E926430002582E0 /* Info.plist */,
);
path = "GRDBDemoWatchOS Extension";
sourceTree = "<group>";
};
56B035FA1E8D9EBE003B6DA4 = {
isa = PBXGroup;
children = (
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */,
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */,
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */,
56F1E56B2C55338C00E5C801 /* GRDBDemoWatchOS Watch App */,
56B036041E8D9EBE003B6DA4 /* Products */,
56606D1F2355938A00185962 /* Frameworks */,
);
@@ -251,9 +189,8 @@
isa = PBXGroup;
children = (
56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */,
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */,
568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */,
56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */,
56F1E56A2C55338C00E5C801 /* GRDBDemoWatchOS Watch App.app */,
);
name = Products;
sourceTree = "<group>";
@@ -313,42 +250,6 @@
productReference = 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
buildPhases = (
568E5FBD1E926430002582E0 /* Resources */,
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
568E5FCE1E926430002582E0 /* PBXTargetDependency */,
);
name = GRDBDemoWatchOS;
productName = GRDBDemoWatchOS;
productReference = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */;
productType = "com.apple.product-type.application.watchapp2";
};
568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */ = {
isa = PBXNativeTarget;
buildConfigurationList = 568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */;
buildPhases = (
568E5FC71E926430002582E0 /* Sources */,
568E5FC81E926430002582E0 /* Frameworks */,
568E5FC91E926430002582E0 /* Resources */,
568E5FE81E926547002582E0 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
5642253429A2391900D714BF /* PBXTargetDependency */,
);
name = "GRDBDemoWatchOS Extension";
productName = "GRDBDemoWatchOS Extension";
productReference = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */;
productType = "com.apple.product-type.watchkit2-extension";
};
56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56B036151E8D9EBE003B6DA4 /* Build configuration list for PBXNativeTarget "GRDBDemoiOS" */;
@@ -357,27 +258,51 @@
56B036001E8D9EBE003B6DA4 /* Frameworks */,
56B036011E8D9EBE003B6DA4 /* Resources */,
56B036621E8D9FB1003B6DA4 /* Embed Frameworks */,
568E5FE11E926430002582E0 /* Embed Watch Content */,
56F1E5772C55338D00E5C801 /* Embed Watch Content */,
);
buildRules = (
);
dependencies = (
5642253029A2390800D714BF /* PBXTargetDependency */,
568E5FD81E926430002582E0 /* PBXTargetDependency */,
56F1E5762C55338D00E5C801 /* PBXTargetDependency */,
);
name = GRDBDemoiOS;
productName = GRDBDemoiOS;
productReference = 56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */;
productType = "com.apple.product-type.application";
};
56F1E5692C55338C00E5C801 /* GRDBDemoWatchOS Watch App */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56F1E5792C55338D00E5C801 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Watch App" */;
buildPhases = (
56F1E5662C55338C00E5C801 /* Sources */,
56F1E5672C55338C00E5C801 /* Frameworks */,
56F1E5682C55338C00E5C801 /* Resources */,
);
buildRules = (
);
dependencies = (
56F1E57E2C553C5F00E5C801 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
56F1E56B2C55338C00E5C801 /* GRDBDemoWatchOS Watch App */,
);
name = "GRDBDemoWatchOS Watch App";
packageProductDependencies = (
);
productName = "GRDBDemoWatchOS Watch App";
productReference = 56F1E56A2C55338C00E5C801 /* GRDBDemoWatchOS Watch App.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
56B035FB1E8D9EBE003B6DA4 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1400;
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1540;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56185BEF25B80B8900B9C30F = {
@@ -386,23 +311,15 @@
ProvisioningStyle = Automatic;
TestTargetID = 56B036021E8D9EBE003B6DA4;
};
568E5FBE1E926430002582E0 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
ProvisioningStyle = Automatic;
};
568E5FCA1E926430002582E0 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
LastSwiftMigration = 1020;
ProvisioningStyle = Automatic;
};
56B036021E8D9EBE003B6DA4 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
LastSwiftMigration = 1020;
ProvisioningStyle = Automatic;
};
56F1E5692C55338C00E5C801 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */;
@@ -425,9 +342,8 @@
projectRoot = "";
targets = (
56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */,
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */,
56F1E5692C55338C00E5C801 /* GRDBDemoWatchOS Watch App */,
);
};
/* End PBXProject section */
@@ -457,23 +373,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FBD1E926430002582E0 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */,
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FC91E926430002582E0 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
568E5FD51E926430002582E0 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56B036011E8D9EBE003B6DA4 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -484,6 +383,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
56F1E5682C55338C00E5C801 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -496,15 +402,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FC71E926430002582E0 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */,
568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56B035FF1E8D9EBE003B6DA4 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -519,6 +416,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
56F1E5662C55338C00E5C801 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -532,32 +436,19 @@
name = GRDB;
targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */;
};
5642253429A2391900D714BF /* PBXTargetDependency */ = {
56F1E5762C55338D00E5C801 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 56F1E5692C55338C00E5C801 /* GRDBDemoWatchOS Watch App */;
targetProxy = 56F1E5752C55338D00E5C801 /* PBXContainerItemProxy */;
};
56F1E57E2C553C5F00E5C801 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDB;
targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */;
};
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */;
targetProxy = 568E5FCD1E926430002582E0 /* PBXContainerItemProxy */;
};
568E5FD81E926430002582E0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */;
targetProxy = 568E5FD71E926430002582E0 /* PBXContainerItemProxy */;
targetProxy = 56F1E57D2C553C5F00E5C801 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
568E5FC11E926430002582E0 /* Interface.storyboard */ = {
isa = PBXVariantGroup;
children = (
568E5FC21E926430002582E0 /* Base */,
);
name = Interface.storyboard;
sourceTree = "<group>";
};
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
@@ -630,80 +521,6 @@
};
name = Release;
};
568E5FDB1E926430002582E0 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
};
name = Debug;
};
568E5FDC1E926430002582E0 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
};
name = Release;
};
568E5FDF1E926430002582E0 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
};
name = Debug;
};
568E5FE01E926430002582E0 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
};
name = Release;
};
56B036131E8D9EBE003B6DA4 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -741,6 +558,7 @@
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -761,6 +579,8 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES;
SWIFT_VERSION = 5.0;
WATCHOS_DEPLOYMENT_TARGET = 8.0;
};
@@ -803,6 +623,7 @@
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -816,6 +637,8 @@
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_STRICT_CONCURRENCY = complete;
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
WATCHOS_DEPLOYMENT_TARGET = 8.0;
@@ -858,6 +681,80 @@
};
name = Release;
};
56F1E57A2C55338D00E5C801 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"GRDBDemoWatchOS Watch App/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = GRDBDemoWatchOS;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = com.github.groue.GRDBDemoiOS2;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 4;
};
name = Debug;
};
56F1E57B2C55338D00E5C801 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"GRDBDemoWatchOS Watch App/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = GRDBDemoWatchOS;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = com.github.groue.GRDBDemoiOS2;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 4;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -870,24 +767,6 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
568E5FDB1E926430002582E0 /* Debug */,
568E5FDC1E926430002582E0 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
568E5FDF1E926430002582E0 /* Debug */,
568E5FE01E926430002582E0 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -906,6 +785,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
56F1E5792C55338D00E5C801 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Watch App" */ = {
isa = XCConfigurationList;
buildConfigurations = (
56F1E57A2C55338D00E5C801 /* Debug */,
56F1E57B2C55338D00E5C801 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "1540"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "1540"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -40,7 +40,7 @@ struct AppDatabase {
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
private static let sqlLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
@@ -61,12 +61,12 @@ extension AppDatabase {
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
db.trace { event in
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
sqlLogger.debug("\(String(describing: event))")
}
}
}
@@ -82,6 +82,9 @@ extension AppDatabase {
}
}
// Safe according to <https://forums.developer.apple.com/forums/thread/747816>
extension Logger: @unchecked Sendable { }
// MARK: - Database Migrations
extension AppDatabase {
@@ -136,7 +136,7 @@ class PlayerListViewController: UITableViewController {
}
playersCancellable = ValueObservation
.tracking(request.fetchAll(_:))
.tracking { db in try request.fetchAll(db) }
.start(
in: AppDatabase.shared.reader,
// Immediate scheduling feeds the data source right on subscription,
@@ -145,8 +145,10 @@ class PlayerListViewController: UITableViewController {
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self else { return }
self.configureTitle(from: players)
self.configureDataSource(from: players)
MainActor.assumeIsolated {
self.configureTitle(from: players)
self.configureDataSource(from: players)
}
})
}
}
+35
View File
@@ -0,0 +1,35 @@
`TableRecord.databaseSelection` should be declared as a computed static property:
```diff
-static met databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
+static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
```
---
// Warning: Converting non-sendable function value to '@Sendable (Database) throws -> sending [Player]' may introduce data races
ValueObservation.tracking(Player.fetchAll())
-> Enable `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` in Build Settings
---
Task cancellation is now honored (exclusively in async accesses)
---
CSQLite was renamed GRDBSQLite.
---
ValueObservation requires Sendable values
---
Strategies
- databaseDataEncodingStrategy(for:)
- databaseDateEncodingStrategy(for:)
- databaseUUIDEncodingStrategy(for:)
- databaseDataDecodingStrategy(for:)
- databaseDateDecodingStrategy(for:)
+3 -1
View File
@@ -395,7 +395,9 @@ This chapter lists all kinds of supported interpolations.
struct AltPlayer: TableRecord {
static let databaseTableName = "player"
static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")]
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name")]
}
}
// SELECT player.id, player.name FROM player
+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'
+200 -57
View File
@@ -7,7 +7,6 @@
objects = {
/* Begin PBXBuildFile section */
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; };
4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; };
56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
@@ -165,7 +164,7 @@
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 */; };
5659F4901EA8D964004A4992 /* ReadWriteLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */; };
5659F4981EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; };
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; };
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; };
@@ -179,6 +178,13 @@
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; };
566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */; };
566A86882BD5774500D5562E /* AdaptedFetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A86872BD5774500D5562E /* AdaptedFetchRequest.swift */; };
566A868A2BD5775B00D5562E /* AnyFetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A86892BD5775B00D5562E /* AnyFetchRequest.swift */; };
566A868C2BD5779E00D5562E /* PreparedRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A868B2BD5779E00D5562E /* PreparedRequest.swift */; };
566A868F2BD5783000D5562E /* Database+Backup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A868E2BD5783000D5562E /* Database+Backup.swift */; };
566A86912BD578BB00D5562E /* DatabaseCursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A86902BD578BB00D5562E /* DatabaseCursor.swift */; };
566A86932BD578EB00D5562E /* StatementCursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A86922BD578EB00D5562E /* StatementCursor.swift */; };
566A86E22BD788D700D5562E /* StatementArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A86E12BD788D700D5562E /* StatementArguments.swift */; };
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
@@ -186,7 +192,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 */; };
@@ -233,6 +239,7 @@
5690C3401D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; };
5691D96A27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; };
569322242C1F105800F335A4 /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569322232C1F105300F335A4 /* AsyncSemaphore.swift */; };
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; };
5695961C222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56959615222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; };
56959629222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56959628222C462D002CB7C9 /* HasManyThroughAssociation.swift */; };
@@ -267,7 +274,6 @@
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238A41B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2FA3524424D2A00E97D23 /* Export.swift */; };
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
@@ -276,6 +282,13 @@
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; };
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; };
56B56C6B2BD567C2000DA88F /* Row+columns.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C6A2BD567C2000DA88F /* Row+columns.swift */; };
56B56C6D2BD56805000DA88F /* Row+scopes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C6C2BD56805000DA88F /* Row+scopes.swift */; };
56B56C6F2BD56869000DA88F /* Row+prefetchedRows.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C6E2BD56869000DA88F /* Row+prefetchedRows.swift */; };
56B56C712BD5693E000DA88F /* RowCursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C702BD5693E000DA88F /* RowCursor.swift */; };
56B56C732BD56960000DA88F /* Row+fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C722BD56960000DA88F /* Row+fetch.swift */; };
56B56C752BD569A5000DA88F /* Row+RandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C742BD569A5000DA88F /* Row+RandomAccessCollection.swift */; };
56B56C772BD56A17000DA88F /* RowImpl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B56C762BD56A17000DA88F /* RowImpl.swift */; };
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */; };
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
@@ -285,7 +298,9 @@
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 */; };
56CB43A12BD9880D001C8ED9 /* PersistenceContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CB43A02BD9880D001C8ED9 /* PersistenceContainer.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; };
@@ -400,6 +415,9 @@
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3B7182C1DC34F001A6C5B /* FixitsGRDB7.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3B7172C1DC34F001A6C5B /* FixitsGRDB7.swift */; };
56F3B7202C1DCCE1001A6C5B /* AsyncDispatchQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3B71F2C1DCCDE001A6C5B /* AsyncDispatchQueue.swift */; };
56F3B7222C1DCCFF001A6C5B /* Immediate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3B7212C1DCCFE001A6C5B /* Immediate.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */; };
@@ -433,7 +451,6 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = "<group>"; };
4ED4BB582731DD25008B127D /* BackupTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
@@ -602,7 +619,7 @@
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>"; };
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = "<group>"; };
5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteLock.swift; sourceTree = "<group>"; };
5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = "<group>"; };
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = "<group>"; };
565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = "<group>"; };
@@ -621,6 +638,13 @@
566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
566A86872BD5774500D5562E /* AdaptedFetchRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AdaptedFetchRequest.swift; sourceTree = "<group>"; };
566A86892BD5775B00D5562E /* AnyFetchRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnyFetchRequest.swift; sourceTree = "<group>"; };
566A868B2BD5779E00D5562E /* PreparedRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreparedRequest.swift; sourceTree = "<group>"; };
566A868E2BD5783000D5562E /* Database+Backup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Backup.swift"; sourceTree = "<group>"; };
566A86902BD578BB00D5562E /* DatabaseCursor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseCursor.swift; sourceTree = "<group>"; };
566A86922BD578EB00D5562E /* StatementCursor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementCursor.swift; sourceTree = "<group>"; };
566A86E12BD788D700D5562E /* StatementArguments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementArguments.swift; sourceTree = "<group>"; };
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = "<group>"; };
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = "<group>"; };
566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = "<group>"; };
@@ -628,8 +652,8 @@
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
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>"; };
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = RowDecodingError.swift; path = GRDB/Core/Row/RowDecodingError.swift; sourceTree = SOURCE_ROOT; };
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>"; };
@@ -685,6 +709,7 @@
56915781231BF28B00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = "<group>"; };
5691D96927256C3A0021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
569322232C1F105300F335A4 /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = "<group>"; };
569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = "<group>"; };
569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBCrashTestCase.swift; sourceTree = "<group>"; };
@@ -756,7 +781,6 @@
56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = "<group>"; };
56A2FA3524424D2A00E97D23 /* Export.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Export.swift; sourceTree = "<group>"; };
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = "<group>"; };
56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = "<group>"; };
56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyInfoTests.swift; sourceTree = "<group>"; };
@@ -771,6 +795,13 @@
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = "<group>"; };
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
56B56C6A2BD567C2000DA88F /* Row+columns.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Row+columns.swift"; sourceTree = "<group>"; };
56B56C6C2BD56805000DA88F /* Row+scopes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Row+scopes.swift"; sourceTree = "<group>"; };
56B56C6E2BD56869000DA88F /* Row+prefetchedRows.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Row+prefetchedRows.swift"; sourceTree = "<group>"; };
56B56C702BD5693E000DA88F /* RowCursor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowCursor.swift; sourceTree = "<group>"; };
56B56C722BD56960000DA88F /* Row+fetch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Row+fetch.swift"; sourceTree = "<group>"; };
56B56C742BD569A5000DA88F /* Row+RandomAccessCollection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Row+RandomAccessCollection.swift"; sourceTree = "<group>"; };
56B56C762BD56A17000DA88F /* RowImpl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowImpl.swift; sourceTree = "<group>"; };
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
@@ -785,10 +816,12 @@
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>"; };
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C494401ED7255500CC72AF /* GRDBBase.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBBase.xcconfig; sourceTree = "<group>"; };
56CB43A02BD9880D001C8ED9 /* PersistenceContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistenceContainer.swift; sourceTree = "<group>"; };
56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
@@ -834,6 +867,10 @@
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
56F3B70A2C1DB120001A6C5B /* GRDBTests.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBTests.xcconfig; sourceTree = "<group>"; };
56F3B7172C1DC34F001A6C5B /* FixitsGRDB7.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FixitsGRDB7.swift; sourceTree = "<group>"; };
56F3B71F2C1DCCDE001A6C5B /* AsyncDispatchQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncDispatchQueue.swift; sourceTree = "<group>"; };
56F3B7212C1DCCFE001A6C5B /* Immediate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Immediate.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
@@ -943,10 +980,6 @@
5605F1561C672E4000235C62 /* StandardLibrary */ = {
isa = PBXGroup;
children = (
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */,
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */,
5615877F288D875E00A67323 /* Optional.swift */,
5605F1581C672E4000235C62 /* StandardLibrary.swift */,
);
@@ -1000,9 +1033,9 @@
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
566BD72F2927AFC300595649 /* Observers */,
56AACAA022ACEC9700A40F2A /* Reducers */,
56F3B71B2C1DCAAD001A6C5B /* Schedulers */,
);
path = ValueObservation;
sourceTree = "<group>";
@@ -1010,8 +1043,10 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
569322232C1F105300F335A4 /* AsyncSemaphore.swift */,
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56BCA65B2B79246300B3A7F8 /* Mutex.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567B5BDA2AD3281B00629622 /* Dump */,
@@ -1320,11 +1355,11 @@
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 */,
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */,
5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */,
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */,
56781B0A243F86E600650A83 /* Refinable.swift */,
5659F4871EA8D94E004A4992 /* Utils.swift */,
@@ -1332,6 +1367,86 @@
path = Utils;
sourceTree = "<group>";
};
566A86822BD576A000D5562E /* SQL */ = {
isa = PBXGroup;
children = (
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
);
path = SQL;
sourceTree = "<group>";
};
566A86832BD576B500D5562E /* DatabaseValue */ = {
isa = PBXGroup;
children = (
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */,
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
);
path = DatabaseValue;
sourceTree = "<group>";
};
566A86842BD576CE00D5562E /* Observation */ = {
isa = PBXGroup;
children = (
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
);
path = Observation;
sourceTree = "<group>";
};
566A86852BD576E800D5562E /* Concurrency */ = {
isa = PBXGroup;
children = (
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
);
path = Concurrency;
sourceTree = "<group>";
};
566A86862BD5771E00D5562E /* FetchRequest */ = {
isa = PBXGroup;
children = (
566A86872BD5774500D5562E /* AdaptedFetchRequest.swift */,
566A86892BD5775B00D5562E /* AnyFetchRequest.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
566A868B2BD5779E00D5562E /* PreparedRequest.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
);
path = FetchRequest;
sourceTree = "<group>";
};
566A868D2BD5781200D5562E /* Database */ = {
isa = PBXGroup;
children = (
56A238711B9C75030082EB20 /* Database.swift */,
566A868E2BD5783000D5562E /* Database+Backup.swift */,
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
566A86902BD578BB00D5562E /* DatabaseCursor.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566A86E12BD788D700D5562E /* StatementArguments.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
566A86922BD578EB00D5562E /* StatementCursor.swift */,
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
);
path = Database;
sourceTree = "<group>";
};
566BD72F2927AFC300595649 /* Observers */ = {
isa = PBXGroup;
children = (
@@ -1568,41 +1683,17 @@
children = (
56A238701B9C75030082EB20 /* Configuration.swift */,
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
56A238711B9C75030082EB20 /* Database.swift */,
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */,
56A238731B9C75030082EB20 /* DatabaseError.swift */,
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
560A37A31C8F625000949E71 /* DatabasePool.swift */,
563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
566A86852BD576E800D5562E /* Concurrency */,
566A868D2BD5781200D5562E /* Database */,
566A86832BD576B500D5562E /* DatabaseValue */,
566A86862BD5771E00D5562E /* FetchRequest */,
566A86842BD576CE00D5562E /* Observation */,
56B56C652BD56785000DA88F /* Row */,
566A86822BD576A000D5562E /* SQL */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -1636,6 +1727,7 @@
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */,
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */,
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */,
56CB43A02BD9880D001C8ED9 /* PersistenceContainer.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
560D92461C672C4B00F4F92B /* TableRecord.swift */,
);
@@ -1654,6 +1746,23 @@
path = Reducers;
sourceTree = "<group>";
};
56B56C652BD56785000DA88F /* Row */ = {
isa = PBXGroup;
children = (
56A238761B9C75030082EB20 /* Row.swift */,
56B56C6A2BD567C2000DA88F /* Row+columns.swift */,
56B56C722BD56960000DA88F /* Row+fetch.swift */,
56B56C6E2BD56869000DA88F /* Row+prefetchedRows.swift */,
56B56C742BD569A5000DA88F /* Row+RandomAccessCollection.swift */,
56B56C6C2BD56805000DA88F /* Row+scopes.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
56B56C702BD5693E000DA88F /* RowCursor.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56B56C762BD56A17000DA88F /* RowImpl.swift */,
);
path = Row;
sourceTree = "<group>";
};
56DAA2C41DE99D8D006E10C8 /* Cursor */ = {
isa = PBXGroup;
children = (
@@ -1695,6 +1804,16 @@
name = Foundation;
sourceTree = "<group>";
};
56F3B71B2C1DCAAD001A6C5B /* Schedulers */ = {
isa = PBXGroup;
children = (
56F3B71F2C1DCCDE001A6C5B /* AsyncDispatchQueue.swift */,
56F3B7212C1DCCFE001A6C5B /* Immediate.swift */,
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
);
path = Schedulers;
sourceTree = "<group>";
};
DC10500F19C904DD00D8CA30 /* Tests */ = {
isa = PBXGroup;
children = (
@@ -1740,8 +1859,8 @@
DC37742D19C8CC90004FCF85 /* GRDB */ = {
isa = PBXGroup;
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
56F3B7172C1DC34F001A6C5B /* FixitsGRDB7.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
567B5BDF2AD3284100629622 /* Dump */,
@@ -1766,7 +1885,8 @@
56C48E731C9A9923005DF1D9 /* module.modulemap */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
56C494401ED7255500CC72AF /* GRDBBase.xcconfig */,
56F3B70A2C1DB120001A6C5B /* GRDBTests.xcconfig */,
);
name = "Supporting Files";
path = ../Support;
@@ -1831,8 +1951,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 1540;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2105,6 +2226,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 */,
@@ -2114,6 +2236,7 @@
56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
569322242C1F105800F335A4 /* AsyncSemaphore.swift in Sources */,
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */,
@@ -2180,23 +2303,28 @@
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteLock.swift in Sources */,
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */,
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
56F3B7182C1DC34F001A6C5B /* FixitsGRDB7.swift in Sources */,
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */,
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */,
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
566A86E22BD788D700D5562E /* StatementArguments.swift in Sources */,
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
56CB43A12BD9880D001C8ED9 /* PersistenceContainer.swift in Sources */,
56B56C772BD56A17000DA88F /* RowImpl.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */,
566A868F2BD5783000D5562E /* Database+Backup.swift in Sources */,
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2207,6 +2335,7 @@
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */,
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
56B56C6D2BD56805000DA88F /* Row+scopes.swift in Sources */,
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
@@ -2220,15 +2349,16 @@
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
56B56C752BD569A5000DA88F /* Row+RandomAccessCollection.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */,
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
56B56C6B2BD567C2000DA88F /* Row+columns.swift in Sources */,
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */,
566A86912BD578BB00D5562E /* DatabaseCursor.swift in Sources */,
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
@@ -2253,6 +2383,7 @@
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
566A86882BD5774500D5562E /* AdaptedFetchRequest.swift in Sources */,
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */,
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */,
@@ -2267,9 +2398,10 @@
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
566A868A2BD5775B00D5562E /* AnyFetchRequest.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 */,
@@ -2278,6 +2410,7 @@
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */,
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
56B56C732BD56960000DA88F /* Row+fetch.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
56894FB72606589700268F4D /* Decimal.swift in Sources */,
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */,
@@ -2296,6 +2429,8 @@
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
56F3B7222C1DCCFF001A6C5B /* Immediate.swift in Sources */,
566A868C2BD5779E00D5562E /* PreparedRequest.swift in Sources */,
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
@@ -2311,8 +2446,10 @@
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
56781B0B243F86E600650A83 /* Refinable.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
56B56C712BD5693E000DA88F /* RowCursor.swift in Sources */,
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */,
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */,
56F3B7202C1DCCE1001A6C5B /* AsyncDispatchQueue.swift in Sources */,
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -2320,9 +2457,11 @@
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
56B56C6F2BD56869000DA88F /* Row+prefetchedRows.swift in Sources */,
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */,
566A86932BD578EB00D5562E /* StatementCursor.swift in Sources */,
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2340,7 +2479,7 @@
/* Begin XCBuildConfiguration section */
56E5D8021B4D422E00430942 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
baseConfigurationReference = 56F3B70A2C1DB120001A6C5B /* GRDBTests.xcconfig */;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
@@ -2370,7 +2509,7 @@
};
56E5D8031B4D422E00430942 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
baseConfigurationReference = 56F3B70A2C1DB120001A6C5B /* GRDBTests.xcconfig */;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
@@ -2525,6 +2664,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2532,6 +2672,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -2556,6 +2697,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2563,6 +2705,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "1540"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -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
let databaseSnapshotCountMutex = Mutex(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
@@ -118,10 +116,6 @@ public final class DatabasePool {
configuration.readonly = true
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
// > But there are some obscure cases where a query against a WAL-mode
// > database can return SQLITE_BUSY, so applications should be prepared
@@ -148,7 +142,7 @@ public final class DatabasePool {
}
}
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
// @unchecked because of readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -222,17 +216,25 @@ extension DatabasePool {
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
private func setupMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
// Avoid compiler warning due to <https://github.com/apple/swift/issues/72456>
// > Main actor-isolated class property 'didReceiveMemoryWarningNotification'
// > can not be referenced from a non-isolated context; this is an
// > error in Swift 6.
DispatchQueue.main.async { [weak self] in
guard let self else { return }
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
}
@objc
@@ -241,23 +243,29 @@ extension DatabasePool {
return
}
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
if task == .invalid {
// Release memory synchronously
releaseMemory()
} else {
// Release memory eventually.
//
// We don't know when reader connections will be closed (because
// they may be currently in use), so we don't quite know when
// reader memory will be freed (which would be the ideal timing for
// ending our background task).
//
// So let's just end the background task after the writer connection
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
application.endBackgroundTask(task)
// `UIApplication.beginBackgroundTask(expirationHandler:)` is MainActor-isolated.
DispatchQueue.main.async { [weak self] in
guard let self else { return }
let taskId = application.beginBackgroundTask(expirationHandler: nil)
if taskId == .invalid {
releaseMemory()
} else {
// Release memory eventually.
//
// We don't know when reader connections will be closed (because
// they may be currently in use), so we don't quite know when
// reader memory will be freed (which would be the ideal timing for
// ending our background task).
//
// So let's just end the background task after the writer connection
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
DispatchQueue.main.async {
application.endBackgroundTask(taskId)
}
}
}
}
}
@@ -357,7 +365,55 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
// FIXME: remove the closure copy when <https://github.com/apple/swift/issues/74457> is fixed.
let value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
releaseReader(.reuse)
}
do {
let _result = try dbAccess.inDatabase(db) {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try valueWrapper.value(db)
}
// Safe because result is not used beyond its transfer to continuation
nonisolated(unsafe) let result = _result
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -367,6 +423,9 @@ extension DatabasePool: DatabaseReader {
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
let valueWrapper = UncheckedSendableWrapper(value: value)
reader.async { db in
defer {
try? db.commit() // Ignore commit error
@@ -376,9 +435,9 @@ extension DatabasePool: DatabaseReader {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
value(.success(db))
valueWrapper.value(.success(db))
} catch {
value(.failure(error))
valueWrapper.value(.failure(error))
}
}
} catch {
@@ -401,7 +460,52 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
// FIXME: remove the closure copy when <https://github.com/apple/swift/issues/74457> is fixed.
let value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(.reuse)
}
do {
let _result = try dbAccess.inDatabase(db) {
try db.clearSchemaCacheIfNeeded()
return try valueWrapper.value(db)
}
// Safe because result is not used beyond its transfer to continuation
nonisolated(unsafe) let result = _result
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -411,15 +515,18 @@ extension DatabasePool: DatabaseReader {
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
let valueWrapper = UncheckedSendableWrapper(value: value)
reader.async { db in
defer {
releaseReader(.reuse)
}
do {
try db.clearSchemaCacheIfNeeded()
value(.success(db))
valueWrapper.value(.success(db))
} catch {
value(.failure(error))
valueWrapper.value(.failure(error))
}
}
} catch {
@@ -446,25 +553,9 @@ 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
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
asyncConcurrentRead(value)
}
@@ -505,7 +596,9 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -644,8 +737,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 +757,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 +785,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 +816,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")
@@ -746,6 +840,13 @@ extension DatabasePool: DatabaseWriter {
try writer.sync(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
guard let readerPool else {
@@ -756,7 +857,38 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
// FIXME: remove the closure copy when <https://github.com/apple/swift/issues/74457> is fixed.
let updates: (Database) throws -> T = updates
let updatesWrapper = UncheckedSendableWrapper(value: updates)
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
asyncBarrierWriteWithoutTransaction { dbResult in
do {
try dbAccess.checkCancellation()
let db = try dbResult.get()
let _result = try dbAccess.inDatabase(db) {
try updatesWrapper.value(db)
}
// Safe because result is not used beyond its transfer to continuation
nonisolated(unsafe) let result = _result
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -788,9 +920,10 @@ extension DatabasePool: DatabaseWriter {
///
/// - precondition: This method is not reentrant.
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
@@ -809,8 +942,10 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
public func asyncWriteWithoutTransaction(
_ updates: sending @escaping (Database) -> Void
) {
writer.async(execute: updates)
}
}
@@ -867,11 +1002,10 @@ extension DatabasePool {
path: path,
configuration: DatabasePool.readerConfiguration(writer.configuration),
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\($databaseSnapshotCount.increment())")
purpose: "snapshot.\(databaseSnapshotCountMutex.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.
@@ -142,17 +142,25 @@ extension DatabaseQueue {
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
private func setupMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
// Avoid compiler warning due to <https://github.com/apple/swift/issues/72456>
// > Main actor-isolated class property 'didReceiveMemoryWarningNotification'
// > can not be referenced from a non-isolated context; this is an
// > error in Swift 6.
DispatchQueue.main.async { [weak self] in
guard let self else { return }
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
}
@objc
@@ -161,15 +169,21 @@ extension DatabaseQueue {
return
}
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
if task == .invalid {
// Release memory synchronously
releaseMemory()
} else {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
application.endBackgroundTask(task)
// `UIApplication.beginBackgroundTask(expirationHandler:)` is MainActor-isolated.
DispatchQueue.main.async { [weak self] in
guard let self else { return }
let taskId: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
if taskId == .invalid {
releaseMemory()
} else {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
DispatchQueue.main.async {
application.endBackgroundTask(taskId)
}
}
}
}
}
@@ -233,7 +247,20 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
try value(db)
}
}
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -258,7 +285,16 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
writer.async { value(.success($0)) }
}
@@ -266,20 +302,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(Result {
// Check that we're on the writer queue, as documented
try writer.execute { db in
try db.isolated(readOnly: true) {
try value(db)
}
}
})
}
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 +332,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 {
@@ -352,9 +375,10 @@ extension DatabaseQueue: DatabaseWriter {
/// ```
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
@@ -374,12 +398,28 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: sending @escaping (Result<Database, Error>) -> Void
) {
writer.async { updates(.success($0)) }
}
@@ -425,8 +465,10 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
public func asyncWriteWithoutTransaction(
_ updates: sending @escaping (Database) -> Void
) {
writer.async(execute: updates)
}
}
@@ -188,6 +188,39 @@ public protocol DatabaseReader: AnyObject, Sendable {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func read<T>(_ value: (Database) throws -> T) throws -> T
/// Executes read-only database operations, and returns their result after
/// they have finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// For example:
///
/// ```swift
/// let count = try await reader.read { db in
/// try Player.fetchCount(db)
/// }
/// ```
///
/// Database operations are isolated in a transaction: they do not see
/// changes performed by eventual concurrent writes (even writes performed
/// by other processes).
///
/// The database connection is read-only: attempts to write throw a
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
///
/// The ``Database`` argument to `value` is valid only during the execution
/// of the closure. Do not store or return the database connection for
/// later use.
///
/// - parameter value: A closure which accesses the database.
/// - throws: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T
/// Schedules read-only database operations for execution, and
/// returns immediately.
///
@@ -214,7 +247,9 @@ 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: sending @escaping (Result<Database, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -254,6 +289,45 @@ public protocol DatabaseReader: AnyObject, Sendable {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// This method is "unsafe" because the database reader does nothing more
/// than providing a database connection. When you use this method, you
/// become responsible for the thread-safety of your application, and
/// responsible for database accesses performed by other processes. See
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
/// more information.
///
/// For example:
///
/// ```swift
/// let count = try await reader.unsafeRead { db in
/// try Player.fetchCount(db)
/// }
/// ```
///
/// The ``Database`` argument to `value` is valid only during the execution
/// of the closure. Do not store or return the database connection for
/// later use.
///
/// - warning: Database operations may not be wrapped in a transaction. They
/// may see changes performed by concurrent writes or writes performed by
/// other processes: two identical requests performed by the `value`
/// closure may not return the same value.
/// - warning: Attempts to write in the database may succeed.
///
/// - parameter value: A closure which accesses the database.
/// - throws: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T
/// Schedules database operations for execution, and returns immediately.
///
/// This method is "unsafe" because the database reader does nothing more
@@ -285,7 +359,9 @@ 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: sending @escaping (Result<Database, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -343,7 +419,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
}
@@ -428,96 +504,6 @@ extension DatabaseReader {
}
}
extension DatabaseReader {
// MARK: - Asynchronous Database Access
/// Executes read-only database operations, and returns their result after
/// they have finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// For example:
///
/// ```swift
/// let count = try await reader.read { db in
/// try Player.fetchCount(db)
/// }
/// ```
///
/// Database operations are isolated in a transaction: they do not see
/// changes performed by eventual concurrent writes (even writes performed
/// by other processes).
///
/// The database connection is read-only: attempts to write throw a
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
///
/// The ``Database`` argument to `value` is valid only during the execution
/// of the closure. Do not store or return the database connection for
/// later use.
///
/// - parameter value: A closure which accesses the database.
/// - 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 {
try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
try continuation.resume(returning: value(result.get()))
} catch {
continuation.resume(throwing: error)
}
}
}
}
/// Executes database operations, and returns their result after they have
/// finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// This method is "unsafe" because the database reader does nothing more
/// than providing a database connection. When you use this method, you
/// become responsible for the thread-safety of your application, and
/// responsible for database accesses performed by other processes. See
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
/// more information.
///
/// For example:
///
/// ```swift
/// let count = try await reader.unsafeRead { db in
/// try Player.fetchCount(db)
/// }
/// ```
///
/// The ``Database`` argument to `value` is valid only during the execution
/// of the closure. Do not store or return the database connection for
/// later use.
///
/// - warning: Database operations may not be wrapped in a transaction. They
/// may see changes performed by concurrent writes or writes performed by
/// other processes: two identical requests performed by the `value`
/// closure may not return the same value.
/// - warning: Attempts to write in the database may succeed.
///
/// - parameter value: A closure which accesses the database.
/// - 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 {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
try continuation.resume(returning: value(result.get()))
} catch {
continuation.resume(throwing: error)
}
}
}
}
}
#if canImport(Combine)
extension DatabaseReader {
// MARK: - Publishing Database Values
@@ -549,17 +535,15 @@ 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, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
value: @escaping @Sendable (Database) throws -> sending 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) } })
}
}
.receiveValues(on: scheduler)
@@ -567,7 +551,7 @@ extension DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that reads from the database.
///
@@ -586,7 +570,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Publisher where Failure == Error {
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
.init(upstream: eraseToAnyPublisher())
@@ -602,7 +586,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() {
@@ -620,24 +604,26 @@ 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) }
}
// Safe because result is not used beyond its transfer to sheduler
let resultWrapper = UncheckedSendableWrapper(value: result)
scheduler.schedule {
guard !isCancelled else { return }
if cancellable.isCancelled { return }
do {
try onChange(result.get())
try onChange(resultWrapper.value.get())
} catch {
observation.events.didFail?(error)
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
return cancellable
}
}
}
@@ -678,7 +664,16 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.read(value)
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncRead(value)
}
@@ -687,7 +682,16 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
@@ -698,7 +702,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(
@@ -758,7 +762,9 @@ 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: sending @escaping (Result<Database, Error>) -> Void
) {
asyncRead(value)
}
}
@@ -126,10 +126,6 @@ public final class DatabaseSnapshot {
// DatabaseSnapshot is read-only.
configuration.readonly = true
// DatabaseSnapshot uses deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// DatabaseSnapshot keeps a long-lived transaction.
configuration.allowsUnsafeTransactions = true
@@ -154,7 +150,16 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await reader.execute(value)
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
@@ -162,8 +167,15 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
// There is no such thing as an unsafe access to a snapshot.
// We can't provide this as a default implementation in
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
@@ -175,7 +187,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(
@@ -1,5 +1,13 @@
// 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)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
///
@@ -122,6 +130,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 +139,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 +159,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 +218,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)")
})
}
@@ -234,10 +239,6 @@ public final class DatabaseSnapshotPool {
// DatabaseSnapshotPool is read-only.
configuration.readonly = true
// DatabaseSnapshotPool uses deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// DatabaseSnapshotPool keeps a long-lived transaction.
configuration.allowsUnsafeTransactions = true
@@ -292,7 +293,51 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
// FIXME: remove the closure copy when <https://github.com/apple/swift/issues/74457> is fixed.
let value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(self.poolCompletion(db))
}
do {
let _result = try dbAccess.inDatabase(db) {
try valueWrapper.value(db)
}
// Safe because result is not used beyond its transfer to continuation
nonisolated(unsafe) let result = _result
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -302,8 +347,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
let valueWrapper = UncheckedSendableWrapper(value: value)
reader.async { db in
value(.success(db))
valueWrapper.value(.success(db))
releaseReader(self.poolCompletion(db))
}
} catch {
@@ -312,12 +360,23 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
// There is no such thing as an unsafe access to a snapshot.
// We can't provide this as a default implementation in
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync { db in
let result = try value(db)
if snapshotIsLost(db) {
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
throw DatabaseError.snapshotIsLost()
}
return result
}
@@ -330,7 +389,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)
@@ -38,9 +38,7 @@ import Dispatch
///
/// ### Reading from the Latest Committed Database State
///
/// - ``concurrentRead(_:)``
/// - ``spawnConcurrentRead(_:)``
/// - ``DatabaseFuture``
///
/// ### Unsafe Methods
///
@@ -102,6 +100,42 @@ public protocol DatabaseWriter: DatabaseReader {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// For example:
///
/// ```swift
/// let newPlayerCount = try await writer.writeWithoutTransaction { db in
/// try Player(name: "Arthur").insert(db)
/// return try Player.fetchCount(db)
/// }
/// ```
///
/// Database operations run in the writer dispatch queue, serialized
/// with all database updates performed by this `DatabaseWriter`.
///
/// The ``Database`` argument to `updates` is valid only during the
/// execution of the closure. Do not store or return the database connection
/// for later use.
///
/// - warning: Database operations are not wrapped in a transaction. They
/// can see changes performed by concurrent writes or writes performed by
/// other processes: two identical requests performed by the `updates`
/// closure may not return the same value. Concurrent database accesses
/// can see partial updates performed by the `updates` closure.
///
/// - parameter updates: A closure which accesses the database.
/// - throws: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func writeWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T
/// Executes database operations, and returns their result after they have
/// finished executing.
///
@@ -142,6 +176,52 @@ public protocol DatabaseWriter: DatabaseReader {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// Database operations are not executed until all currently executing
/// database accesses performed by the database writer finish executing
/// (both reads and writes). At that point, database operations are
/// executed. Once they finish, the database writer can proceed with other
/// database accesses.
///
/// For example:
///
/// ```swift
/// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in
/// try Player(name: "Arthur").insert(db)
/// return try Player.fetchCount(db)
/// }
/// ```
///
/// Database operations run in the writer dispatch queue, serialized
/// with all database updates performed by this `DatabaseWriter`.
///
/// The ``Database`` argument to `updates` is valid only during the
/// execution of the closure. Do not store or return the database connection
/// for later use.
///
/// It is a programmer error to call this method from another database
/// access method. Doing so raises a "Database methods are not reentrant"
/// fatal error at runtime.
///
/// - warning: Database operations are not wrapped in a transaction. They
/// can see changes performed by concurrent writes or writes performed by
/// other processes: two identical requests performed by the `updates`
/// closure may not return the same value. Concurrent database accesses
/// can see partial updates performed by the `updates` closure.
///
/// - parameter updates: A closure which accesses the database.
/// - throws: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func barrierWriteWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T
/// Schedules database operations for execution, and returns immediately.
///
/// Database operations are not executed until all currently executing
@@ -181,7 +261,9 @@ 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: sending @escaping (Result<Database, Error>) -> Void
)
/// Schedules database operations for execution, and returns immediately.
///
@@ -213,7 +295,9 @@ 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: sending @escaping (Database) -> Void
)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -251,49 +335,6 @@ public protocol DatabaseWriter: DatabaseReader {
// MARK: - Reading from Database
/// Schedules read-only database operations for execution, and returns a
/// future value.
///
/// This method must be called from the writer dispatch queue, outside of
/// any transaction. You'll get a fatal error otherwise.
///
/// Database operations performed by the `value` closure are isolated in a
/// transaction: they do not see changes performed by eventual concurrent
/// writes (even writes performed by other processes).
///
/// They see the database in the state left by the last updates performed
/// by the database writer.
///
/// To access the fetched results, you call the ``DatabaseFuture/wait()``
/// method of the returned future, on any dispatch queue.
///
/// In the example below, the number of players is fetched concurrently with
/// the player insertion. Yet the future is guaranteed to return zero:
///
/// ```swift
/// try writer.writeWithoutTransaction { db in
/// // Delete all players
/// try Player.deleteAll()
///
/// // Count players concurrently
/// let future = writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
///
/// // Insert a player
/// try Player(...).insert(db)
///
/// // Guaranteed to be zero
/// let count = try future.wait()
/// }
/// ```
///
/// - note: Usage of this method is discouraged, because waiting on the
/// 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>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
///
@@ -340,7 +381,9 @@ 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: sending @escaping (Result<Database, Error>) -> Void
)
}
extension DatabaseWriter {
@@ -426,9 +469,9 @@ 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: sending @escaping (Database) throws -> sending T,
completion: sending @escaping (Database, Result<T, Error>) -> Void
) {
asyncWriteWithoutTransaction { db in
do {
var result: T?
@@ -541,7 +584,7 @@ extension DatabaseWriter {
///
/// - Parameter filePath: file path for new database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *)
@available(iOS 14, macOS 10.16, tvOS 14, *)
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -557,7 +600,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")
@@ -604,115 +647,27 @@ extension DatabaseWriter {
/// for later use.
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
/// 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 {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
})
}
}
/// Executes database operations, and returns their result after they have
/// finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// For example:
///
/// ```swift
/// let newPlayerCount = try await writer.writeWithoutTransaction { db in
/// try Player(name: "Arthur").insert(db)
/// return try Player.fetchCount(db)
/// }
/// ```
///
/// Database operations run in the writer dispatch queue, serialized
/// with all database updates performed by this `DatabaseWriter`.
///
/// The ``Database`` argument to `updates` is valid only during the
/// execution of the closure. Do not store or return the database connection
/// for later use.
///
/// - warning: Database operations are not wrapped in a transaction. They
/// can see changes performed by concurrent writes or writes performed by
/// other processes: two identical requests performed by the `updates`
/// closure may not return the same value. Concurrent database accesses
/// can see partial updates performed by the `updates` closure.
///
/// - 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 {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
try continuation.resume(returning: updates(db))
} catch {
continuation.resume(throwing: error)
}
}
}
}
/// Executes database operations, and returns their result after they have
/// finished executing.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// Database operations are not executed until all currently executing
/// database accesses performed by the database writer finish executing
/// (both reads and writes). At that point, database operations are
/// executed. Once they finish, the database writer can proceed with other
/// database accesses.
///
/// For example:
///
/// ```swift
/// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in
/// try Player(name: "Arthur").insert(db)
/// return try Player.fetchCount(db)
/// }
/// ```
///
/// Database operations run in the writer dispatch queue, serialized
/// with all database updates performed by this `DatabaseWriter`.
///
/// The ``Database`` argument to `updates` is valid only during the
/// execution of the closure. Do not store or return the database connection
/// for later use.
///
/// It is a programmer error to call this method from another database
/// access method. Doing so raises a "Database methods are not reentrant"
/// fatal error at runtime.
///
/// - warning: Database operations are not wrapped in a transaction. They
/// can see changes performed by concurrent writes or writes performed by
/// other processes: two identical requests performed by the `updates`
/// closure may not return the same value. Concurrent database accesses
/// can see partial updates performed by the `updates` closure.
///
/// - 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)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
asyncBarrierWriteWithoutTransaction { dbResult in
continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } })
/// - throws: Any ``DatabaseError`` that happens while establishing the
/// database access or committing the transaction, or the error thrown
/// by `updates`, or `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func write<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writeWithoutTransaction { db in
var result: T?
try db.inTransaction {
result = try updates(db)
return .commit
}
return result!
}
}
/// Erase the database: delete all content, drop all tables, etc.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func erase() async throws {
try await writeWithoutTransaction { try $0.erase() }
}
@@ -723,7 +678,7 @@ extension DatabaseWriter {
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html>
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func vacuum() async throws {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
@@ -740,7 +695,7 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -755,7 +710,7 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -800,10 +755,10 @@ 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, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping (Database) throws -> Output)
updates: @escaping @Sendable (Database) throws -> sending Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -865,11 +820,11 @@ extension DatabaseWriter {
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
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 -> sending T,
thenRead value: @escaping @Sendable (Database, T) throws -> sending Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
{
@@ -885,8 +840,12 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
// Safe because result is not used beyond its transfer
let updatesValueWrapper = UncheckedSendableWrapper(value: updatesValue!)
self.spawnConcurrentRead { [updatesValueWrapper] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValueWrapper.value) } })
}
}
}
@@ -897,7 +856,7 @@ extension DatabaseWriter {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that writes into the database.
///
@@ -916,7 +875,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Publisher where Failure == Error {
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
.init(upstream: self.eraseToAnyPublisher())
@@ -924,49 +883,6 @@ extension Publisher where Failure == Error {
}
#endif
/// A future database value.
///
/// You get instances of `DatabaseFuture` from the `DatabaseWriter`
/// ``DatabaseWriter/concurrentRead(_:)`` method. For example:
///
/// ```swift
/// let futureCount: Future<Int> = try writer.writeWithoutTransaction { db in
/// try Player(...).insert()
///
/// // Count players concurrently
/// return writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
/// }
///
/// let count: Int = try futureCount.wait()
/// ```
public class DatabaseFuture<Value> {
private var consumed = false
private let _wait: () throws -> Value
init(_ wait: @escaping () throws -> Value) {
_wait = wait
}
init(_ result: Result<Value, Error>) {
_wait = result.get
}
/// Blocks the current thread until the value is available, and returns it.
///
/// It is a programmer error to call this method several times.
///
/// - throws: Any error that prevented the value from becoming available.
public func wait() throws -> Value {
// Not thread-safe and quick and dirty.
// Goal is that users learn not to call this method twice.
GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once")
consumed = true
return try _wait()
}
}
/// A type-erased database writer.
///
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
@@ -1003,7 +919,16 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.read(value)
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncRead(value)
}
@@ -1012,7 +937,16 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
@@ -1023,7 +957,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(
@@ -1039,16 +973,34 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.writeWithoutTransaction(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.writeWithoutTransaction(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(
_ updates: sending @escaping (Database) -> Void
) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -1056,11 +1008,9 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.spawnConcurrentRead(value)
}
}
@@ -22,7 +22,7 @@ import Dispatch
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
nonisolated(unsafe) private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
@@ -223,9 +223,11 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping (Database) -> Void) {
queue.async {
block(self.db)
func async(
execute work: sending @escaping (Database) -> Void
) {
queue.asyncSending {
work(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
}
}
@@ -243,6 +245,34 @@ final class SerializedDatabase {
return try block(db)
}
/// Asynchrously executes the block.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func execute<T>(
_ block: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
// FIXME: remove the closure copy when <https://github.com/apple/swift/issues/74457> is fixed.
let block: (Database) throws -> T = block
let blockWrapper = UncheckedSendableWrapper(value: block)
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
self.async { db in
do {
let _result = try dbAccess.inDatabase(db) {
try blockWrapper.value(db)
}
// Safe because result is not used beyond its transfer to continuation
nonisolated(unsafe) let result = _result
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
}
}
func interrupt() {
// Intentionally not scheduled in our serial queue
db.interrupt()
@@ -286,3 +316,105 @@ final class SerializedDatabase {
// It happens the job of SerializedDatabase is precisely to provide thread-safe
// access to `Database`.
extension SerializedDatabase: @unchecked Sendable { }
// MARK: - Task Cancellation Support
@available(iOS 13, macOS 10.15, tvOS 13, *)
enum DatabaseAccessCancellationState: @unchecked Sendable {
// @unchecked Sendable because database is only accessed from its
// dispatch queue.
case notConnected
case connected(Database)
case cancelled
case expired
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
/// Supports Task cancellation in async database accesses.
///
/// Usage:
///
/// ```swift
/// let dbAccess = CancellableDatabaseAccess()
/// return try dbAccess.withCancellableContinuation { continuation in
/// asyncDatabaseAccess { db in
/// do {
/// let result = try dbAccess.inDatabase(db) {
/// // Perform database operations
/// }
/// continuation.resume(returning: result)
/// } catch {
/// continuation.resume(throwing: error)
/// }
/// }
/// }
/// ```
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension CancellableDatabaseAccess: DatabaseCancellable {
convenience init() {
self.init(.notConnected)
}
func cancel() {
withLock { state in
switch state {
case let .connected(db):
db.cancel()
state = .cancelled
case .notConnected:
state = .cancelled
case .cancelled, .expired:
break
}
}
}
func withCancellableContinuation<Value>(
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
) async throws -> Value {
try await withTaskCancellationHandler {
try checkCancellation()
return try await withUnsafeThrowingContinuation { continuation in
fn(continuation)
}
} onCancel: {
cancel()
}
}
func checkCancellation() throws {
try withLock { state in
if case .cancelled = state {
throw CancellationError()
}
}
}
/// Wraps a full database access with cancellation support. When this
/// method returns, the database is NOT cancelled.
func inDatabase<Value>(_ db: Database, _ work: () throws -> sending Value) throws -> sending Value {
try withLock { state in
switch state {
case .connected, .expired:
fatalError("Can't use a CancellableDatabaseAccess twice")
case .notConnected:
state = .connected(db)
case .cancelled:
throw CancellationError()
}
}
defer {
withLock { state in
if case .cancelled = state {
db.uncancel()
}
state = .expired
}
}
return try work()
}
}
@@ -1,5 +1,13 @@
// 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)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
@@ -0,0 +1,125 @@
#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).
final class WALSnapshotTransaction: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a 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
private let databaseAccessMutex: Mutex<DatabaseAccess?>
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
/// Creates a long-live WAL transaction on a read-only connection.
///
/// The `release` closure is always called. It is called when the
/// `WALSnapshotTransaction` is deallocated, or if the initializer
/// throws.
///
/// In normal operations, the argument to `release` is always false,
/// meaning that the connection is no longer in a transaction. If true,
/// the connection has been left inside a transaction, due to
/// some error.
///
/// Usage:
///
/// ```swift
/// let transaction = WALSnapshotTransaction(
/// reader: reader,
/// release: { isInsideTransaction in
/// ...
/// })
/// ```
///
/// - parameter reader: A read-only database connection.
/// - parameter release: A closure to call when the read-only connection
/// is no longer used.
init(
onReader reader: SerializedDatabase,
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
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
try db.beginTransaction(.deferred)
// This also acquires snapshot isolation because checking
// database schema performs a read access.
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.databaseAccessMutex = Mutex(databaseAccess)
} catch {
// self is not initialized, so deinit will not run.
databaseAccess.commitAndRelease()
throw error
}
}
deinit {
close()
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) throws -> T {
try databaseAccessMutex.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: sending @escaping (Result<Database, Error>) -> Void
) {
guard let databaseAccess = databaseAccessMutex.load() 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.databaseAccessMutex.load() == nil {
value(.failure(DatabaseError.snapshotIsLost()))
}
value(.success(db))
}
}
func close() {
databaseAccessMutex.withLock { databaseAccess in
databaseAccess?.commitAndRelease()
databaseAccess = nil
}
}
}
#endif
+32 -28
View File
@@ -1,7 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Dispatch
import Foundation
public struct Configuration {
// TODO: remove @unchecked when DispatchQoS is Sendable
public struct Configuration: @unchecked Sendable {
// MARK: - Misc options
@@ -186,7 +196,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,34 +233,12 @@ 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)
}
// MARK: - Transactions
/// The default kind of write transactions.
///
/// The default is ``Database/TransactionKind/deferred``.
///
/// You can change the default transaction kind. For example, you can force
/// all write transactions to be `IMMEDIATE`:
///
/// ```swift
/// var config = Configuration()
/// config.defaultTransactionKind = .immediate
/// let dbQueue = try DatabaseQueue(configuration: config)
///
/// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION;
/// try dbQueue.write { db in ... }
/// ```
///
/// This property is ignored for read-only transactions. Those always open
/// `DEFERRED` SQLite transactions.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
public var defaultTransactionKind: Database.TransactionKind = .deferred
/// A boolean value indicating whether it is valid to leave a transaction
/// opened at the end of a database access method.
///
@@ -445,9 +433,25 @@ public struct Configuration {
/// through a `SerializedDatabase`.
var threadingMode = Database.ThreadingMode.default
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
private(set) var SQLiteConnectionDidOpen: (@Sendable () -> Void)?
private(set) var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)?
private(set) var SQLiteConnectionDidClose: (@Sendable () -> Void)?
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidOpen(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidOpen = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionWillClose(_ callback: @escaping @Sendable (SQLiteConnection) -> Void) {
SQLiteConnectionWillClose = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidClose(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidClose = callback
}
var SQLiteOpenFlags: CInt {
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
if sqlite3_libversion_number() >= 3037000 {
+8 -12
View File
@@ -670,24 +670,16 @@ extension Cursor where Element: Equatable {
extension Cursor where Element: Comparable {
/// Returns the maximum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
/// - Returns: The cursor's maximum element. If the cursor has no
/// elements, returns `nil`.
public func max() throws -> Element? {
try max(by: <)
}
/// Returns the minimum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
/// - Returns: The cursor's minimum element. If the cursor has no
/// elements, returns `nil`.
public func min() throws -> Element? {
try min(by: <)
}
@@ -915,6 +907,10 @@ public final class FilterCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable.
@available(*, unavailable)
extension FilterCursor: Sendable { }
extension FilterCursor: Cursor {
public func next() throws -> Base.Element? {
while let element = try base.next() {
+147
View File
@@ -0,0 +1,147 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
/// Copies the database contents into another database.
///
/// The `backup` method blocks the current thread until the destination
/// database contains the same contents as the source database.
///
/// Usage:
///
/// ```swift
/// let source: DatabaseQueue = ...
/// let destination: DatabaseQueue = ...
/// try source.write { sourceDb in
/// try destination.barrierWriteWithoutTransaction { destDb in
/// try sourceDb.backup(to: destDb)
/// }
/// }
/// ```
///
/// When you're after progress reporting during backup, you'll want to
/// perform the backup in several steps. Each step copies the number of
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
/// for more information:
///
/// ```swift
/// // Backup with progress reporting
/// try sourceDb.backup(to: destDb, pagesPerStep: ...) { progress in
/// print("Database backup progress:", progress)
/// }
/// ```
///
/// The `progress` callback will be called at least once—when
/// `backupProgress.isCompleted == true`. If the callback throws
/// when `backupProgress.isCompleted == false`, the backup is aborted
/// and the error is rethrown. If the callback throws when
/// `backupProgress.isCompleted == true`, backup completion is
/// unaffected and the error is silently ignored.
///
/// See also ``DatabaseReader/backup(to:pagesPerStep:progress:)``.
///
/// - parameters:
/// - destDb: The destination database.
/// - pagesPerStep: The number of database pages copied on each backup
/// step. By default, all pages are copied in one single step.
/// - progress: An optional function that is notified of the backup
/// progress.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `progress`.
public func backup(
to destDb: Database,
pagesPerStep: CInt = -1,
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
throws
{
try backupInternal(
to: destDb,
pagesPerStep: pagesPerStep,
afterBackupStep: progress)
}
func backupInternal(
to destDb: Database,
pagesPerStep: CInt = -1,
afterBackupInit: (() -> Void)? = nil,
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
throws
{
guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else {
throw DatabaseError(resultCode: destDb.lastErrorCode, message: destDb.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError()
}
afterBackupInit?()
do {
backupLoop: while true {
let rc = sqlite3_backup_step(backup, pagesPerStep)
let totalPageCount = Int(sqlite3_backup_pagecount(backup))
let remainingPageCount = Int(sqlite3_backup_remaining(backup))
let progress = DatabaseBackupProgress(
remainingPageCount: remainingPageCount,
totalPageCount: totalPageCount,
isCompleted: rc == SQLITE_DONE)
switch rc {
case SQLITE_DONE:
try? afterBackupStep?(progress)
break backupLoop
case SQLITE_OK:
try afterBackupStep?(progress)
case let code:
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
}
}
} catch {
sqlite3_backup_finish(backup)
throw error
}
switch sqlite3_backup_finish(backup) {
case SQLITE_OK:
break
case let code:
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
}
// The schema of the destination database has changed:
destDb.clearSchemaCache()
}
}
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress: Sendable {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
public let remainingPageCount: Int
/// The number of pages in the source database.
///
/// It is the result of the `sqlite3_backup_pagecount` function.
public let totalPageCount: Int
/// The number of of backed up pages.
///
/// It is equal to `totalPageCount - remainingPageCount`.
public var completedPageCount: Int {
totalPageCount - remainingPageCount
}
/// A boolean value indicating whether the backup is complete.
///
/// It is true if and only if the last call the `sqlite3_backup_step` has
/// returned `SQLITE_DONE`.
public let isCompleted: Bool
}
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
/// A cache for the available database schemas.
struct SchemaCache {
@@ -1,9 +1,15 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
extension Database {
// MARK: - Statements
/// Returns a new prepared statement that can be reused.
///
/// For example:
@@ -430,6 +436,7 @@ extension Database {
// documentation of this method for more information).
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
// Cancelled database accesses must not execute.
// Suspended databases must not execute statements that create the risk
// of `0xdead10cc` exception (see the documentation of this method for
// more information).
@@ -482,6 +489,19 @@ extension Database {
// and throws the user-provided cancelled commit error.
try observationBroker?.statementDidFail(statement)
if #available(iOS 13, macOS 10.15, tvOS 13, *) {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
if suspensionMutex.load().isCancelled {
// The only error that a user sees when a Task is cancelled
// is CancellationError.
throw CancellationError()
}
default:
break
}
}
// Throw statement failure
throw DatabaseError(
resultCode: resultCode,
@@ -538,7 +558,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, *) { // SQLite 3.20+
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
} else {
statement = try db.makeStatement(sql: sql)
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite connection, suitable for the SQLite C API.
@@ -6,7 +15,9 @@ public typealias SQLiteConnection = OpaquePointer
/// A raw SQLite function argument.
typealias SQLiteValue = OpaquePointer
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(
OpaquePointer(bitPattern: -1),
to: sqlite3_destructor_type.self)
/// An SQLite connection.
///
@@ -113,8 +124,14 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``logError``
/// - ``releaseMemory()``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
///
/// - ``BusyCallback``
/// - ``BusyMode``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``LogErrorFunction``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
@@ -124,8 +141,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
@@ -136,8 +151,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The error logging function.
///
/// SQLite can be configured to invoke a callback function containing
/// an error code and a terse error message whenever anomalies occur.
///
/// This global error callback must be configured early in the lifetime
/// of your application:
///
/// ```swift
/// Database.logError = { (resultCode, message) in
/// NSLog("%@", "SQLite error \(resultCode): \(message)")
/// }
/// ```
///
/// - warning: Database.logError must be set before any database
/// connection is opened. This includes the connections that your
/// application opens with GRDB, but also connections opened by
/// other tools, such as third-party libraries. Setting it after a
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// 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
@@ -281,18 +314,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// `isRecordingSelectedRegion` is true.
var selectedRegion = DatabaseRegion()
/// Support for `checkForAbortedTransaction()`
var isInsideTransactionBlock = false
/// Support for `checkForSuspensionViolation(from:)`
@LockedBox var isSuspended = false
/// Support for `checkForSuspensionViolation(from:)`
/// This cache is never cleared: we assume journal mode never changes.
var journalModeCache: String?
// MARK: - Suspension
struct Suspension {
/// If true, the database is suspended and should not acquire any
/// write lock in order to avoid the 0xDEAD10CC exception.
var isSuspended: Bool
/// If true, the database access has been cancelled.
var isCancelled: Bool
}
/// Support for `checkForSuspensionViolation(from:)`
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
// MARK: - Transaction Date
/// Support for `checkForAbortedTransaction()`
var isInsideTransactionBlock = false
enum AutocommitState {
case off
case on
@@ -604,7 +648,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
guard code == SQLITE_OK else {
// So there remain some unfinalized prepared statement somewhere.
if let log = Self.logError {
if code == SQLITE_BUSY {
if ResultCode(rawValue: code).primaryResultCode == .SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
@@ -1118,22 +1162,25 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// Suspension ends with `resume()`.
func suspend() {
$isSuspended.update { isSuspended in
if isSuspended {
return
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isSuspended {
return false
}
// Prevent future lock acquisition
isSuspended = true
// Interrupt the database because this may trigger an
// SQLITE_INTERRUPT error which may itself abort a transaction and
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
suspension.isSuspended = true
return true
}
if needsInterrupt {
// Interrupting the database can trigger an SQLITE_INTERRUPT
// error which may itself abort a transaction and
// release a database lock, which is our goal.
// See <https://www.sqlite.org/c3ref/interrupt.html>
//
// Maybe interrupt will not release any lock. To address this,
// we'll issue a rollback on next database access which requires
// a lock. See `checkForSuspensionViolation(from:).`
interrupt()
// Now what about the eventual remaining lock? We'll issue a
// rollback on next database access which requires a lock, in
// checkForSuspensionViolation(from:).
}
}
@@ -1145,7 +1192,37 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See suspend().
func resume() {
isSuspended = false
suspensionMutex.withLock {
$0.isSuspended = false
}
}
/// Cancels the current database access. All statements but ROLLBACK
/// will throw `CancellationError`, until `uncancel()` is called.
///
/// This method can be called from any thread.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func cancel() {
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
}
suspension.isCancelled = true
return true
}
if needsInterrupt {
interrupt()
}
}
/// Undo `cancel()`.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func uncancel() {
suspensionMutex.withLock {
$0.isCancelled = false
}
}
/// Support for `checkForSuspensionViolation(from:)`
@@ -1169,15 +1246,51 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return journalMode
}
/// If the database is suspended, and executing the statement would lock the
/// database in a way that may trigger the [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report),
/// this method rollbacks the current transaction and throws `SQLITE_ABORT`.
/// Prevents a statement from running, if the database is suspended, or
/// if the current database access is cancelled by Task cancellation.
///
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
/// Transaction rollbacks are always allowed. For other statements:
///
/// - When database access is cancelled, this method
/// throws `CancellationError`.
///
/// - When database is suspensed, and if the statement would lock the
/// database in a way that may trigger the 0xDEAD10CC exception, this
/// method rollbacks the current transaction and throws `SQLITE_ABORT`.
///
/// See `cancel()`, `suspend()` and
/// ``Configuration/observesSuspensionNotifications``.
func checkForSuspensionViolation(from statement: Statement) throws {
try $isSuspended.read { isSuspended in
guard isSuspended else {
return
// No reason for suspension should prevent rollbacks:
//
// - A rollback releases the write lock when the database
// is interrupted, when preventing 0xDEAD10CC.
//
// - A rollback properly closes a transaction that fails because
// it runs in a Task that was cancelled.
//
// Finally, a rollback must be run by GRDB, not by a direct call
// to `sqlite3_exec`, so that transaction observers are
// properly notified.
if statement.transactionEffect == .rollbackTransaction {
return
}
// How should we interrupt the statement?
enum Interrupt {
case abort // Rollback and throw SQLITE_ABORT
case cancel // Throw CancellationError
}
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
// Check for cancellation first, so that the only error that
// a user sees when a Task is cancelled is CancellationError.
if suspension.isCancelled {
return .cancel
}
guard suspension.isSuspended else {
return nil
}
if try journalMode() == "wal" && statement.isReadonly {
@@ -1188,7 +1301,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Those are not read-only:
// - INSERT ...
// - BEGIN IMMEDIATE TRANSACTION
return
return nil
}
if statement.releasesDatabaseLock {
@@ -1197,15 +1310,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// - ROLLBACK
// - ROLLBACK TRANSACTION TO SAVEPOINT
// - RELEASE SAVEPOINT
return
return nil
}
// Assume statement can acquire a write lock: abort.
return .abort
}
switch interrupt {
case nil:
break
case .cancel:
if #available(iOS 13, macOS 10.15, tvOS 13, *) {
throw CancellationError()
} else {
// GRDB bug: cancellation is a Swift concurrency feature
fatalError("Can't cancel without support for Swift concurrency")
}
case .abort:
// Attempt at releasing an eventual lock with ROLLBACk,
// as explained in Database.suspend().
//
// Use sqlite3_exec instead of `try? rollback()` in order to avoid
// an infinite loop in checkForSuspensionViolation(from:)
_ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
try? rollback()
throw DatabaseError(
resultCode: .SQLITE_ABORT,
@@ -1275,14 +1402,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Use ``inSavepoint(_:)`` instead.
///
/// - parameters:
/// - kind: The transaction type (default nil).
/// - kind: The transaction type.
///
/// If nil, and the database connection is read-only, the transaction
/// kind is ``TransactionKind/deferred``.
///
/// If nil, and the database connection is not read-only, the
/// transaction kind is the ``Configuration/defaultTransactionKind``
/// of the ``configuration``.
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// - operations: A function that executes SQL statements and returns
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
@@ -1406,8 +1529,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// By default, top level SQLite savepoints open a
// deferred transaction.
//
// But GRDB database configuration mandates a default transaction
// kind that we have to honor.
// But GRDB prefers immediate transactions for writes.
//
// Besides, starting some (?) SQLCipher/SQLite version, SQLite has a
// bug. Returning 1 from `sqlite3_commit_hook` does not leave the
@@ -1497,16 +1619,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, and the database connection is read-only, the transaction
/// kind is ``TransactionKind/deferred``.
///
/// If nil, and the database connection is not read-only, the
/// transaction kind is the ``Configuration/defaultTransactionKind``
/// of the ``configuration``.
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
// SQLite throws an error for non-deferred transactions when read-only.
let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind)
// We prefer immediate transactions for writes, so that write
// transactions can not overlap. This reduces the opportunity for
// SQLITE_BUSY, which is immediately thrown whenever a transaction
// is upgraded after an initial read and a concurrent processes
// has acquired the write lock beforehand. This SQLITE_BUSY error
// can not be avoided with a busy timeout.
//
// See <https://github.com/groue/GRDB.swift/issues/1483>.
let kind = kind ?? (isReadOnly ? .deferred : .immediate)
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
}
@@ -1620,117 +1746,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
try DatabaseQueue().backup(to: self)
#endif
}
// MARK: - Backup
/// Copies the database contents into another database.
///
/// The `backup` method blocks the current thread until the destination
/// database contains the same contents as the source database.
///
/// Usage:
///
/// ```swift
/// let source: DatabaseQueue = ...
/// let destination: DatabaseQueue = ...
/// try source.write { sourceDb in
/// try destination.barrierWriteWithoutTransaction { destDb in
/// try sourceDb.backup(to: destDb)
/// }
/// }
/// ```
///
/// When you're after progress reporting during backup, you'll want to
/// perform the backup in several steps. Each step copies the number of
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
/// for more information:
///
/// ```swift
/// // Backup with progress reporting
/// try sourceDb.backup(to: destDb, pagesPerStep: ...) { progress in
/// print("Database backup progress:", progress)
/// }
/// ```
///
/// The `progress` callback will be called at least once—when
/// `backupProgress.isCompleted == true`. If the callback throws
/// when `backupProgress.isCompleted == false`, the backup is aborted
/// and the error is rethrown. If the callback throws when
/// `backupProgress.isCompleted == true`, backup completion is
/// unaffected and the error is silently ignored.
///
/// See also ``DatabaseReader/backup(to:pagesPerStep:progress:)``.
///
/// - parameters:
/// - destDb: The destination database.
/// - pagesPerStep: The number of database pages copied on each backup
/// step. By default, all pages are copied in one single step.
/// - progress: An optional function that is notified of the backup
/// progress.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `progress`.
public func backup(
to destDb: Database,
pagesPerStep: CInt = -1,
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
throws
{
try backupInternal(
to: destDb,
pagesPerStep: pagesPerStep,
afterBackupStep: progress)
}
func backupInternal(
to destDb: Database,
pagesPerStep: CInt = -1,
afterBackupInit: (() -> Void)? = nil,
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
throws
{
guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else {
throw DatabaseError(resultCode: destDb.lastErrorCode, message: destDb.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError()
}
afterBackupInit?()
do {
backupLoop: while true {
let rc = sqlite3_backup_step(backup, pagesPerStep)
let totalPageCount = Int(sqlite3_backup_pagecount(backup))
let remainingPageCount = Int(sqlite3_backup_remaining(backup))
let progress = DatabaseBackupProgress(
remainingPageCount: remainingPageCount,
totalPageCount: totalPageCount,
isCompleted: rc == SQLITE_DONE)
switch rc {
case SQLITE_DONE:
try? afterBackupStep?(progress)
break backupLoop
case SQLITE_OK:
try afterBackupStep?(progress)
case let code:
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
}
}
} catch {
sqlite3_backup_finish(backup)
throw error
}
switch sqlite3_backup_finish(backup) {
case SQLITE_OK:
break
case let code:
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
}
// The schema of the destination database has changed:
destDb.clearSchemaCache()
}
}
// Explicit non-conformance to Sendable: `Database` must be used from a
@@ -1816,8 +1831,8 @@ extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
/// See ``BusyMode`` and <https://www.sqlite.org/c3ref/busy_handler.html>
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.
@@ -1845,7 +1860,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
@@ -1923,7 +1938,6 @@ extension Database {
/// 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
@@ -2006,7 +2020,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 SQLite storage class.
///
+106
View File
@@ -0,0 +1,106 @@
/// A cursor that lazily iterates the results of a prepared ``Statement``.
///
/// ## Overview
///
/// To get a `DatabaseCursor` instance, use one of the `fetchCursor` methods.
/// For example:
///
/// - A cursor of ``Row`` built from a prepared ``Statement``:
///
/// ```swift
/// try dbQueue.read { db in
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
/// let rows = try Row.fetchCursor(statement)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// - A cursor of `Int` built from an SQL string (see ``DatabaseValueConvertible``):
///
/// ```swift
/// try dbQueue.read { db in
/// let sql = "SELECT score FROM player"
/// let scores = try Int.fetchCursor(db, sql: sql)
/// while let score = try scores.next() {
/// print(score)
/// }
/// }
/// ```
///
/// - A cursor of `Player` records built from a request (see ``FetchableRecord`` and ``FetchRequest``):
///
/// ```swift
/// try dbQueue.read { db in
/// let request = Player.all()
/// let players = try request.fetchCursor(db)
/// while let player = try players.next() {
/// print(player.name, player.score)
/// }
/// }
/// ```
///
/// A database cursor is valid only during the current database access (read or
/// write). Do not store or escape a cursor for later use.
///
/// A database cursor resets its underlying prepared statement with
/// [`sqlite3_reset`](https://www.sqlite.org/c3ref/reset.html) when the cursor
/// is created, and when it is deallocated. Don't share the same prepared
/// statement between two cursors!
public protocol DatabaseCursor<Element>: Cursor {
/// Must be initialized to false.
var _isDone: Bool { get set }
/// The statement iterated by the cursor
var _statement: Statement { get }
/// Called after one successful call to `sqlite3_step()`. Returns the
/// element for the current statement step.
func _element(sqliteStatement: SQLiteStatement) throws -> Element
}
// Read-only access to statement information. We don't want the user to modify
// a statement through a cursor, in case this would mess with the cursor state.
extension DatabaseCursor {
/// The SQL query.
public var sql: String { _statement.sql }
/// The statement arguments.
public var arguments: StatementArguments { _statement.arguments }
/// The column names, ordered from left to right.
public var columnNames: [String] { _statement.columnNames }
/// The number of columns in the resulting rows.
public var columnCount: Int { _statement.columnCount }
/// The database region that the cursor looks into.
public var databaseRegion: DatabaseRegion { _statement.databaseRegion }
}
extension DatabaseCursor {
@inlinable
public func next() throws -> Element? {
if _isDone {
return nil
}
if let element = try _statement.step(_element) {
return element
}
_isDone = true
return nil
}
// Specific implementation of `forEach`, for a slight performance
// improvement due to the single `sqlite3_stmt_busy` check.
@inlinable
public func forEach(_ body: (Element) throws -> Void) throws {
if _isDone { return }
try _statement.forEachStep {
try body(_element(sqliteStatement: $0))
}
_isDone = true
}
}
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -26,7 +35,7 @@ extension String {
}
public final class Statement {
enum TransactionEffect {
enum TransactionEffect: Equatable {
case beginTransaction
case commitTransaction
case rollbackTransaction
@@ -137,7 +146,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, *) { // SQLite 3.20+
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
@@ -227,7 +236,7 @@ public final class Statement {
}()
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
fileprivate lazy var sqliteArgumentNames: [String?] = {
lazy var sqliteArgumentNames: [String?] = {
(1..<CInt(sqliteArgumentCount + 1)).map {
guard let cString = sqlite3_bind_parameter_name(sqliteStatement, $0) else {
return nil
@@ -657,150 +666,6 @@ extension Statement {
}
}
// MARK: - Cursors
/// A cursor that lazily iterates the results of a prepared ``Statement``.
///
/// ## Overview
///
/// To get a `DatabaseCursor` instance, use one of the `fetchCursor` methods.
/// For example:
///
/// - A cursor of ``Row`` built from a prepared ``Statement``:
///
/// ```swift
/// try dbQueue.read { db in
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
/// let rows = try Row.fetchCursor(statement)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// - A cursor of `Int` built from an SQL string (see ``DatabaseValueConvertible``):
///
/// ```swift
/// try dbQueue.read { db in
/// let sql = "SELECT score FROM player"
/// let scores = try Int.fetchCursor(db, sql: sql)
/// while let score = try scores.next() {
/// print(score)
/// }
/// }
/// ```
///
/// - A cursor of `Player` records built from a request (see ``FetchableRecord`` and ``FetchRequest``):
///
/// ```swift
/// try dbQueue.read { db in
/// let request = Player.all()
/// let players = try request.fetchCursor(db)
/// while let player = try players.next() {
/// print(player.name, player.score)
/// }
/// }
/// ```
///
/// A database cursor is valid only during the current database access (read or
/// write). Do not store or escape a cursor for later use.
///
/// A database cursor resets its underlying prepared statement with
/// [`sqlite3_reset`](https://www.sqlite.org/c3ref/reset.html) when the cursor
/// is created, and when it is deallocated. Don't share the same prepared
/// statement between two cursors!
public protocol DatabaseCursor: Cursor {
/// Must be initialized to false.
var _isDone: Bool { get set }
/// The statement iterated by the cursor
var _statement: Statement { get }
/// Called after one successful call to `sqlite3_step()`. Returns the
/// element for the current statement step.
func _element(sqliteStatement: SQLiteStatement) throws -> Element
}
// Read-only access to statement information. We don't want the user to modify
// a statement through a cursor, in case this would mess with the cursor state.
extension DatabaseCursor {
/// The SQL query.
public var sql: String { _statement.sql }
/// The statement arguments.
public var arguments: StatementArguments { _statement.arguments }
/// The column names, ordered from left to right.
public var columnNames: [String] { _statement.columnNames }
/// The number of columns in the resulting rows.
public var columnCount: Int { _statement.columnCount }
/// The database region that the cursor looks into.
public var databaseRegion: DatabaseRegion { _statement.databaseRegion }
}
extension DatabaseCursor {
@inlinable
public func next() throws -> Element? {
if _isDone {
return nil
}
if let element = try _statement.step(_element) {
return element
}
_isDone = true
return nil
}
// Specific implementation of `forEach`, for a slight performance
// improvement due to the single `sqlite3_stmt_busy` check.
@inlinable
public func forEach(_ body: (Element) throws -> Void) throws {
if _isDone { return }
try _statement.forEachStep {
try body(_element(sqliteStatement: $0))
}
_isDone = true
}
}
/// A cursor that iterates a database statement without producing any value.
/// Each call to the `next()` method calls the `sqlite3_step()` C function.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let statement = try db.makeStatement(sql: "SELECT performSideEffect()")
/// let cursor = statement.makeCursor()
/// try cursor.next()
/// }
/// ```
final class StatementCursor: DatabaseCursor {
typealias Element = Void
let _statement: Statement
var _isDone = false
// Use Statement.makeCursor() instead
init(statement: Statement, arguments: StatementArguments? = nil) throws {
self._statement = statement
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
}
@inlinable
func _element(sqliteStatement: SQLiteStatement) throws { }
}
// MARK: - Update Statements
extension Statement {
@@ -876,523 +741,3 @@ where C: Collection, C.Element == DatabaseValue
do: body)
}
}
// MARK: - StatementArguments
/// An instance of `StatementArguments` provides the values for argument
/// placeholders in a prepared `Statement`.
///
/// Argument placeholders can take several forms in SQL queries (see
/// <https://www.sqlite.org/lang_expr.html#varparam> for more information):
///
/// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1)
/// - `?`: the N-th argument, where N is one greater than the largest argument
/// number already assigned
/// - `:AAAA` (e.g. `:name`): named argument
/// - `@AAAA` (e.g. `@name`): named argument
/// - `$AAAA` (e.g. `$name`): named argument
///
/// All forms are supported, but GRDB does not allow to distinguish between
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
/// named arguments with a colon prefix: `:name`.
///
/// ## Positional Arguments
///
/// To fill question marks placeholders, feed `StatementArguments` with an array:
///
/// ```swift
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
/// arguments: StatementArguments(["Arthur", 41]))
///
/// // Array literals are automatically converted:
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
/// arguments: ["Arthur", 41])
/// ```
///
/// ## Named Arguments
///
/// To fill named arguments, feed `StatementArguments` with a dictionary:
///
/// ```swift
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)",
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
///
/// // Dictionary literals are automatically converted:
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)",
/// arguments: ["name": "Arthur", "score": 41])
/// ```
///
/// ## Concatenating Arguments
///
/// Several arguments can be concatenated and mixed with the
/// ``append(contentsOf:)`` method and the `+`, `&+`, `+=` operators:
///
/// ```swift
/// var arguments: StatementArguments = ["Arthur"]
/// arguments += [41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
/// arguments: arguments)
/// ```
///
/// The `+` and `+=` operators consider that overriding named arguments is a
/// programmer error:
///
/// ```swift
/// var arguments: StatementArguments = ["name": "Arthur"]
///
/// // fatal error: already defined statement argument: name
/// arguments += ["name": "Barbara"]
/// ```
///
/// On the other side, `&+` and ``append(contentsOf:)`` allow overriding
/// named arguments:
///
/// ```swift
/// var arguments: StatementArguments = ["name": "Arthur"]
/// arguments = arguments &+ ["name": "Barbara"]
///
/// // Prints ["name": "Barbara"]
/// print(arguments)
/// ```
///
/// ## Mixed Arguments
///
/// It is possible to mix named and positional arguments. Yet this is usually
/// confusing, and it is best to avoid this practice:
///
/// ```swift
/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
/// let row = try Row.fetchOne(db, sql: sql, arguments: arguments)!
///
/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
/// print(row)
/// ```
///
/// Mixed arguments exist as a support for requests like the following:
///
/// ```swift
/// let players = try Player
/// .filter(sql: "team = :team", arguments: ["team": "Blue"])
/// .filter(sql: "score > ?", arguments: [1000])
/// .fetchAll(db)
/// ```
public struct StatementArguments: Hashable {
private(set) var values: [DatabaseValue]
private(set) var namedValues: [String: DatabaseValue]
public var isEmpty: Bool {
values.isEmpty && namedValues.isEmpty
}
// MARK: Empty Arguments
/// Creates an empty `StatementArguments`.
public init() {
values = .init()
namedValues = .init()
}
// MARK: Positional Arguments
/// Creates a `StatementArguments` from a sequence of values.
///
/// For example:
///
/// ```swift
/// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil]
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
/// ```
public init<S>(_ sequence: S)
where S: Sequence, S.Element == (any DatabaseValueConvertible)?
{
values = sequence.map { $0?.databaseValue ?? .null }
namedValues = .init()
}
/// Creates a `StatementArguments` from a sequence of values.
///
/// For example:
///
/// ```swift
/// let values: [String] = ["foo", "bar"]
/// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
/// ```
public init<S>(_ sequence: S)
where S: Sequence, S.Element: DatabaseValueConvertible
{
values = sequence.map(\.databaseValue)
namedValues = .init()
}
/// Creates a `StatementArguments` from an array.
///
/// The result is nil unless all array elements conform to the
/// ``DatabaseValueConvertible`` protocol.
public init?(_ array: [Any]) {
var values = [(any DatabaseValueConvertible)?]()
for value in array {
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
values.append(dbValue)
}
self.init(values)
}
private mutating func set(databaseValues: [DatabaseValue]) {
self.values = databaseValues
namedValues.removeAll(keepingCapacity: true)
}
// MARK: Named Arguments
/// Creates a `StatementArguments` of named arguments from a dictionary.
///
/// For example:
///
/// ```swift
/// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
/// ```
public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
values = .init()
}
/// Creates a `StatementArguments` of named arguments from a sequence of
/// (key, value) pairs.
public init<S>(_ sequence: S)
where S: Sequence, S.Element == (String, (any DatabaseValueConvertible)?)
{
namedValues = .init(minimumCapacity: sequence.underestimatedCount)
for (key, value) in sequence {
namedValues[key] = value?.databaseValue ?? .null
}
values = .init()
}
/// Creates a `StatementArguments` from a dictionary.
///
/// The result is nil unless all dictionary keys are strings, and values
/// adopt DatabaseValueConvertible.
///
/// - parameter dictionary: A dictionary.
public init?(_ dictionary: [AnyHashable: Any]) {
var initDictionary = [String: (any DatabaseValueConvertible)?]()
for (key, value) in dictionary {
guard let columnName = key as? String else {
return nil
}
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
initDictionary[columnName] = dbValue
}
self.init(initDictionary)
}
// MARK: Adding arguments
/// Appends statement arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// var arguments: StatementArguments = [1]
/// arguments.append(contentsOf: [2, 3])
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted or updated:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments.append(contentsOf: ["bar": 2])
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// Named arguments that were replaced, if any, are returned:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1, "bar": 2]
/// let replacedValues = arguments.append(contentsOf: ["foo": 3])
///
/// // Prints ["foo": 3, "bar": 2]
/// print(arguments)
///
/// // Prints ["foo": 1]
/// print(replacedValues)
/// ```
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments.append(contentsOf: [2, 3])
///
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public mutating func append(contentsOf arguments: StatementArguments) -> [String: DatabaseValue] {
var replacedValues: [String: DatabaseValue] = [:]
values.append(contentsOf: arguments.values)
for (name, value) in arguments.namedValues {
if let replacedValue = namedValues.updateValue(value, forKey: name) {
replacedValues[name] = replacedValue
}
}
return replacedValues
}
/// Creates a new `StatementArguments` by extending the left-hand size
/// arguments with the right-hand side arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// let arguments: StatementArguments = [1] + [2, 3]
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] + ["bar": 2]
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// If the arguments on the right-hand side has named parameters that are
/// already defined on the left, a fatal error is raised:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] + ["foo": 2]
/// // fatal error: already defined statement argument: foo
/// ```
///
/// This fatal error can be avoided with the &+ operator, or the
/// ``append(contentsOf:)`` method.
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] + [2, 3]
///
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public static func + (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments {
var lhs = lhs
lhs += rhs
return lhs
}
/// Creates a new `StatementArguments` by extending the left-hand size
/// arguments with the right-hand side arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// let arguments: StatementArguments = [1] &+ [2, 3]
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted or updated:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] &+ ["bar": 2]
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// If a named arguments is defined in both arguments, the right-hand
/// side wins:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] &+ ["foo": 2]
///
/// // Prints ["foo": 2]
/// print(arguments)
/// ```
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] &+ [2, 3]
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public static func &+ (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments {
var lhs = lhs
_ = lhs.append(contentsOf: rhs)
return lhs
}
/// Extends the left-hand size arguments with the right-hand side arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// var arguments: StatementArguments = [1]
/// arguments += [2, 3]
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments += ["bar": 2]
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// If the arguments on the right-hand side has named parameters that are
/// already defined on the left, a fatal error is raised:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
///
/// // fatal error: already defined statement argument: foo
/// arguments += ["foo": 2]
/// ```
///
/// This fatal error can be avoided with the &+ operator, or the
/// ``append(contentsOf:)`` method.
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments.append(contentsOf: [2, 3])
///
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public static func += (lhs: inout StatementArguments, rhs: StatementArguments) {
let replacedValues = lhs.append(contentsOf: rhs)
GRDBPrecondition(
replacedValues.isEmpty,
"already defined statement argument: \(replacedValues.keys.joined(separator: ", "))")
}
// MARK: Not Public
mutating func extractBindings(
forStatement statement: Statement,
allowingRemainingValues: Bool)
throws -> [DatabaseValue]
{
var iterator = values.makeIterator()
var consumedValuesCount = 0
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
if let argumentName {
if let dbValue = namedValues[argumentName] {
return dbValue
} else if let value = iterator.next() {
consumedValuesCount += 1
return value
} else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "missing statement argument: \(argumentName)",
sql: statement.sql)
}
} else if let value = iterator.next() {
consumedValuesCount += 1
return value
} else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(values.count)",
sql: statement.sql)
}
}
if !allowingRemainingValues && iterator.next() != nil {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(values.count)",
sql: statement.sql)
}
if consumedValuesCount == values.count {
values.removeAll()
} else {
values = Array(values[consumedValuesCount...])
}
return bindings
}
}
extension StatementArguments: ExpressibleByArrayLiteral {
/// Creates a `StatementArguments` from an array literal.
///
/// For example:
///
/// ```swift
/// let arguments: StatementArguments = ["Arthur", 41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)"
/// arguments: arguments)
/// ```
public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) {
self.init(elements)
}
}
extension StatementArguments: ExpressibleByDictionaryLiteral {
/// Creates a `StatementArguments` from a dictionary literal.
///
/// For example:
///
/// ```swift
/// let arguments: StatementArguments = ["name": "Arthur", "score": 41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)"
/// arguments: arguments)
/// ```
public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
self.init(elements)
}
}
extension StatementArguments: CustomStringConvertible {
public var description: String {
let valuesDescriptions = values.map(\.description)
let namedValuesDescriptions = namedValues.map { (key, value) in
"\(String(reflecting: key)): \(value)"
}
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
}
extension StatementArguments: Sendable { }
+518
View File
@@ -0,0 +1,518 @@
/// An instance of `StatementArguments` provides the values for argument
/// placeholders in a prepared `Statement`.
///
/// Argument placeholders can take several forms in SQL queries (see
/// <https://www.sqlite.org/lang_expr.html#varparam> for more information):
///
/// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1)
/// - `?`: the N-th argument, where N is one greater than the largest argument
/// number already assigned
/// - `:AAAA` (e.g. `:name`): named argument
/// - `@AAAA` (e.g. `@name`): named argument
/// - `$AAAA` (e.g. `$name`): named argument
///
/// All forms are supported, but GRDB does not allow to distinguish between
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
/// named arguments with a colon prefix: `:name`.
///
/// ## Positional Arguments
///
/// To fill question marks placeholders, feed `StatementArguments` with an array:
///
/// ```swift
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
/// arguments: StatementArguments(["Arthur", 41]))
///
/// // Array literals are automatically converted:
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
/// arguments: ["Arthur", 41])
/// ```
///
/// ## Named Arguments
///
/// To fill named arguments, feed `StatementArguments` with a dictionary:
///
/// ```swift
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)",
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
///
/// // Dictionary literals are automatically converted:
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)",
/// arguments: ["name": "Arthur", "score": 41])
/// ```
///
/// ## Concatenating Arguments
///
/// Several arguments can be concatenated and mixed with the
/// ``StatementArguments/append(contentsOf:)`` method and the `+`, `&+`,
/// `+=` operators:
///
/// ```swift
/// var arguments: StatementArguments = ["Arthur"]
/// arguments += [41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
/// arguments: arguments)
/// ```
///
/// The `+` and `+=` operators consider that overriding named arguments is a
/// programmer error:
///
/// ```swift
/// var arguments: StatementArguments = ["name": "Arthur"]
///
/// // fatal error: already defined statement argument: name
/// arguments += ["name": "Barbara"]
/// ```
///
/// On the other side, `&+` and ``StatementArguments/append(contentsOf:)``
/// allow overriding named arguments:
///
/// ```swift
/// var arguments: StatementArguments = ["name": "Arthur"]
/// arguments = arguments &+ ["name": "Barbara"]
///
/// // Prints ["name": "Barbara"]
/// print(arguments)
/// ```
///
/// ## Mixed Arguments
///
/// It is possible to mix named and positional arguments. Yet this is usually
/// confusing, and it is best to avoid this practice:
///
/// ```swift
/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
/// let row = try Row.fetchOne(db, sql: sql, arguments: arguments)!
///
/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
/// print(row)
/// ```
///
/// Mixed arguments exist as a support for requests like the following:
///
/// ```swift
/// let players = try Player
/// .filter(sql: "team = :team", arguments: ["team": "Blue"])
/// .filter(sql: "score > ?", arguments: [1000])
/// .fetchAll(db)
/// ```
public struct StatementArguments: Hashable {
private(set) var values: [DatabaseValue]
private(set) var namedValues: [String: DatabaseValue]
public var isEmpty: Bool {
values.isEmpty && namedValues.isEmpty
}
// MARK: Empty Arguments
/// Creates an empty `StatementArguments`.
public init() {
values = .init()
namedValues = .init()
}
// MARK: Positional Arguments
/// Creates a `StatementArguments` from a sequence of values.
///
/// For example:
///
/// ```swift
/// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil]
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
/// ```
public init<S>(_ sequence: S)
where S: Sequence, S.Element == (any DatabaseValueConvertible)?
{
values = sequence.map { $0?.databaseValue ?? .null }
namedValues = .init()
}
/// Creates a `StatementArguments` from a sequence of values.
///
/// For example:
///
/// ```swift
/// let values: [String] = ["foo", "bar"]
/// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
/// ```
public init<S>(_ sequence: S)
where S: Sequence, S.Element: DatabaseValueConvertible
{
values = sequence.map(\.databaseValue)
namedValues = .init()
}
/// Creates a `StatementArguments` from an array.
///
/// The result is nil unless all array elements conform to the
/// ``DatabaseValueConvertible`` protocol.
public init?(_ array: [Any]) {
var values = [(any DatabaseValueConvertible)?]()
for value in array {
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
values.append(dbValue)
}
self.init(values)
}
private mutating func set(databaseValues: [DatabaseValue]) {
self.values = databaseValues
namedValues.removeAll(keepingCapacity: true)
}
// MARK: Named Arguments
/// Creates a `StatementArguments` of named arguments from a dictionary.
///
/// For example:
///
/// ```swift
/// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
/// ```
public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
values = .init()
}
/// Creates a `StatementArguments` of named arguments from a sequence of
/// (key, value) pairs.
public init<S>(_ sequence: S)
where S: Sequence, S.Element == (String, (any DatabaseValueConvertible)?)
{
namedValues = .init(minimumCapacity: sequence.underestimatedCount)
for (key, value) in sequence {
namedValues[key] = value?.databaseValue ?? .null
}
values = .init()
}
/// Creates a `StatementArguments` from a dictionary.
///
/// The result is nil unless all dictionary keys are strings, and values
/// adopt DatabaseValueConvertible.
///
/// - parameter dictionary: A dictionary.
public init?(_ dictionary: [AnyHashable: Any]) {
var initDictionary = [String: (any DatabaseValueConvertible)?]()
for (key, value) in dictionary {
guard let columnName = key as? String else {
return nil
}
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
initDictionary[columnName] = dbValue
}
self.init(initDictionary)
}
// MARK: Adding arguments
/// Appends statement arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// var arguments: StatementArguments = [1]
/// arguments.append(contentsOf: [2, 3])
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted or updated:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments.append(contentsOf: ["bar": 2])
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// Named arguments that were replaced, if any, are returned:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1, "bar": 2]
/// let replacedValues = arguments.append(contentsOf: ["foo": 3])
///
/// // Prints ["foo": 3, "bar": 2]
/// print(arguments)
///
/// // Prints ["foo": 1]
/// print(replacedValues)
/// ```
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments.append(contentsOf: [2, 3])
///
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public mutating func append(contentsOf arguments: StatementArguments) -> [String: DatabaseValue] {
var replacedValues: [String: DatabaseValue] = [:]
values.append(contentsOf: arguments.values)
for (name, value) in arguments.namedValues {
if let replacedValue = namedValues.updateValue(value, forKey: name) {
replacedValues[name] = replacedValue
}
}
return replacedValues
}
/// Creates a new `StatementArguments` by extending the left-hand size
/// arguments with the right-hand side arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// let arguments: StatementArguments = [1] + [2, 3]
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] + ["bar": 2]
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// If the arguments on the right-hand side has named parameters that are
/// already defined on the left, a fatal error is raised:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] + ["foo": 2]
/// // fatal error: already defined statement argument: foo
/// ```
///
/// This fatal error can be avoided with the &+ operator, or the
/// ``append(contentsOf:)`` method.
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] + [2, 3]
///
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public static func + (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments {
var lhs = lhs
lhs += rhs
return lhs
}
/// Creates a new `StatementArguments` by extending the left-hand size
/// arguments with the right-hand side arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// let arguments: StatementArguments = [1] &+ [2, 3]
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted or updated:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] &+ ["bar": 2]
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// If a named arguments is defined in both arguments, the right-hand
/// side wins:
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] &+ ["foo": 2]
///
/// // Prints ["foo": 2]
/// print(arguments)
/// ```
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// let arguments: StatementArguments = ["foo": 1] &+ [2, 3]
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public static func &+ (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments {
var lhs = lhs
_ = lhs.append(contentsOf: rhs)
return lhs
}
/// Extends the left-hand size arguments with the right-hand side arguments.
///
/// Positional arguments are concatenated:
///
/// ```swift
/// var arguments: StatementArguments = [1]
/// arguments += [2, 3]
///
/// // Prints [1, 2, 3]
/// print(arguments)
/// ```
///
/// Named arguments are inserted:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments += ["bar": 2]
///
/// // Prints ["foo": 1, "bar": 2]
/// print(arguments)
/// ```
///
/// If the arguments on the right-hand side has named parameters that are
/// already defined on the left, a fatal error is raised:
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
///
/// // fatal error: already defined statement argument: foo
/// arguments += ["foo": 2]
/// ```
///
/// This fatal error can be avoided with the &+ operator, or the
/// ``append(contentsOf:)`` method.
///
/// You can mix named and positional arguments (see the documentation of
/// the ``StatementArguments`` type for more information about
/// mixed arguments):
///
/// ```swift
/// var arguments: StatementArguments = ["foo": 1]
/// arguments.append(contentsOf: [2, 3])
///
/// // Prints ["foo": 1, 2, 3]
/// print(arguments)
/// ```
public static func += (lhs: inout StatementArguments, rhs: StatementArguments) {
let replacedValues = lhs.append(contentsOf: rhs)
GRDBPrecondition(
replacedValues.isEmpty,
"already defined statement argument: \(replacedValues.keys.joined(separator: ", "))")
}
// MARK: Not Public
mutating func extractBindings(
forStatement statement: Statement,
allowingRemainingValues: Bool)
throws -> [DatabaseValue]
{
var iterator = values.makeIterator()
var consumedValuesCount = 0
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
if let argumentName {
if let dbValue = namedValues[argumentName] {
return dbValue
} else if let value = iterator.next() {
consumedValuesCount += 1
return value
} else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "missing statement argument: \(argumentName)",
sql: statement.sql)
}
} else if let value = iterator.next() {
consumedValuesCount += 1
return value
} else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(values.count)",
sql: statement.sql)
}
}
if !allowingRemainingValues && iterator.next() != nil {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(values.count)",
sql: statement.sql)
}
if consumedValuesCount == values.count {
values.removeAll()
} else {
values = Array(values[consumedValuesCount...])
}
return bindings
}
}
extension StatementArguments: ExpressibleByArrayLiteral {
/// Creates a `StatementArguments` from an array literal.
///
/// For example:
///
/// ```swift
/// let arguments: StatementArguments = ["Arthur", 41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)"
/// arguments: arguments)
/// ```
public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) {
self.init(elements)
}
}
extension StatementArguments: ExpressibleByDictionaryLiteral {
/// Creates a `StatementArguments` from a dictionary literal.
///
/// For example:
///
/// ```swift
/// let arguments: StatementArguments = ["name": "Arthur", "score": 41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)"
/// arguments: arguments)
/// ```
public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
self.init(elements)
}
}
extension StatementArguments: CustomStringConvertible {
public var description: String {
let valuesDescriptions = values.map(\.description)
let namedValuesDescriptions = namedValues.map { (key, value) in
"\(String(reflecting: key)): \(value)"
}
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
}
extension StatementArguments: Sendable { }
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if os(Linux)
import Glibc
#endif
+34
View File
@@ -0,0 +1,34 @@
/// A cursor that iterates a database statement without producing any value.
/// Each call to the `next()` method calls the `sqlite3_step()` C function.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let statement = try db.makeStatement(sql: "SELECT performSideEffect()")
/// let cursor = statement.makeCursor()
/// try cursor.next()
/// }
/// ```
final class StatementCursor: DatabaseCursor {
typealias Element = Void
let _statement: Statement
var _isDone = false
// Use Statement.makeCursor() instead
init(statement: Statement, arguments: StatementArguments? = nil) throws {
self._statement = statement
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
}
@inlinable
func _element(sqliteStatement: SQLiteStatement) throws { }
}
@@ -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
}
-27
View File
@@ -1,27 +0,0 @@
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress: Sendable {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
public let remainingPageCount: Int
/// The number of pages in the source database.
///
/// It is the result of the `sqlite3_backup_pagecount` function.
public let totalPageCount: Int
/// The number of of backed up pages.
///
/// It is equal to `totalPageCount - remainingPageCount`.
public var completedPageCount: Int {
totalPageCount - remainingPageCount
}
/// A boolean value indicating whether the backup is complete.
///
/// It is true if and only if the last call the `sqlite3_backup_step` has
/// returned `SQLITE_DONE`.
public let isCompleted: Bool
}
+12 -3
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// `DatabaseCollation` is a custom string comparison function used by SQLite.
@@ -20,10 +29,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 +49,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.
+13
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// An SQLite result code.
@@ -406,6 +415,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`
+15 -6
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A custom SQL function or aggregate.
///
/// ## Topics
@@ -20,7 +29,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 +82,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 +274,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>
+1 -1
View File
@@ -1,5 +1,5 @@
#if canImport(Combine)
/// A namespace for database Combine publishers.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public enum DatabasePublishers { }
#endif
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A value stored in a database table.
@@ -129,7 +129,7 @@ private class DatabaseValueEncoder: Encoder {
// eventually perform JSON decoding.
// TODO: possible optimization: avoid this conversion to string,
// and store raw data bytes as an SQLite string
let jsonString = String(data: jsonData, encoding: .utf8)!
let jsonString = String(decoding: jsonData, as: UTF8.self)
try jsonString.encode(to: self)
}
}
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
///
-311
View File
@@ -1,311 +0,0 @@
// MARK: - FetchRequest
/// A type that fetches and decodes database rows.
///
/// The main kinds of fetch requests are ``SQLRequest``
/// and ``QueryInterfaceRequest``:
///
/// ```swift
/// let lastName = "O'Reilly"
///
/// // SQLRequest
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// // QueryInterfaceRequest
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // Use the request
/// try dbQueue.read { db in
/// let players = try request.fetchAll(db) // [Player]
/// }
/// ```
///
/// ## Topics
///
/// ### Counting the Results
///
/// - ``fetchCount(_:)``
///
/// ### Fetching Database Rows
///
/// - ``fetchCursor(_:)-9283d``
/// - ``fetchAll(_:)-7p809``
/// - ``fetchOne(_:)-9fafl``
/// - ``fetchSet(_:)-6bdrd``
///
/// ### Fetching Database Values
///
/// - ``fetchCursor(_:)-19f5g``
/// - ``fetchCursor(_:)-66xoi``
/// - ``fetchAll(_:)-1loau``
/// - ``fetchAll(_:)-28pne``
/// - ``fetchOne(_:)-44mvv``
/// - ``fetchOne(_:)-5hlkf``
/// - ``fetchSet(_:)-4hhtm``
/// - ``fetchSet(_:)-9wshm``
///
/// ### Fetching Records
///
/// - ``fetchCursor(_:)-2ah3q``
/// - ``fetchAll(_:)-vdos``
/// - ``fetchOne(_:)-2bq0k``
/// - ``fetchSet(_:)-4jdrq``
///
/// ### Preparing Database Requests
///
/// - ``makePreparedRequest(_:forSingleResult:)``
/// - ``PreparedRequest``
///
/// ### Adapting the Fetched Rows
///
/// - ``adapted(_:)``
/// - ``AdaptedFetchRequest``
///
/// ### Supporting Types
///
/// - ``AnyFetchRequest``
public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
/// Returns a ``PreparedRequest``.
///
/// The `singleResult` argument is a hint that a single result row will be
/// consumed. Implementations can optionally use it to optimize the
/// prepared statement, for example by adding a `LIMIT 1` SQL clause:
///
/// ```swift
/// // Calls makePreparedRequest(db, forSingleResult: true)
/// try request.fetchOne(db)
///
/// // Calls makePreparedRequest(db, forSingleResult: false)
/// try request.fetchAll(db)
/// ```
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed.
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
func fetchCount(_ db: Database) throws -> Int
}
extension FetchRequest {
/// Returns the database region that the request feeds from.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
}
}
// MARK: - PreparedRequest
/// A closure executed before a supplementary fetch is performed.
///
/// Support for `Database.dumpRequest`.
///
/// - parameter request: The supplementary request
/// - parameter keyPath: The key path target of the supplementary fetch.
typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _ keyPath: [String]) throws -> Void
/// A closure that performs supplementary fetches.
///
/// Support for eager loading of hasMany associations.
///
/// - parameter db: A database connection.
/// - parameter rows: The rows that are modified by the supplementary fetch.
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
/// performing supplementary fetches.
typealias SupplementaryFetch = (
_ db: Database,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequest {
/// A prepared statement with bound parameters.
public var statement: Statement
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: SupplementaryFetch?
init(
statement: Statement,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch? = nil)
{
self.statement = statement
self.adapter = adapter
self.supplementaryFetch = supplementaryFetch
}
}
// Explicit non-conformance to Sendable: `PreparedRequest` contains
// a statement.
@available(*, unavailable)
extension PreparedRequest: Sendable { }
extension PreparedRequest: Refinable { }
// MARK: - AdaptedFetchRequest
extension FetchRequest {
/// Returns an adapted request.
///
/// The returned request performs an identical database query, but adapts
/// the fetched rows. See ``RowAdapter``, and
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
/// `adapted(_:)`.
///
/// - 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> {
AdaptedFetchRequest(self, adapter)
}
}
/// An adapted request.
///
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: (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) {
self.base = base
self.adapter = adapter
}
}
extension AdaptedFetchRequest: SQLSubqueryable {
public var sqlSubquery: SQLSubquery {
base.sqlSubquery
}
}
extension AdaptedFetchRequest: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
public func fetchCount(_ db: Database) throws -> Int {
try base.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
if let baseAdapter = preparedRequest.adapter {
preparedRequest.adapter = try ChainedAdapter(first: baseAdapter, second: adapter(db))
} else {
preparedRequest.adapter = try adapter(db)
}
return preparedRequest
}
}
// MARK: - AnyFetchRequest
/// A type-erased FetchRequest.
///
/// An `AnyFetchRequest` forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<RowDecoder> {
private let request: FetchRequestEraser
/// Returns a request that performs an identical database query, but decodes
/// database rows with `type`.
///
/// For example:
///
/// ```swift
/// // AnyFetchRequest<Player>
/// let playerRequest = AnyFetchRequest(Player.all())
///
/// // AnyFetchRequest<Row>
/// let rowRequest = playerRequest.asRequest(of: Row.self)
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
AnyFetchRequest<T>(request: request)
}
}
extension AnyFetchRequest {
/// Creates a request that wraps and forwards operations to `request`.
public init(_ request: some FetchRequest<RowDecoder>) {
self.init(request: ConcreteFetchRequestEraser(request: request))
}
}
extension AnyFetchRequest: SQLSubqueryable {
public var sqlSubquery: SQLSubquery {
request.sqlSubquery
}
}
extension AnyFetchRequest: FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
// Class-based type erasure, so that we preserve full type information.
private class FetchRequestEraser: FetchRequest {
typealias RowDecoder = Void
var sqlSubquery: SQLSubquery {
fatalError("subclass must override")
}
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
fatalError("subclass must override")
}
func fetchCount(_ db: Database) throws -> Int {
fatalError("subclass must override")
}
}
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser {
let request: Request
init(request: Request) {
self.request = request
}
override var sqlSubquery: SQLSubquery {
request.sqlSubquery
}
override func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
@@ -0,0 +1,61 @@
/// An adapted request.
///
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
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 @Sendable (Database) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
}
extension AdaptedFetchRequest: SQLSubqueryable {
public var sqlSubquery: SQLSubquery {
base.sqlSubquery
}
}
extension AdaptedFetchRequest: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
public func fetchCount(_ db: Database) throws -> Int {
try base.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
if let baseAdapter = preparedRequest.adapter {
preparedRequest.adapter = try ChainedAdapter(first: baseAdapter, second: adapter(db))
} else {
preparedRequest.adapter = try adapter(db)
}
return preparedRequest
}
}
extension FetchRequest {
/// Returns an adapted request.
///
/// The returned request performs an identical database query, but adapts
/// the fetched rows. See ``RowAdapter``, and
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
/// `adapted(_:)`.
///
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
}
@@ -0,0 +1,88 @@
/// A type-erased FetchRequest.
///
/// An `AnyFetchRequest` forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<RowDecoder> {
private let request: FetchRequestEraser
/// Returns a request that performs an identical database query, but decodes
/// database rows with `type`.
///
/// For example:
///
/// ```swift
/// // AnyFetchRequest<Player>
/// let playerRequest = AnyFetchRequest(Player.all())
///
/// // AnyFetchRequest<Row>
/// let rowRequest = playerRequest.asRequest(of: Row.self)
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
AnyFetchRequest<T>(request: request)
}
}
extension AnyFetchRequest {
/// Creates a request that wraps and forwards operations to `request`.
public init(_ request: some FetchRequest<RowDecoder>) {
self.init(request: ConcreteFetchRequestEraser(request: request))
}
}
extension AnyFetchRequest: SQLSubqueryable {
public var sqlSubquery: SQLSubquery {
request.sqlSubquery
}
}
extension AnyFetchRequest: FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
// Class-based type erasure, so that we preserve full type information.
private class FetchRequestEraser: @unchecked Sendable {
// @unchecked Sendable because abstract.
typealias RowDecoder = Void
var sqlSubquery: SQLSubquery {
fatalError("subclass must override")
}
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
fatalError("subclass must override")
}
func fetchCount(_ db: Database) throws -> Int {
fatalError("subclass must override")
}
}
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser, @unchecked Sendable {
// @unchecked Sendable because Request is Sendable, and superclass is @unchecked Sendable
let request: Request
init(request: Request) {
self.request = request
}
override var sqlSubquery: SQLSubquery {
request.sqlSubquery
}
override func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
+106
View File
@@ -0,0 +1,106 @@
// MARK: - FetchRequest
/// A type that fetches and decodes database rows.
///
/// The main kinds of fetch requests are ``SQLRequest``
/// and ``QueryInterfaceRequest``:
///
/// ```swift
/// let lastName = "O'Reilly"
///
/// // SQLRequest
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// // QueryInterfaceRequest
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // Use the request
/// try dbQueue.read { db in
/// let players = try request.fetchAll(db) // [Player]
/// }
/// ```
///
/// ## Topics
///
/// ### Counting the Results
///
/// - ``fetchCount(_:)``
///
/// ### Fetching Database Rows
///
/// - ``fetchCursor(_:)-9283d``
/// - ``fetchAll(_:)-7p809``
/// - ``fetchOne(_:)-9fafl``
/// - ``fetchSet(_:)-6bdrd``
///
/// ### Fetching Database Values
///
/// - ``fetchCursor(_:)-19f5g``
/// - ``fetchCursor(_:)-66xoi``
/// - ``fetchAll(_:)-1loau``
/// - ``fetchAll(_:)-28pne``
/// - ``fetchOne(_:)-44mvv``
/// - ``fetchOne(_:)-5hlkf``
/// - ``fetchSet(_:)-4hhtm``
/// - ``fetchSet(_:)-9wshm``
///
/// ### Fetching Records
///
/// - ``fetchCursor(_:)-2ah3q``
/// - ``fetchAll(_:)-vdos``
/// - ``fetchOne(_:)-2bq0k``
/// - ``fetchSet(_:)-4jdrq``
///
/// ### Preparing Database Requests
///
/// - ``makePreparedRequest(_:forSingleResult:)``
/// - ``PreparedRequest``
///
/// ### Adapting the Fetched Rows
///
/// - ``adapted(_:)``
/// - ``AdaptedFetchRequest``
///
/// ### Supporting Types
///
/// - ``AnyFetchRequest``
public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
/// Returns a ``PreparedRequest``.
///
/// The `singleResult` argument is a hint that a single result row will be
/// consumed. Implementations can optionally use it to optimize the
/// prepared statement, for example by adding a `LIMIT 1` SQL clause:
///
/// ```swift
/// // Calls makePreparedRequest(db, forSingleResult: true)
/// try request.fetchOne(db)
///
/// // Calls makePreparedRequest(db, forSingleResult: false)
/// try request.fetchAll(db)
/// ```
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed.
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
func fetchCount(_ db: Database) throws -> Int
}
extension FetchRequest {
/// Returns the database region that the request feeds from.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
}
}
@@ -0,0 +1,51 @@
/// A closure executed before a supplementary fetch is performed.
///
/// Support for `Database.dumpRequest`.
///
/// - parameter request: The supplementary request
/// - parameter keyPath: The key path target of the supplementary fetch.
typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _ keyPath: [String]) throws -> Void
/// A closure that performs supplementary fetches.
///
/// Support for eager loading of hasMany associations.
///
/// - parameter db: A database connection.
/// - parameter rows: The rows that are modified by the supplementary fetch.
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
/// performing supplementary fetches.
typealias SupplementaryFetch = (
_ db: Database,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequest {
/// A prepared statement with bound parameters.
public var statement: Statement
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: SupplementaryFetch?
init(
statement: Statement,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch? = nil)
{
self.statement = statement
self.adapter = adapter
self.supplementaryFetch = supplementaryFetch
}
}
// Explicit non-conformance to Sendable: `PreparedRequest` contains
// a statement.
@available(*, unavailable)
extension PreparedRequest: Sendable { }
extension PreparedRequest: Refinable { }
File renamed without changes.
@@ -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
// TODO: simplify when <https://github.com/apple/swift/issues/71541> is resolved.
_region = { try region.databaseRegion($0) }
}
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
@@ -461,7 +462,7 @@ extension DatabaseRegion {
}
}
static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion {
static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion {
return { db in
try regions.reduce(into: DatabaseRegion()) { union, region in
try union.formUnion(region.databaseRegion(db))
@@ -3,10 +3,10 @@ import Combine
#endif
import Foundation
public struct DatabaseRegionObservation {
public struct DatabaseRegionObservation: Sendable {
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: (Database) throws -> DatabaseRegion
var observedRegion: @Sendable (Database) throws -> DatabaseRegion
}
extension DatabaseRegionObservation {
@@ -46,7 +46,7 @@ extension DatabaseRegionObservation {
private enum ObservationState {
case cancelled
case pending
case started(DatabaseRegionObserver)
case started(StrongReference<DatabaseRegionObserver>)
}
/// Starts observing the database.
@@ -89,16 +89,16 @@ extension DatabaseRegionObservation {
onChange: @escaping (Database) -> Void)
-> AnyDatabaseCancellable
{
@LockedBox var state = ObservationState.pending
let stateMutex = 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 {
stateMutex.withLock { state in
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = state {
if case .cancelled = stateMutex.load() {
return
}
onChange($0)
@@ -111,7 +111,7 @@ extension DatabaseRegionObservation {
// the observer.
db.add(transactionObserver: observer, extent: .observerLifetime)
$0 = .started(observer)
state = .started(StrongReference(observer))
}
} catch {
onError(error)
@@ -122,13 +122,13 @@ 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
stateMutex.store(.cancelled)
}
}
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabaseRegionObservation {
// MARK: - Publishing Impactful Transactions
@@ -140,7 +140,7 @@ extension DatabaseRegionObservation {
///
/// Do not reschedule the publisher with `receive(on:options:)` or any
/// `Publisher` method that schedules publisher elements.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
DatabasePublishers.DatabaseRegion(self, in: writer)
}
@@ -186,7 +186,7 @@ private class DatabaseRegionObserver: TransactionObserver {
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that tracks transactions that modify a database region.
///
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
-2573
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,49 @@
extension Row: RandomAccessCollection {
public var startIndex: Index { Index(0) }
public var endIndex: Index { Index(count) }
/// Returns the (column, value) pair at given index.
public subscript(position: Index) -> (String, DatabaseValue) {
let index = position.index
_checkIndex(index)
return (
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
}
}
// MARK: - Index
@available(*, deprecated, renamed: "Row.Index")
typealias RowIndex = Row.Index
extension Row {
/// An index to a (column, value) pair in a ``Row``.
public struct Index: Sendable {
let index: Int
init(_ index: Int) { self.index = index }
}
}
extension Row.Index: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.index == rhs.index
}
}
extension Row.Index: Comparable {
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.index < rhs.index
}
}
extension Row.Index: Strideable {
public func distance(to other: Self) -> Int {
other.index - index
}
public func advanced(by n: Int) -> Self {
Row.Index(index + n)
}
}
+543
View File
@@ -0,0 +1,543 @@
import Foundation
extension Row {
/// The names of columns in the row, from left to right.
///
/// Columns appear in the same order as they occur as the `.0` member
/// of column-value pairs in `self`.
public var columnNames: LazyMapCollection<Row, String> {
lazy.map { $0.0 }
}
/// The database values in the row, from left to right.
///
/// Values appear in the same order as they occur as the `.1` member
/// of column-value pairs in `self`.
public var databaseValues: LazyMapCollection<Row, DatabaseValue> {
lazy.map { $0.1 }
}
/// Returns whether the row has one column with the given name
/// (case-insensitive).
public func hasColumn(_ columnName: String) -> Bool {
index(forColumn: columnName) != nil
}
@usableFromInline
func index(forColumn name: String) -> Int? {
impl.index(forColumn: name)
}
}
extension Row {
/// Fatal errors if index is out of bounds
@inline(__always)
@usableFromInline
/* private */ func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
}
/// Returns a boolean value indicating if the row contains one value this
/// is not `NULL`.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'foo', NULL")!
/// row.containsNonNullValue // true
///
/// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")!
/// row.containsNonNullValue // false
/// ```
public var containsNonNullValue: Bool {
for i in (0..<count) where !impl.hasNull(atUncheckedIndex: i) {
return true
}
for (_, scopedRow) in scopes where scopedRow.containsNonNullValue {
return true
}
return false
}
/// Returns whether the row has a `NULL` value at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// This method is equivalent to `row[index] == nil`, but may be preferred
/// in performance-critical code because it avoids decoding
/// database values.
public func hasNull(atIndex index: Int) -> Bool {
_checkIndex(index)
return impl.hasNull(atUncheckedIndex: index)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
/// value stored at the given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
public subscript(_ index: Int) -> (any DatabaseValueConvertible)? {
_checkIndex(index)
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
/// Returns the value at given index, converted to the requested type.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score: Int = row[0] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name: String = row[0] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = row[0] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
try! decode(Value.self, atIndex: index)
}
/// Returns the value at given index, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score: Int = row[0] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name: String = row[0] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = row[0] // nil
/// ```
@inline(__always)
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
try! decode(Value.self, atIndex: index)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
/// value stored at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain any column with that name.
public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? {
// IMPLEMENTATION NOTE
// This method has a single known use case: checking if the value is nil,
// as in:
//
// if row["foo"] != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = index(forColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row["score"] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row["name"] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row["name"] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row["missing"] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row["score"] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row["name"] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row["name"] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row["missing"] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
/// value stored at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain any column with that name.
public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? {
self[column.name]
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row[Column("score")] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row[Column("name")] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row[Column("name")] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row[Column("missing")] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
try! decode(Value.self, forKey: column.name)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row[Column("score")] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row[Column("name")] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row[Column("name")] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row[Column("missing")] // nil
/// ```
@inlinable
public subscript<Value>(_ column: some ColumnExpression)
-> Value
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
try! decode(Value.self, forKey: column.name)
}
/// Calls the given closure with the `Data` at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is `NULL`, the data is nil. If the SQLite value can
/// not be converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
public func withUnsafeData<T>(atIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
_checkIndex(index)
return try impl.withUnsafeData(atUncheckedIndex: index, body)
}
/// Calls the given closure with the `Data` at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain any column with that name, or if the SQLite
/// value is `NULL`, the data is nil. If the SQLite value can not be
/// converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
public func withUnsafeData<T>(named columnName: String, _ body: (Data?) throws -> T) throws -> T {
guard let index = index(forColumn: columnName) else {
return try body(nil)
}
return try impl.withUnsafeData(atUncheckedIndex: index, body)
}
/// Calls the given closure with the `Data` at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain any column with that name, or if the SQLite
/// value is `NULL`, the data is nil. If the SQLite value can not be
/// converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
public func withUnsafeData<T>(at column: some ColumnExpression, _ body: (Data?) throws -> T) throws -> T {
try withUnsafeData(named: column.name, body)
}
/// Returns the optional `Data` at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, the result is nil. If the SQLite value can
/// not be converted to Data, a fatal error is raised.
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
@available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.")
public func dataNoCopy(atIndex index: Int) -> Data? {
try! withUnsafeData(atIndex: index, { $0 })
}
/// Returns the optional `Data` at given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. If the SQLite value can not be converted to Data, a fatal error
/// is raised.
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
@available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.")
public func dataNoCopy(named columnName: String) -> Data? {
guard let index = index(forColumn: columnName) else {
return nil
}
return try! withUnsafeData(atUncheckedIndex: index, { $0 })
}
/// Returns the optional `Data` at given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. If the SQLite value can not be converted to Data, a fatal error
/// is raised.
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
@available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.")
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
dataNoCopy(named: column.name)
}
}
// MARK: - Support for DatabaseValueConvertible
extension Row {
/// Returns the value at given index, converted to the requested type.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
@inlinable
func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
{
_checkIndex(index)
return try Value.decode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
@inlinable
func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
if let value = Value.fromMissingColumn() {
return value
} else {
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
}
}
return try Value.decode(fromRow: self, atUncheckedIndex: index)
}
}
// MARK: - Support for DatabaseValueConvertible & StatementColumnConvertible
extension Row {
/// Returns the value at given index, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
@inline(__always)
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
{
_checkIndex(index)
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
if let value = Value.fromMissingColumn() {
return value
} else {
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
}
}
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
}
// Support for fast decoding in scoped rows
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
throws -> Value
{
try impl.fastDecode(type, atUncheckedIndex: index)
}
}
// MARK: - Support for Data
extension Row {
/// Calls the given closure with the `Data` at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is `NULL`, the data is nil. If the SQLite value can
/// not be converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
try impl.withUnsafeData(atUncheckedIndex: index, body)
}
}
+538
View File
@@ -0,0 +1,538 @@
// MARK: - Fetching From Prepared Statement
extension Row {
/// Returns a cursor over rows fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let rows = try Row.fetchCursor(statement, arguments: [lastName])
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` since you would not get the
/// distinct rows you expect.
/// Use ``fetchAll(_:arguments:adapter:)`` instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> RowCursor
{
try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of rows fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let rows = try Row.fetchAll(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Row]
{
// The cursor reuses a single mutable row. Return immutable copies.
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
}
/// Returns a set of rows fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let rows = try Row.fetchSet(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Row>
{
// The cursor reuses a single mutable row. Return immutable copies.
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
}
/// Returns a single row fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1"
/// let statement = try db.makeStatement(sql: sql)
/// let row = try Row.fetchOne(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Row?
{
let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter)
// Keep cursor alive until we can copy the fetched row
return try withExtendedLifetime(cursor) {
try cursor.next().map { $0.copy() }
}
}
}
// MARK: - Fetching From SQL
extension Row {
/// Returns a cursor over rows fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let rows = try Row.fetchCursor(db, sql: sql, arguments: [lastName])
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` since you would not get the
/// distinct rows you expect.
/// Use ``fetchAll(_:sql:arguments:adapter:)`` instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> RowCursor
{
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of rows fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let rows = try Row.fetchAll(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> [Row]
{
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a set of rows fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let rows = try Row.fetchSet(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> Set<Row>
{
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single row fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1"
/// let row = try Row.fetchOne(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> Row?
{
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
}
// MARK: - Fetching From FetchRequest
extension Row {
/// Returns a cursor over rows fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let rows = try Row.fetchCursor(db, request)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` since you would not get the
/// distinct rows you expect.
/// Use ``fetchAll(_:_:)`` instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor {
let request = try request.makePreparedRequest(db, forSingleResult: false)
precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch")
return try fetchCursor(request.statement, adapter: request.adapter)
}
/// Returns an array of rows fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let rows = try Row.fetchAll(db, request)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows, nil)
return rows
}
/// Returns a set of rows fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let rows = try Row.fetchSet(db, request)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows, nil)
return Set(rows)
} else {
return try fetchSet(request.statement, adapter: request.adapter)
}
}
/// Returns a single row fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
/// """
///
/// let row = try Row.fetchOne(db, request)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
}
try request.supplementaryFetch?(db, [row], nil)
return row
}
}
// MARK: FetchRequest+Row
extension FetchRequest<Row> {
/// Returns a cursor over fetched rows.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
/// let rows = try request.fetchCursor(db)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` since you would not get the
/// distinct rows you expect.
/// Use ``FetchRequest/fetchAll(_:)-7p809`` instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameter db: A database connection.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RowCursor {
try Row.fetchCursor(db, self)
}
/// Returns an array of fetched rows.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
/// let rows = try request.fetchAll(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
try Row.fetchAll(db, self)
}
/// Returns a set of fetched rows.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
/// let rows = try request.fetchSet(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - returns: A set of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
try Row.fetchSet(db, self)
}
/// Returns a single row.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let request: SQLRequest<Row> = """
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
/// """
/// let rows = try request.fetchOne(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
try Row.fetchOne(db, self)
}
}
+266
View File
@@ -0,0 +1,266 @@
extension Row {
/// A collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord, FetchableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: [Book] = author["books"]
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter key: An association key.
public subscript<Records>(_ key: String)
-> Records
where
Records: RangeReplaceableCollection,
Records.Element: FetchableRecord
{
try! decode(Records.self, forKey: key)
}
/// A set prefetched records associated to the given association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: Set<Book> = author["books"]
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter key: An association key.
public subscript<Record: FetchableRecord & Hashable>(_ key: String) -> Set<Record> {
try! decode(Set<Record>.self, forKey: key)
}
}
// MARK: - Support
extension Row {
/// Returns the records encoded in the given prefetched rows.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: [Book] = row["books"]
/// print(books[0].title)
/// // Prints "Moby-Dick"
func decode<Collection>(
_ type: Collection.Type = Collection.self,
forKey key: String)
throws -> Collection
where
Collection: RangeReplaceableCollection,
Collection.Element: FetchableRecord
{
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
throw RowDecodingError.keyNotFound(
.prefetchKey(key),
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self),
debugDescription: """
key for prefetched rows not found: \(String(reflecting: key))
"""))
} else {
throw RowDecodingError.keyNotFound(
.prefetchKey(key),
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self),
debugDescription: """
key for prefetched rows not found: \(String(reflecting: key)) \
- available keys: \(availableKeys.sorted())
"""))
}
}
var collection = Collection()
collection.reserveCapacity(rows.count)
for row in rows {
try collection.append(Collection.Element(row: row))
}
return collection
}
/// Returns the set of records encoded in the given prefetched rows.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: Set<Book> = row["books"]
/// print(books.first!.title)
/// // Prints "Moby-Dick"
func decode<Record: FetchableRecord & Hashable>(
_ type: Set<Record>.Type = Set<Record>.self,
forKey key: String)
throws -> Set<Record>
{
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
throw RowDecodingError.keyNotFound(
.prefetchKey(key),
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self),
debugDescription: """
key for prefetched rows not found: \(String(reflecting: key))
"""))
} else {
throw RowDecodingError.keyNotFound(
.prefetchKey(key),
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self),
debugDescription: """
key for prefetched rows not found: \(String(reflecting: key)) \
- available keys: \(availableKeys.sorted())
"""))
}
}
var set = Set<Record>(minimumCapacity: rows.count)
for row in rows {
try set.insert(Record(row: row))
}
return set
}
}
// MARK: - Row.PrefetchedRowsView
extension Row {
struct Prefetch: Equatable {
// Nil for intermediate associations
var rows: [Row]?
// OrderedDictionary so that breadth-first search gives a consistent result
// (we preserve the ordering of associations in the request)
var prefetches: OrderedDictionary<String, Prefetch>
}
/// A view on the prefetched associated rows.
///
/// See ``Row/prefetchedRows`` for more information.
public struct PrefetchedRowsView: Equatable {
// OrderedDictionary so that breadth-first search gives a consistent result
// (we preserve the ordering of associations in the request)
var prefetches: OrderedDictionary<String, Prefetch> = [:]
/// A boolean value indicating if there is no prefetched
/// associated rows.
public var isEmpty: Bool {
prefetches.isEmpty
}
/// The available association keys.
///
/// Keys in the returned set can be used with ``subscript(_:)``.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// print(authorRow.prefetchedRows.keys)
/// // Prints ["books"]
///
/// let bookRows = authorRow.prefetchedRows["books"]!
/// print(bookRows[0])
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
/// print(bookRows[1])
/// // Prints [id:57, title:"Pierre", authorId:1]
/// ```
public var keys: Set<String> {
var result: Set<String> = []
var fifo = Array(prefetches)
while !fifo.isEmpty {
let (prefetchKey, prefetch) = fifo.removeFirst()
if prefetch.rows != nil {
result.insert(prefetchKey)
}
fifo.append(contentsOf: prefetch.prefetches)
}
return result
}
/// The prefetched rows associated with the given association key.
///
/// The result is nil if the key is not available.
///
/// See ``Row/prefetchedRows`` for more information.
///
/// - parameter key: An association key.
public subscript(_ key: String) -> [Row]? {
var fifo = Array(prefetches)
while !fifo.isEmpty {
let (prefetchKey, prefetch) = fifo.removeFirst()
if prefetchKey == key,
let rows = prefetch.rows // nil for "through" associations
{
return rows
}
fifo.append(contentsOf: prefetch.prefetches)
}
return nil
}
mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) {
prefetches.setRows(rows, forKeyPath: keyPath)
}
}
}
extension OrderedDictionary<String, Row.Prefetch> {
fileprivate mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) {
var keyPath = keyPath
let key = keyPath.removeFirst()
if keyPath.isEmpty {
self[key, default: Row.Prefetch(rows: nil, prefetches: [:])].rows = rows
} else {
self[key, default: Row.Prefetch(rows: nil, prefetches: [:])].prefetches.setRows(rows, forKeyPath: keyPath)
}
}
}
+474
View File
@@ -0,0 +1,474 @@
extension Row {
/// A view on the scopes defined by row adapters.
///
/// The returned object provides an access to all available scopes in
/// the row.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// print(bookRow)
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
///
/// let authorRow = bookRow.scopes["author"]!
/// print(authorRow)
/// // Prints [id:1, name:"Herman Melville", countryCode: "US"]
///
/// let countryRow = authorRow.scopes["country"]!
/// print(countryRow)
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopesTree``.
public var scopes: ScopesView {
impl.scopes(prefetchedRows: prefetchedRows)
}
/// A view on the scopes tree defined by row adapters.
///
/// The returned object provides an access to all available scopes in
/// the row, recursively. For any given scope identifier, a breadth-first
/// search is performed.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// print(bookRow)
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
///
/// print(bookRow.scopesTree["author"])
/// // Prints [id:1, name:"Herman Melville", countryCode: "US"]
///
/// print(bookRow.scopesTree["country"])
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopes``.
public var scopesTree: ScopesTreeView {
ScopesTreeView(scopes: scopes)
}
/// The row, without any scope of prefetched rows.
///
/// This property is useful when testing the content of rows fetched from
/// joined requests.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// static let awards = hasMany(Award.self)
/// }
///
/// struct Author: TableRecord { }
/// struct Award: TableRecord { }
///
/// // Fetch a book, with its author, and its awards.
/// let request = Book
/// .including(required: Book.author)
/// .including(all: Book.awards)
/// let bookRow = try Row.fetchOne(db, request)!
///
/// // Failure
/// XCTAssertEqual(bookRow, ["id":42, "title":"Moby-Dick", "authorId":1])
///
/// // Success
/// XCTAssertEqual(bookRow.unscoped, ["id":42, "title":"Moby-Dick", "authorId":1])
/// ```
public var unscoped: Row {
var row = impl.unscopedRow(self)
// Remove prefetchedRows
if row.prefetchedRows.isEmpty == false {
// Make sure we build another Row instance
row = Row(impl: row.copy().impl)
assert(row !== self)
assert(row.prefetchedRows.isEmpty)
}
return row
}
/// The raw row fetched from the database.
///
/// This property is useful when debugging the content of rows fetched from
/// joined requests.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord { }
///
/// // SELECT book.*, author.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// let request = Book.including(required: Book.author)
/// let bookRow = try Row.fetchOne(db, request)!
///
/// print(bookRow)
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
///
/// print(bookRow.unadapted)
/// // Prints [id:42, title:"Moby-Dick", authorId:1, id:1, name:"Herman Melville"]
/// ```
public var unadapted: Row {
impl.unadaptedRow(self)
}
}
// MARK: - Records
extension Row {
/// The record associated to the given scope.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// A fatal error is raised if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author = bookRow["author"]
/// let country: Country = bookRow["country"]
/// ```
///
/// See also: ``scopesTree``
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
try! decode(Record.self, forKey: scope)
}
/// The eventual record associated to the given scope.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// The result is nil if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author? = bookRow["author"]
/// let country: Country? = bookRow["country"]
/// ```
///
/// See also: ``scopesTree``
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
try! decodeIfPresent(Record.self, forKey: scope)
}
}
extension Row {
/// Returns the eventual record associated with the given scope.
///
/// For example:
///
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author? = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
///
/// Associated records stored in nested associations are available, too:
///
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country? = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// Nil is returned if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decodeIfPresent<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record?
{
guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
return nil
}
return try Record(row: scopedRow)
}
/// Returns the record associated with the given scope.
///
/// For example:
///
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
///
/// Associated records stored in nested associations are available, too:
///
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// A fatal error is raised if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decode<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record
{
guard let scopedRow = scopesTree[scope] else {
let availableScopes = scopesTree.names
if availableScopes.isEmpty {
throw RowDecodingError.keyNotFound(
.scope(scope),
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self),
debugDescription: """
scope not found: \(String(reflecting: scope))
"""))
} else {
throw RowDecodingError.keyNotFound(
.scope(scope),
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self),
debugDescription: """
scope not found: \(String(reflecting: scope)) - \
available scopes: \(availableScopes.sorted())
"""))
}
}
guard scopedRow.containsNonNullValue else {
throw RowDecodingError.valueMismatch(
Record.self,
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: self, key: .scope(scope)),
debugDescription: """
scope \(String(reflecting: scope)) only contains null values
"""))
}
return try Record(row: scopedRow)
}
}
// MARK: - Row.ScopesView
extension Row {
/// A view on the scopes defined by row adapters.
///
/// `ScopesView` is a `Collection` of `(name: String, row: Row)` pairs.
///
/// See ``Row/scopes`` for more information.
public struct ScopesView {
private let row: Row
private let scopes: [String: any _LayoutedRowAdapter]
private let prefetchedRows: Row.PrefetchedRowsView
/// The available scopes in this row.
public var names: Dictionary<String, any _LayoutedRowAdapter>.Keys {
scopes.keys
}
init() {
self.init(row: Row(), scopes: [:], prefetchedRows: Row.PrefetchedRowsView())
}
init(row: Row, scopes: [String: any _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) {
self.row = row
self.scopes = scopes
self.prefetchedRows = prefetchedRows
}
/// The row associated with the given scope, or nil if the scope is
/// not available.
public subscript(_ name: String) -> Row? {
scopes.index(forKey: name).map { self[$0].row }
}
}
}
extension Row.ScopesView: Collection {
public typealias Index = Dictionary<String, any _LayoutedRowAdapter>.Index
public var startIndex: Index {
scopes.startIndex
}
public var endIndex: Index {
scopes.endIndex
}
public func index(after i: Index) -> Index {
scopes.index(after: i)
}
public subscript(position: Index) -> (name: String, row: Row) {
let (name, adapter) = scopes[position]
let adaptedRow = Row(base: row, adapter: adapter)
if let prefetch = prefetchedRows.prefetches[name] {
// Let the adapted row access its own prefetched rows.
// Use case:
//
// let request = A.including(required: A.b.including(all: B.c))
// let row = try Row.fetchOne(db, request)!
// row.prefetchedRows["cs"] // Some array
// row.scopes["b"]!.prefetchedRows["cs"] // The same array
adaptedRow.prefetchedRows = Row.PrefetchedRowsView(prefetches: prefetch.prefetches)
}
return (name: name, row: adaptedRow)
}
}
// MARK: - Row.ScopesTreeView
extension Row {
/// A view on the scopes tree defined by row adapters.
///
/// See ``Row/scopesTree`` for more information.
public struct ScopesTreeView {
let scopes: ScopesView
/// The scopes available on this row, recursively.
public var names: Set<String> {
var names = Set<String>()
for (name, row) in scopes {
names.insert(name)
names.formUnion(row.scopesTree.names)
}
return names
}
/// The row associated with the given scope, or nil if the scope is
/// not available.
///
/// See ``Row/scopesTree`` for more information.
///
/// - parameter name: The name of a scope.
public subscript(_ name: String) -> Row? {
var fifo = Array(scopes)
while !fifo.isEmpty {
let scope = fifo.removeFirst()
if scope.name == name {
return scope.row
}
fifo.append(contentsOf: scope.row.scopes)
}
return nil
}
}
}
+377
View File
@@ -0,0 +1,377 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A database row.
///
/// To get `Row` instances, you will generally fetch them from a ``Database``
/// instance. For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let rows = try Row.fetchCursor(db, sql: """
/// SELECT * FROM player
/// """)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// ## Topics
///
/// ### Creating Rows
///
/// - ``init()``
/// - ``init(_:)-5uezw``
/// - ``init(_:)-65by6``
///
/// ### Copying a Row
///
/// - ``copy()``
///
/// ### Row Informations
///
/// - ``columnNames``
/// - ``containsNonNullValue``
/// - ``count-5flaw``
/// - ``databaseValues``
/// - ``hasColumn(_:)``
/// - ``hasNull(atIndex:)``
///
/// ### Accessing Row Values by Int Index
///
/// - ``subscript(_:)-9c1fw``
/// - ``subscript(_:)-3jhwm``
/// - ``subscript(_:)-7krrg``
/// - ``withUnsafeData(atIndex:_:)``
/// - ``dataNoCopy(atIndex:)``
///
/// ### Accessing Row Values by Column Name
///
/// - ``subscript(_:)-3tp8o``
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
/// ### Accessing Row Values by Column
///
/// - ``subscript(_:)-9txgm``
/// - ``subscript(_:)-2esg7``
/// - ``subscript(_:)-wl9a``
/// - ``withUnsafeData(at:_:)``
/// - ``dataNoCopy(_:)``
///
/// ### Row Scopes & Associated Rows
///
/// - ``prefetchedRows``
/// - ``scopes``
/// - ``scopesTree``
/// - ``unadapted``
/// - ``unscoped``
/// - ``subscript(_:)-4dx01``
/// - ``subscript(_:)-8god3``
/// - ``subscript(_:)-jwnx``
/// - ``subscript(_:)-6ge6t``
/// - ``PrefetchedRowsView``
/// - ``ScopesTreeView``
/// - ``ScopesView``
///
/// ### Fetching Rows from Raw SQL
///
/// - ``fetchCursor(_:sql:arguments:adapter:)``
/// - ``fetchAll(_:sql:arguments:adapter:)``
/// - ``fetchSet(_:sql:arguments:adapter:)``
/// - ``fetchOne(_:sql:arguments:adapter:)``
///
/// ### Fetching Rows from a Prepared Statement
///
/// - ``fetchCursor(_:arguments:adapter:)``
/// - ``fetchAll(_:arguments:adapter:)``
/// - ``fetchSet(_:arguments:adapter:)``
/// - ``fetchOne(_:arguments:adapter:)``
///
/// ### Fetching Rows from a Request
///
/// - ``fetchCursor(_:_:)``
/// - ``fetchAll(_:_:)``
/// - ``fetchSet(_:_:)``
/// - ``fetchOne(_:_:)``
///
/// ### Row as RandomAccessCollection
///
/// - ``count-5flaw``
/// - ``subscript(_:)-68yae``
/// - ``Index``
///
/// ### Adapting Rows
///
/// - ``RowAdapter``
///
/// ### Supporting Types
///
/// - ``RowCursor``
public final class Row {
// It is not a violation of the Demeter law when another type uses this
// property, which is exposed for optimizations.
let impl: any RowImpl
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// let players = try Player.fetchAll(db, sql: "SELECT ...")
let statement: Statement?
@usableFromInline
let sqliteStatement: SQLiteStatement?
/// The number of columns in the row.
public let count: Int
/// A view on the prefetched associated rows.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// print(authorRow)
/// // Prints [id:1, name:"Herman Melville"]
///
/// let bookRows = authorRow.prefetchedRows["books"]!
/// print(bookRows[0])
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
/// print(bookRows[1])
/// // Prints [id:57, title:"Pierre", authorId:1]
/// ```
public internal(set) var prefetchedRows = PrefetchedRowsView()
// MARK: - Building rows
/// Creates an empty row.
public convenience init() {
self.init(impl: EmptyRowImpl())
}
/// Creates a row from a dictionary of database values.
public convenience init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) }))
}
/// Creates a row from a dictionary.
///
/// The result is nil unless all dictionary keys are strings, and values
/// conform to ``DatabaseValueConvertible``.
public convenience init?(_ dictionary: [AnyHashable: Any]) {
var initDictionary = [String: (any DatabaseValueConvertible)?]()
for (key, value) in dictionary {
guard let columnName = key as? String else {
return nil
}
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
initDictionary[columnName] = dbValue
}
self.init(initDictionary)
}
/// Returns an immutable copy of the row.
///
/// For performance reasons, rows fetched from a cursor are reused during
/// the iteration of a query: make sure to make a copy of it whenever you
/// want to keep a specific one: `row.copy()`.
public func copy() -> Row {
impl.copiedRow(self)
}
// MARK: - Not Public
/// Returns true if and only if the row was fetched from a database.
var isFetched: Bool { impl.isFetched }
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
///
/// The row is implemented on top of StatementRowImpl, which grants *direct*
/// access to the SQLite statement. Iteration of the statement does modify
/// the row.
init(statement: Statement) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
init(sqliteStatement: SQLiteStatement) {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that contain a copy of the current state of the
/// SQLite statement. Further calls to sqlite3_step() do not modify the row.
///
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
statement: Statement)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
columnNames: statement.columnNames))
}
init(impl: any RowImpl) {
self.statement = nil
self.sqliteStatement = nil
self.impl = impl
self.count = impl.count
}
}
// Explicit non-conformance to Sendable: a row contains transient
// information. TODO GRDB7: split non sendable statement rows from sendable
// copied rows.
@available(*, unavailable)
extension Row: Sendable { }
extension Row: Equatable {
/// Returns true if and only if both rows have the same columns and values,
/// in the same order. Columns are compared in a case-sensitive way.
public static func == (lhs: Row, rhs: Row) -> Bool {
if lhs === rhs {
return true
}
guard lhs.count == rhs.count else {
return false
}
for ((lcol, lval), (rcol, rval)) in zip(lhs, rhs) {
guard lcol == rcol else {
return false
}
guard lval == rval else {
return false
}
}
let lscopeNames = lhs.scopes.names
let rscopeNames = rhs.scopes.names
guard lscopeNames == rscopeNames else {
return false
}
for name in lscopeNames {
let lscope = lhs.scopes[name]
let rscope = rhs.scopes[name]
guard lscope == rscope else {
return false
}
}
guard lhs.prefetchedRows == rhs.prefetchedRows else {
return false
}
return true
}
}
extension Row: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(count)
for (column, dbValue) in self {
hasher.combine(column)
hasher.combine(dbValue)
}
}
}
extension Row: CustomStringConvertible {
public var description: String {
"["
+ map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ")
+ "]"
}
}
extension Row: CustomDebugStringConvertible {
public var debugDescription: String {
debugDescription(level: 0)
}
private func debugDescription(level: Int) -> String {
if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty {
return description
}
let prefix = repeatElement(" ", count: level + 1).joined()
var str = ""
if level == 0 {
str = "▿ " + description
let unadapted = self.unadapted
if self != unadapted {
str += "\n" + prefix + "unadapted: " + unadapted.description
}
} else {
str = description
}
for (name, scopedRow) in scopes.sorted(by: { $0.name < $1.name }) {
str += "\n" + prefix + "- " + name + ": " + scopedRow.debugDescription(level: level + 1)
}
for key in prefetchedRows.keys.sorted() {
// rows is nil if key is a pivot in a "through" association
if let rows = prefetchedRows[key] {
let prefetchedRowsDescription: String
switch rows.count {
case 0:
prefetchedRowsDescription = "0 row"
case 1:
prefetchedRowsDescription = "1 row"
case let count:
prefetchedRowsDescription = "\(count) rows"
}
str += "\n" + prefix + "+ " + key + ": \(prefetchedRowsDescription)"
}
}
return str
}
}
extension Row: ExpressibleByDictionaryLiteral {
/// Creates a row initialized with elements. Column order is preserved, and
/// duplicated columns names are allowed.
///
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
/// print(row)
/// // Prints [foo:1 foo:"bar" baz:NULL]
public convenience init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) }))
}
}
@@ -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
}
+45
View File
@@ -0,0 +1,45 @@
/// A cursor of raw database rows.
///
/// A `RowCursor` iterates all rows from a database request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let rows = try Row.fetchCursor(db, sql: """
/// SELECT * FROM player
/// """)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
public final class RowCursor: DatabaseCursor {
public typealias Element = Row
public let _statement: Statement
public var _isDone = false
@usableFromInline let _row: Row // Reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
self._statement = statement
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
}
@inlinable
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension RowCursor: Sendable { }
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A key that is used to decode a value in a row
@usableFromInline
enum RowKey: Hashable, Sendable {
+272
View File
@@ -0,0 +1,272 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
// The protocol for Row underlying implementation
protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView
func columnName(atUncheckedIndex index: Int) -> String
func hasNull(atUncheckedIndex index: Int) -> Bool
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
throws -> Value
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
func index(forColumn name: String) -> Int?
// row.impl is guaranteed to be self.
func unscopedRow(_ row: Row) -> Row
func unadaptedRow(_ row: Row) -> Row
func copiedRow(_ row: Row) -> Row
}
extension RowImpl {
func copiedRow(_ row: Row) -> Row {
// unless customized, assume unsafe and unadapted row
Row(impl: ArrayRowImpl(columns: Array(row)))
}
func unscopedRow(_ row: Row) -> Row {
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
row
}
func unadaptedRow(_ row: Row) -> Row {
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
row
}
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
// unless customized, assume unuscoped row (see AdaptedRowImpl for customization)
Row.ScopesView()
}
func hasNull(atUncheckedIndex index: Int) -> Bool {
// unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization)
databaseValue(atUncheckedIndex: index).isNull
}
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
throws -> Value
{
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
try Value.decode(
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
}
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
let data = try Optional<Data>.decode(
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
return try body(data)
}
}
// TODO: merge with StatementCopyRowImpl eventually?
/// See Row.init(dictionary:)
struct ArrayRowImpl: RowImpl {
let columns: [(String, DatabaseValue)]
init<Columns>(columns: Columns)
where Columns: Collection, Columns.Element == (String, DatabaseValue)
{
self.columns = Array(columns)
}
var count: Int { columns.count }
var isFetched: Bool { false }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
columns[index].1
}
func columnName(atUncheckedIndex index: Int) -> String {
columns[index].0
}
func index(forColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columns.firstIndex { (column, _) in column.lowercased() == lowercaseName }
}
func copiedRow(_ row: Row) -> Row {
row
}
}
extension ArrayRowImpl: Sendable { }
// TODO: merge with ArrayRowImpl eventually?
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
struct StatementCopyRowImpl: RowImpl {
let dbValues: ContiguousArray<DatabaseValue>
let columnNames: [String]
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
let sqliteStatement = sqliteStatement
self.dbValues = ContiguousArray(
(0..<sqlite3_column_count(sqliteStatement))
.map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) }
as [DatabaseValue])
self.columnNames = columnNames
}
var count: Int { columnNames.count }
var isFetched: Bool { true }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
dbValues[index]
}
func columnName(atUncheckedIndex index: Int) -> String {
columnNames[index]
}
func index(forColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columnNames.firstIndex { $0.lowercased() == lowercaseName }
}
func copiedRow(_ row: Row) -> Row {
row
}
}
/// See Row.init(statement:)
struct StatementRowImpl: RowImpl {
let statement: Statement
let sqliteStatement: SQLiteStatement
let lowercaseColumnIndexes: [String: Int]
init(sqliteStatement: SQLiteStatement, statement: Statement) {
self.statement = statement
self.sqliteStatement = sqliteStatement
// Optimize row[columnName]
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
.map { ($0.element, $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
var count: Int {
Int(sqlite3_column_count(sqliteStatement))
}
var isFetched: Bool { true }
func hasNull(atUncheckedIndex index: Int) -> Bool {
// Avoid extracting values, because this modifies the SQLite statement.
sqlite3_column_type(sqliteStatement, CInt(index)) == SQLITE_NULL
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index))
}
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
throws -> Value
{
try Value.fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(statement: statement, index: index))
}
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else {
return try body(nil)
}
guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else {
return try body(Data())
}
let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index)))
let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
return try body(data)
}
func columnName(atUncheckedIndex index: Int) -> String {
statement.columnNames[index]
}
func index(forColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
return lowercaseColumnIndexes[name.lowercased()]
}
func copiedRow(_ row: Row) -> Row {
Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
}
}
// This one is not optimized at all, since it is only used in fatal conversion errors, so far
struct SQLiteStatementRowImpl: RowImpl {
let sqliteStatement: SQLiteStatement
var count: Int { Int(sqlite3_column_count(sqliteStatement)) }
var isFetched: Bool { true }
func columnName(atUncheckedIndex index: Int) -> String {
String(cString: sqlite3_column_name(sqliteStatement, CInt(index)))
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index))
}
func index(forColumn name: String) -> Int? {
let name = name.lowercased()
for index in 0..<count where columnName(atUncheckedIndex: index).lowercased() == name {
return index
}
return nil
}
}
/// See Row.init()
struct EmptyRowImpl: RowImpl {
var count: Int { 0 }
var isFetched: Bool { false }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
// Programmer error
fatalError("row index out of range")
}
func columnName(atUncheckedIndex index: Int) -> String {
// Programmer error
fatalError("row index out of range")
}
func index(forColumn name: String) -> Int? { nil }
func copiedRow(_ row: Row) -> Row { row }
}
@@ -39,7 +39,7 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
public struct SQL {
public struct SQL: Sendable {
/// `SQL.Element` is a component of an `SQL` literal.
///
/// Elements can be qualified with table aliases, and this is how `SQL`
File renamed without changes.
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Data is convertible to and from DatabaseValue.
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A database value that holds date components.
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#if !os(Linux)
@@ -1,4 +1,13 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Decimal adopts DatabaseValueConvertible
+10 -1
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#if !os(Linux)
@@ -8,7 +17,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
}
}
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
switch self {
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
-94
View File
@@ -1,94 +0,0 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// 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
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
/// Creates a long-live WAL transaction on a read-only connection.
///
/// The `release` closure is always called. It is called when the
/// `WALSnapshotTransaction` is deallocated, or if the initializer
/// throws.
///
/// In normal operations, the argument to `release` is always false,
/// meaning that the connection is no longer in a transaction. If true,
/// the connection has been left inside a transaction, due to
/// some error.
///
/// Usage:
///
/// ```swift
/// let transaction = WALSnapshotTransaction(
/// reader: reader,
/// release: { isInsideTransaction in
/// ...
/// })
/// ```
///
/// - parameter reader: A read-only database connection.
/// - parameter release: A closure to call when the read-only connection
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping (_ isInsideTransaction: Bool) -> Void)
throws
{
assert(reader.configuration.readonly)
do {
// Open a long-lived transaction, and enter snapshot isolation
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
try db.beginTransaction(.deferred)
// This also acquires snapshot isolation because checking
// database schema performs a read access.
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.reader = reader
self.release = release
} catch {
// self is not initialized, so deinit will not run.
Self.commitAndRelease(reader: reader, release: release)
throw error
}
}
deinit {
Self.commitAndRelease(reader: reader, release: release)
}
/// 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)
}
/// 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)
}
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
}
release(isInsideTransaction)
}
}
#endif
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more