Compare commits

..
Author SHA1 Message Date
Gwendal Roué 015c4db2b0 SharedValueObservation isolation 2026-12-04 18:04:24 +01:00
Gwendal Roué 9eb2b98ae8 ValueObservation isolation 2026-12-04 17:27:00 +01:00
Gwendal Roué e54f3703b2 Merge pull request #1907 from groue/dev/sending-database-accesses
[GRDB8] Relax Sendable constraints on async database accesses
2026-12-04 15:23:43 +01:00
Gwendal Roué 67ebc8287b Restore support for shorthand notation 2026-12-04 14:44:48 +01:00
Gwendal Roué a311aa30e8 Fix data race in ValueObservation.removeDuplicates(by:) 2026-12-04 14:44:48 +01:00
Gwendal Roué 039e1b8ebe More sending, and fix a bug in WALSnapshotTransaction 2026-12-04 14:44:48 +01:00
Gwendal Roué e49c5e1fff Relax Sendable constraints on closures and results of callbacks 2026-12-04 14:44:48 +01:00
Gwendal Roué 3d5f139ad3 Failing tests for non-sendable values sent or returned from callbacks 2026-12-04 14:44:48 +01:00
Gwendal Roué 61a816df14 CHANGELOG 2026-12-04 14:44:48 +01:00
Gwendal Roué fe9481be94 Update documentation 2026-12-04 14:44:48 +01:00
Gwendal Roué cfe1906a7f Update DocC references 2026-12-04 14:44:48 +01:00
Gwendal Roué e6a04ccab4 Async database accesses have sending results 2026-12-04 14:44:48 +01:00
Gwendal Roué ad1060c383 Failing tests for non-sendable values returned from an async database access 2026-12-04 14:44:48 +01:00
Gwendal Roué 05c382d42c Vendor Disconnected from SE-0538
Disconnected will ship with Swift 6.5
2026-12-04 14:44:48 +01:00
Gwendal Roué a22872c799 Async database access methods accept a sending closure 2026-12-04 14:44:48 +01:00
Gwendal Roué c5e635e9a8 Failing tests for non-sendable value sent to an async database access 2026-12-04 14:44:48 +01:00
Gwendal Roué 2df93772e8 GRDBTestSupport target builds database connections for tests 2026-12-04 14:44:38 +01:00
Gwendal Roué 932122fef4 Rename GRDBTestSupport to GRDBTestSupportC 2026-12-04 14:31:57 +01:00
49 changed files with 5116 additions and 768 deletions

No files matched your search

+3 -1
View File
@@ -152,12 +152,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- **New**: Bump custom SQLite build to version 3.54.1
- **New**: SQLCipher package trait by [@GeorgeElsham](https://github.com/GeorgeElsham) and [@groue](https://github.com/groue) in [#1902](https://github.com/groue/GRDB.swift/pull/1902)
- **New**: `sum(_:orderBy:filter:)` and `total(_:orderBy:filter:)` are available with the system SQLite, from iOS 26, macOS 26, tvOS 26, watchOS 26, and visionOS 26.
- **New**: Async database accesses accept `sending` closures and return `sending` results, instead of requiring `Sendable`.
- **New**: Asynchronous database accesses accept `sending` closures and return `sending` results, instead of requiring `Sendable` closures and results. Some callback-based database accesses (with completion blocks) are improved in the same way (`asyncRead(_:)`, `asyncMigrate(_:completion:)`, `writePublisher(receiveOn:updates:thenRead:)`, etc.)
- **Breaking Change**: Raise deployment targets for Xcode 27 compatibility: iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 9.0
- **Breaking Change**: Raise minimal Swift version to 6.4 (Xcode 27.0)
- **Breaking Change**: Raise minimal SQLite version to 3.36.0
- **Breaking Change**: Raise minimal SQLCipher version to 4.5.0
- **Breaking Change**: Drop CocoaPods support
- **Breaking Change**: In the Swift 5 language mode, the shorthand closure notation in asynchronous database accesses, such as `try await writer.read(Player.fetchAll)`, triggers a compiler warning, even when the `InferSendableFromCaptures` upcoming feature is enabled.
- **Breaking Change**: `ValueObservation.removeDuplicates(by:)` requires a `Sendable` predicate.
- **Breaking Change**: `FetchableRecord.databaseDecodingUserInfo` and `EncodableRecord.databaseEncodingUserInfo` are now declared as `[CodingUserInfoKey: any Sendable]`, as `JSONDecoder.userInfo` and `JSONEncoder.userInfo` are.
- **Breaking Change**: Remove deprecated APIs
+130
View File
@@ -7,6 +7,11 @@ Migrating From GRDB 7 to GRDB 8
- [New requirements](#new-requirements)
- [CocoaPods is no Longer Supported](#cocoapods-is-no-longer-supported)
- [SQLCipher](#sqlcipher)
- [Shorthand Closure Notation in Asynchronous Database Accesses](#shorthand-closure-notation-in-asynchronous-database-accesses)
- [Removing Duplicate Observed Values](#removing-duplicate-observed-values)
- [Starting a ValueObservation](#starting-a-valueobservation)
- [Asynchronous Sequences of Observed Values](#asynchronous-sequences-of-observed-values)
- [Sharing a ValueObservation](#sharing-a-valueobservation)
- [Cached Statements](#cached-statements)
- [JSON User Info](#json-user-info)
@@ -37,6 +42,131 @@ To use GRDB with SQLCipher, enable the `SQLCipher` trait of the GRDB package. Th
When GRDB uses SQLCipher, access SQLite C functions with `import SQLCipher` only. Importing `SQLite3` or `GRDBSQLite` can link the system SQLite next to SQLCipher, which creates undefined behavior.
## Shorthand Closure Notation in Asynchronous Database Accesses
In applications compiled in the Swift 5 language mode, an asynchronous database access that uses the shorthand closure notation triggers a compiler warning with GRDB 8:
```swift
// GRDB 8, application in Swift 5 language mode
// ⚠️ Converting a value of type '(Database) throws -> [Player]' to
// type '(Database) throws -> sending [Player]' risks causing
// data races; this is an error in the Swift 6 language mode
let players = try await dbQueue.read(Player.fetchAll)
```
Fix this warning by writing a regular closure:
```swift
// GRDB 8, application in Swift 5 language mode
let players = try await dbQueue.read { db in
try Player.fetchAll(db)
}
```
Applications compiled in the Swift 6 language mode do not need to adapt their usages of the shorthand closure notation.
Synchronous database accesses are not affected, and still accept the shorthand closure notation in all language modes.
## Removing Duplicate Observed Values
The `ValueObservation.removeDuplicates(by:)` method now requires a `Sendable` predicate closure. If the compiler reports that your predicate is not `Sendable`, make it `Sendable`, for example by capturing only `Sendable` values.
`ValueObservation.removeDuplicates()`, which compares `Equatable` values, is not affected.
## Starting a ValueObservation
In GRDB 7, `ValueObservation.start(in:onError:onChange:)` had to be called from the main actor, and notified fresh values on the main actor. In GRDB 8, it can be called from any actor, and notifies fresh values on this actor. The `onError` and `onChange` callbacks do not need to be `Sendable`:
```swift
actor PlayerTracker {
var playerCount = 0
var cancellable: AnyDatabaseCancellable?
func start(in reader: any DatabaseReader) {
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
// GRDB 8: notifies fresh values on the PlayerTracker actor.
cancellable = observation.start(in: reader) { error in
// handle error
} onChange: { [unowned self] count in
self.playerCount = count
}
}
}
```
The `.immediate` scheduling, which notifies the initial value immediately, is no longer restricted to the main actor: it is available on all actors.
`ValueObservation.start` no longer accepts a `ValueObservationScheduler`. When the observation is started from an actor, remove this `scheduling` argument: fresh values are notified on this actor.
`ValueObservation.start` must now be called from an actor. In nonisolated code, it no longer compiles, with or without a `scheduling` argument. Without one, the compiler reports `'nil' is not compatible with expected argument type 'any Actor'`.
Synchronous nonisolated code that runs on the main thread can start the observation from `MainActor.assumeIsolated`:
```swift
// GRDB 7
let cancellable = observation.start(
in: dbQueue,
scheduling: .immediate)
{ error in
// handle error
} onChange: { value in
print("Fresh value", value)
}
// GRDB 8
let cancellable = MainActor.assumeIsolated {
observation.start(in: dbQueue, scheduling: .immediate) { error in
// handle error
} onChange: { value in
print("Fresh value", value)
}
}
```
Other nonisolated code can start the observation from an actor, or iterate the asynchronous sequence of observed values:
```swift
// GRDB 8
for try await value in observation.values(in: dbQueue) {
print("Fresh value", value)
}
```
The `ValueObservationMainActorScheduler` protocol and the `DelayedMainActorValueObservationScheduler` type were removed. Custom schedulers adopt `ValueObservationScheduler` instead, and implement `schedule(_:)` instead of `scheduleOnMainActor(_:)`.
## Asynchronous Sequences of Observed Values
`ValueObservation.values(in:)` no longer accepts a `scheduling` argument: the loop that iterates the sequence runs with the isolation of its surrounding code, regardless of any scheduler. Remove this argument:
```swift
// GRDB 7
for try await players in observation.values(in: dbQueue, scheduling: .immediate) { ... }
// GRDB 8
for try await players in observation.values(in: dbQueue) { ... }
```
## Sharing a ValueObservation
`SharedValueObservation.start(onError:onChange:)` changes like `ValueObservation.start` (see [Starting a ValueObservation](#starting-a-valueobservation)): it notifies each client on the actor that starts it, its callbacks do not need to be `Sendable`, and it must be called from an actor.
`ValueObservation.shared(in:scheduling:extent:)` now accepts the same scheduling as `ValueObservation.start`: `.async` (the default) or `.immediate`. The `.immediate` scheduling is no longer restricted to the main actor: each client, on any actor, is notified of its initial value immediately when it starts.
Other schedulers, such as `.task` or `.async(onQueue:)`, are no longer accepted. Remove them:
```swift
// GRDB 7
let sharedObservation = observation.shared(in: dbQueue, scheduling: .task)
for try await players in sharedObservation.values() { ... }
// GRDB 8
let sharedObservation = observation.shared(in: dbQueue)
for try await players in sharedObservation.values() { ... }
```
## Cached Statements
The statements returned by `Database.cachedStatement(sql:)` and `Database.cachedStatement(literal:)` no longer preserve their arguments between two calls. You must set the arguments of a cached statement each time you load it from the cache:
+1 -1
View File
@@ -145,7 +145,7 @@ No matter which observation technique you use, you have common guarantees:
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rolled back.
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). GRDB makes sure notifications happen in the same order as database transactions.
Next, notifications happen on the actor that starts the observation. GRDB makes sure notifications happen in the same order as database transactions.
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
+8 -3
View File
@@ -86,7 +86,8 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
56A1E0012FD0A00000ABCDEF /* GRDBTestSupport */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBTestSupport; sourceTree = "<group>"; };
1D1937F0CDDDB96354EF407C /* GRDBTestSupport */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBTestSupport; sourceTree = "<group>"; };
565F928630C2F80E009B685D /* GRDBTestSupportC */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBTestSupportC; sourceTree = "<group>"; };
56C883812FCC65300099DE9A /* Sources/GRDB */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (56C8842B2FCC65300099DE9A /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Sources/GRDB; sourceTree = "<group>"; };
56C887EB2FCC6B9A0099DE9A /* GRDBSwift5Tests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBSwift5Tests; sourceTree = "<group>"; };
56D0F1FC30C171E0004DBD2B /* GRDBSwift6ApproachableConcurrencyTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBSwift6ApproachableConcurrencyTests; sourceTree = "<group>"; };
@@ -160,7 +161,8 @@
56D0F1FC30C171E0004DBD2B /* GRDBSwift6ApproachableConcurrencyTests */,
56D0F20130C171E0004DBD2B /* GRDBSwift6MainActorIsolationTests */,
56D0F20630C171E0004DBD2B /* GRDBSwift6Tests */,
56A1E0012FD0A00000ABCDEF /* GRDBTestSupport */,
1D1937F0CDDDB96354EF407C /* GRDBTestSupport */,
565F928630C2F80E009B685D /* GRDBTestSupportC */,
DC37740319C8CBB3004FCF85 /* Supporting Files */,
);
path = Tests;
@@ -248,6 +250,7 @@
064B54476CF36B181327EDFC /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
1D1937F0CDDDB96354EF407C /* GRDBTestSupport */,
56D0F20630C171E0004DBD2B /* GRDBSwift6Tests */,
);
name = GRDBSwift6Tests;
@@ -269,6 +272,7 @@
56D0F20830C17218004DBD2B /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
1D1937F0CDDDB96354EF407C /* GRDBTestSupport */,
56D0F1FC30C171E0004DBD2B /* GRDBSwift6ApproachableConcurrencyTests */,
);
name = GRDBSwift6ApproachableConcurrencyTests;
@@ -290,7 +294,7 @@
56E5D8001B4D422E00430942 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
56A1E0012FD0A00000ABCDEF /* GRDBTestSupport */,
565F928630C2F80E009B685D /* GRDBTestSupportC */,
56C887EB2FCC6B9A0099DE9A /* GRDBSwift5Tests */,
);
name = GRDBSwift5Tests;
@@ -312,6 +316,7 @@
F0D310A8491E14866D6C126A /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
1D1937F0CDDDB96354EF407C /* GRDBTestSupport */,
56D0F20130C171E0004DBD2B /* GRDBSwift6MainActorIsolationTests */,
);
name = GRDBSwift6MainActorIsolationTests;
+9 -4
View File
@@ -102,7 +102,8 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
56A1E0022FD0A00000ABCDEF /* GRDBTestSupport */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBTestSupport; sourceTree = "<group>"; };
3C9247A9B16595411751F740 /* GRDBTestSupport */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBTestSupport; sourceTree = "<group>"; };
565F928B30C2F820009B685D /* GRDBTestSupportC */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBTestSupportC; sourceTree = "<group>"; };
56FF360A2FCC8CBA00E841A9 /* Sources/GRDB */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (56FF36B42FCC8CBA00E841A9 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Sources/GRDB; sourceTree = "<group>"; };
56FF3CD82FCC8D9600E841A9 /* GRDBSwift5Tests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBSwift5Tests; sourceTree = "<group>"; };
6C4C1471D2FDF9FD118A4A88 /* GRDBSwift6ApproachableConcurrencyTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = GRDBSwift6ApproachableConcurrencyTests; sourceTree = "<group>"; };
@@ -165,12 +166,13 @@
isa = PBXGroup;
children = (
5614DEEE1BA9D6F9003163B3 /* Frameworks */,
DC37740319C8CBB3004FCF85 /* Supporting Files */,
56FF3CD82FCC8D9600E841A9 /* GRDBSwift5Tests */,
6C4C1471D2FDF9FD118A4A88 /* GRDBSwift6ApproachableConcurrencyTests */,
CA4DBF2CD3C9B36548CD0E27 /* GRDBSwift6MainActorIsolationTests */,
8E9FCAC86BBBA0815D11605C /* GRDBSwift6Tests */,
56A1E0022FD0A00000ABCDEF /* GRDBTestSupport */,
3C9247A9B16595411751F740 /* GRDBTestSupport */,
565F928B30C2F820009B685D /* GRDBTestSupportC */,
DC37740319C8CBB3004FCF85 /* Supporting Files */,
);
path = Tests;
sourceTree = "<group>";
@@ -290,6 +292,7 @@
D7F44CA5E3DF0445555A67AD /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
3C9247A9B16595411751F740 /* GRDBTestSupport */,
CA4DBF2CD3C9B36548CD0E27 /* GRDBSwift6MainActorIsolationTests */,
);
name = GRDBCustomSwift6MainActorIsolationTests;
@@ -311,6 +314,7 @@
91A130C334C256F66E3035BE /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
3C9247A9B16595411751F740 /* GRDBTestSupport */,
8E9FCAC86BBBA0815D11605C /* GRDBSwift6Tests */,
);
name = GRDBCustomSwift6Tests;
@@ -332,6 +336,7 @@
910B2E4620DF4C75AB752E6B /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
3C9247A9B16595411751F740 /* GRDBTestSupport */,
6C4C1471D2FDF9FD118A4A88 /* GRDBSwift6ApproachableConcurrencyTests */,
);
name = GRDBCustomSwift6ApproachableConcurrencyTests;
@@ -377,7 +382,7 @@
F3BA80A21CFB2F6F003DC1BA /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
56A1E0022FD0A00000ABCDEF /* GRDBTestSupport */,
565F928B30C2F820009B685D /* GRDBTestSupportC */,
56FF3CD82FCC8D9600E841A9 /* GRDBSwift5Tests */,
);
name = GRDBCustomSwift5Tests;
+15 -5
View File
@@ -95,10 +95,20 @@ let package = Package(
]),
.target(
name: "GRDBTestSupport",
path: "Tests/GRDBTestSupport"),
dependencies: ["GRDB"],
path: "Tests/GRDBTestSupport",
cSettings: cSettings,
swiftSettings: swiftSettings + [
.enableUpcomingFeature("ApproachableConcurrency"),
],
),
.target(
name: "GRDBTestSupportC",
path: "Tests/GRDBTestSupportC",
),
.testTarget(
name: "GRDBSwift5Tests",
dependencies: ["GRDB", "GRDBTestSupport"],
dependencies: ["GRDB", "GRDBTestSupportC"],
resources: [
.copy("Betty.jpeg"),
.copy("Private/InflectionsTests.json"),
@@ -114,7 +124,7 @@ let package = Package(
),
.testTarget(
name: "GRDBSwift6ApproachableConcurrencyTests",
dependencies: ["GRDB"],
dependencies: ["GRDB", "GRDBTestSupport"],
cSettings: cSettings,
swiftSettings: swiftSettings + [
.enableUpcomingFeature("ApproachableConcurrency"),
@@ -122,7 +132,7 @@ let package = Package(
),
.testTarget(
name: "GRDBSwift6MainActorIsolationTests",
dependencies: ["GRDB"],
dependencies: ["GRDB", "GRDBTestSupport"],
cSettings: cSettings,
swiftSettings: swiftSettings + [
.defaultIsolation(MainActor.self),
@@ -131,7 +141,7 @@ let package = Package(
),
.testTarget(
name: "GRDBSwift6Tests",
dependencies: ["GRDB"],
dependencies: ["GRDB", "GRDBTestSupport"],
cSettings: cSettings,
swiftSettings: swiftSettings,
),
+11 -7
View File
@@ -379,13 +379,15 @@ extension DatabasePool: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
}
// Safe because `value` is sending, and called only once.
nonisolated(unsafe) let value = value
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
@@ -446,13 +448,15 @@ extension DatabasePool: DatabaseReader {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
}
// Safe because `value` is sending, and called only once.
nonisolated(unsafe) let value = value
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
@@ -493,7 +497,7 @@ extension DatabasePool: DatabaseReader {
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
asyncConcurrentRead(value)
}
@@ -536,7 +540,7 @@ extension DatabasePool: DatabaseReader {
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -708,7 +712,7 @@ 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 @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
_ completion: sending @escaping (Result<WALSnapshotTransaction, Error>) -> Void
) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
@@ -830,7 +834,7 @@ extension DatabasePool: DatabaseWriter {
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
@@ -886,7 +890,7 @@ extension DatabasePool: DatabaseWriter {
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: sending @escaping (Database) -> Void
) {
writer.async(updates)
}
+5 -5
View File
@@ -245,7 +245,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
writer.async { db in
defer {
@@ -285,7 +285,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
writer.async { value(.success($0)) }
}
@@ -295,7 +295,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -414,7 +414,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: sending @escaping (Result<Database, Error>) -> Void
) {
writer.async { updates(.success($0)) }
}
@@ -462,7 +462,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: sending @escaping (Database) -> Void
) {
writer.async(updates)
}
+67 -8
View File
@@ -22,14 +22,16 @@ import Dispatch
/// ### Reading from the Database
///
/// - ``read(_:)-3806d``
/// - ``read(_:)-5mfwu``
/// - ``read(_:)-40k5v``
/// - ``read(_:)-5t1ik``
/// - ``readPublisher(receiveOn:value:)``
/// - ``asyncRead(_:)``
///
/// ### Unsafe Methods
///
/// - ``unsafeRead(_:)-5i7tf``
/// - ``unsafeRead(_:)-90w0p``
/// - ``unsafeRead(_:)-9e4ug``
/// - ``unsafeRead(_:)-45db3``
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
@@ -244,7 +246,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// 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 @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -352,7 +354,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// 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 @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -403,7 +405,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// Starts a value observation.
///
/// Use the ``ValueObservation/start(in:scheduling:onError:onChange:)``
/// Use the ``ValueObservation/start(in:scheduling:isolation:onError:onChange:)``
/// method instead.
///
/// - parameter observation: a ValueObservation.
@@ -415,6 +417,63 @@ public protocol DatabaseReader: AnyObject, Sendable {
) -> AnyDatabaseCancellable
}
extension DatabaseReader {
// MARK: - Asynchronous Database Access
/// Executes read-only database operations, and returns their `Sendable`
/// result after they have finished executing.
///
/// This method supports the shorthand closure notation, where a
/// `Sendable` function such as `Player.fetchAll` is given instead of
/// a closure. For example:
///
/// ```swift
/// let players = try await reader.read(Player.fetchAll)
/// ```
///
/// Apart from its `Sendable` requirements, this method behaves exactly
/// like ``DatabaseReader/read(_:)-40k5v``. See
/// <doc:SwiftConcurrency#Shorthand-Closure-Notation> for more information.
///
/// - parameter value: A function 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.
@_disfavoredOverload
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read { db in try value(db) }
}
/// Executes database operations, and returns their `Sendable` result
/// after they have finished executing.
///
/// This method supports the shorthand closure notation, where a
/// `Sendable` function such as `Player.fetchAll` is given instead of
/// a closure. For example:
///
/// ```swift
/// let players = try await reader.unsafeRead(Player.fetchAll)
/// ```
///
/// Apart from its `Sendable` requirements, this method behaves exactly
/// like ``DatabaseReader/unsafeRead(_:)-9e4ug``. See
/// <doc:SwiftConcurrency#Shorthand-Closure-Notation> for more information.
///
/// - parameter value: A function 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.
@_disfavoredOverload
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await unsafeRead { db in try value(db) }
}
}
extension DatabaseReader {
// MARK: - Backup
@@ -655,7 +714,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncRead(value)
}
@@ -671,7 +730,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
@@ -743,7 +802,7 @@ extension DatabaseSnapshotReader {
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
asyncRead(value)
}
@@ -86,8 +86,8 @@ extension DatabaseRegionObservation {
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
public func start(
in writer: any DatabaseWriter,
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Database) -> Void)
onError: sending @escaping (Error) -> Void,
onChange: sending @escaping (Database) -> Void)
-> AnyDatabaseCancellable
{
let stateMutex = Mutex(ObservationState.pending)
@@ -148,10 +148,10 @@ extension DatabaseRegionObservation {
private class DatabaseRegionObserver: TransactionObserver {
let region: DatabaseRegion
let onChange: @Sendable (Database) -> Void
let onChange: (Database) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
self.region = region
self.onChange = onChange
}
+2 -2
View File
@@ -164,7 +164,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
@@ -184,7 +184,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
+3 -1
View File
@@ -330,13 +330,15 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
}
// Safe because `value` is sending, and called only once.
nonisolated(unsafe) let value = value
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
+122 -19
View File
@@ -22,18 +22,21 @@ import Dispatch
/// ### Writing into the Database
///
/// - ``write(_:)-76inz``
/// - ``write(_:)-7mrav``
/// - ``write(_:)-4gnqx``
/// - ``writePublisher(receiveOn:updates:)``
/// - ``writePublisher(receiveOn:updates:thenRead:)``
/// - ``writeWithoutTransaction(_:)-4qh1w``
/// - ``writeWithoutTransaction(_:)-18zhj``
/// - ``writeWithoutTransaction(_:)-7oqlh``
/// - ``writeWithoutTransaction(_:)-1b250``
/// - ``asyncWrite(_:completion:)``
/// - ``asyncWriteWithoutTransaction(_:)``
///
/// ### Exclusive Access to the Database
///
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
/// - ``barrierWriteWithoutTransaction(_:)-5u7gc``
/// - ``barrierWriteWithoutTransaction(_:)-1dvaq``
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
///
/// ### Reading from the Latest Committed Database State
@@ -254,7 +257,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// 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 @Sendable (Result<Database, Error>) -> Void
_ updates: sending @escaping (Result<Database, Error>) -> Void
)
/// Schedules database operations for execution, and returns immediately.
@@ -288,7 +291,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: sending @escaping (Database) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -372,7 +375,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// 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 @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
)
}
@@ -459,8 +462,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void
_ updates: sending @escaping (Database) throws -> T,
completion: sending @escaping (Database, Result<T, Error>) -> Void
) {
asyncWriteWithoutTransaction { db in
do {
@@ -621,6 +624,86 @@ extension DatabaseWriter {
}
}
/// Executes database operations wrapped in a transaction, and returns
/// their `Sendable` result after they have finished executing.
///
/// This method supports the shorthand closure notation, where a
/// `Sendable` function such as `Player.deleteAll` is given instead of
/// a closure. For example:
///
/// ```swift
/// let deletedCount = try await writer.write(Player.deleteAll)
/// ```
///
/// Apart from its `Sendable` requirements, this method behaves exactly
/// like ``DatabaseWriter/write(_:)-7mrav``. See
/// <doc:SwiftConcurrency#Shorthand-Closure-Notation> for more information.
///
/// - parameter updates: A function 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.
@_disfavoredOverload
public func write<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await write { db in try updates(db) }
}
/// Executes database operations outside of any transaction, and returns
/// their `Sendable` result after they have finished executing.
///
/// This method supports the shorthand closure notation, where a
/// `Sendable` function such as `Player.fetchCount` is given instead of
/// a closure. For example:
///
/// ```swift
/// let count = try await writer.writeWithoutTransaction(Player.fetchCount)
/// ```
///
/// Apart from its `Sendable` requirements, this method behaves exactly
/// like ``DatabaseWriter/writeWithoutTransaction(_:)-7oqlh``. See
/// <doc:SwiftConcurrency#Shorthand-Closure-Notation> for more information.
///
/// - parameter updates: A function 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.
@_disfavoredOverload
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writeWithoutTransaction { db in try updates(db) }
}
/// Executes database operations with exclusive access to the database,
/// and returns their `Sendable` result after they have
/// finished executing.
///
/// This method supports the shorthand closure notation, where a
/// `Sendable` function such as `Player.fetchCount` is given instead of
/// a closure. For example:
///
/// ```swift
/// let count = try await writer.barrierWriteWithoutTransaction(
/// Player.fetchCount)
/// ```
///
/// Apart from its `Sendable` requirements, this method behaves exactly
/// like ``DatabaseWriter/barrierWriteWithoutTransaction(_:)-5u7gc``. See
/// <doc:SwiftConcurrency#Shorthand-Closure-Notation> for more information.
///
/// - parameter updates: A function 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.
@_disfavoredOverload
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await barrierWriteWithoutTransaction { db in try updates(db) }
}
/// Erase the database: delete all content, drop all tables, etc.
public func erase() async throws {
try await writeWithoutTransaction { try $0.erase() }
@@ -690,6 +773,22 @@ extension DatabaseWriter {
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> Output
) -> DatabasePublishers.Write<Output> {
// `updates` is Sendable, and not `sending`, because `Output` is
// not `sending`: a `sending` closure could return a non-Sendable
// value it has captured. Such a value would be published to all
// subscriptions, and race with the next execution of `updates` on
// the writer dispatch queue.
//
// `Output` is not `sending` because otherwise users could not
// publish non-Sendable records fetched from the database (region
// isolation ties them to the `db` argument).
//
// The price is a possible data race when `updates` returns a
// non-Sendable value that the database connection keeps alive
// across calls, such as a cached statement: a subscriber could
// use it while another subscription executes `updates`. This never
// happens in practice, because people do not publish values that
// contain the database instance.
OnDemandFuture { fulfill in
self.asyncWrite(updates, completion: { _, result in
fulfill(result)
@@ -749,25 +848,29 @@ 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.
public func writePublisher<T: Sendable, Output>(
public func writePublisher<T, Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> T,
updates: sending @escaping (Database) throws -> sending T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output
) -> DatabasePublishers.Write<Output> {
OnDemandFuture { fulfill in
// Safe because `updates` is sending, and only called from the
// writer dispatch queue (once per subscription, serially).
nonisolated(unsafe) let updates = updates
return OnDemandFuture { fulfill in
self.asyncWriteWithoutTransaction { db in
var updatesValue: T?
var result = Disconnected<T?>(nil)
do {
try db.inTransaction {
updatesValue = try updates(db)
try result.exchange(newValue: updates(db))
return .commit
}
} catch {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { [updatesValue] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
let updatesValue = result.consume()!
self.spawnConcurrentRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue) } })
}
}
}
@@ -845,7 +948,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncRead(value)
}
@@ -861,7 +964,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
@@ -904,13 +1007,13 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: sending @escaping (Result<Database, Error>) -> Void
) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: sending @escaping (Database) -> Void
) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -920,7 +1023,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
base.spawnConcurrentRead(value)
}
+4 -1
View File
@@ -228,7 +228,10 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping @Sendable (Database) -> Void) {
func async(_ block: sending @escaping (Database) -> Void) {
// The block is `sending`, and executed only once: it is safe to
// execute it on the database dispatch queue.
nonisolated(unsafe) let block = block
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+6 -6
View File
@@ -113,16 +113,16 @@ extension Database {
/// - parameter onCommit: A closure executed on transaction commit.
/// - parameter onRollback: A closure executed on transaction rollback.
public func afterNextTransaction(
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void = { _ in })
onCommit: sending @escaping (Database) -> Void,
onRollback: sending @escaping (Database) -> Void = { _ in })
{
class TransactionHandler: TransactionObserver {
let onCommit: @Sendable (Database) -> Void
let onRollback: @Sendable (Database) -> Void
let onCommit: (Database) -> Void
let onRollback: (Database) -> Void
init(
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void
onCommit: @escaping (Database) -> Void,
onRollback: @escaping (Database) -> Void
) {
self.onCommit = onCommit
self.onRollback = onRollback
@@ -103,7 +103,9 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
func asyncRead(_ value: sending @escaping (Result<Database, Error>) -> Void) {
// Safe because `value` is sending, and called only once.
nonisolated(unsafe) let value = value
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
@@ -115,6 +117,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
// At least check if self was closed:
if self.databaseAccessMutex.load() == nil {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
value(.success(db))
}
@@ -97,7 +97,7 @@ try dbQueue.write { db in
}
```
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
See ``DatabaseReader/read(_:)-40k5v`` and ``DatabaseWriter/write(_:)-7mrav``.
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
@@ -259,7 +259,7 @@ All you need is a little "concurrent thinking", based on those two basic facts:
Does this mean you can't rely on anything? Of course not:
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value is fetched, and soon notified on the main thread where the screen can be updated.
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value is fetched, and soon notified on the actor that started the observation, such as the main actor where the screen can be updated.
- As said above, the moment of truth is the next write access!
@@ -78,7 +78,7 @@ See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the li
By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see <doc:ValueObservation#Specifying-the-Tracked-Region>.
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, asynchronously, on the actor that starts the observation. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
@@ -98,81 +98,50 @@ The database observation stops when the cancellable returned by the `start` meth
## ValueObservation Scheduling
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously:
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, asynchronously, on the actor that starts the observation. In a graphical application, this is usually the main actor:
```swift
// The default scheduling
let cancellable = observation.start(in: dbQueue) { error in
// This closure is MainActor-isolated.
} onChange: { value in
// This closure is MainActor-isolated.
print("Fresh value", value)
@MainActor func startObservation() {
cancellable = observation.start(in: dbQueue) { error in
// Called on the main actor
} onChange: { value in
// Called on the main actor
print("Fresh value", value)
}
}
```
You can change this behavior by adding a `scheduling` argument to the `start()` method.
The callbacks are called in order, on the actor that starts the observation, so they can access its state, and they do not need to be `Sendable`.
For example, the ``ValueObservationMainActorScheduler/immediate`` scheduler notifies all values on the main actor, and notifies the first one immediately when the observation starts.
The `start()` method must be called from an actor. Synchronous nonisolated code that runs on the main thread can call it from `MainActor.assumeIsolated`. Other nonisolated code can iterate the asynchronous sequence returned by ``values(in:bufferingPolicy:)``.
You can change the default scheduling by adding a `scheduling` argument to the `start()` method.
For example, the ``IsolatedValueObservationScheduling/immediate`` scheduling notifies all values on the actor that starts the observation, and notifies the first one immediately when the observation starts.
It is very useful in graphical applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Be aware that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests!
```swift
// Immediate scheduling notifies
// the initial value right on subscription.
let cancellable = observation
.start(in: dbQueue, scheduling: .immediate) { error in
// Called on the main actor
} onChange: { value in
// Called on the main actor
print("Fresh value", value)
}
// <- Here "Fresh value" has already been printed.
```
The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispatchQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
```swift
// Async scheduling notifies all values
// on the specified dispatch queue.
let myQueue: DispatchQueue
let cancellable = observation
.start(in: dbQueue, scheduling: .async(myQueue)) { error in
// Called asynchronously on myQueue
} onChange: { value in
// Called asynchronously on myQueue
print("Fresh value", value)
}
```
The ``ValueObservationScheduler/task`` scheduler asynchronously schedules values and errors on the cooperative thread pool. It is implicitly used when you turn a ValueObservation into an async sequence. You can specify it explicitly when you intend to consume a shared observation as an async sequence:
```swift
do {
for try await players in observation.values(in: dbQueue) {
// Called on the cooperative thread pool
print("Fresh players", players)
}
} catch {
// Handle error
@MainActor func startObservation() {
cancellable = observation
.start(in: dbQueue, scheduling: .immediate) { error in
// Called on the main actor
} onChange: { value in
// Called on the main actor
print("Fresh value", value)
}
// <- Here "Fresh value" has already been printed.
}
let sharedObservation = observation.shared(in: dbQueue, scheduling: .task)
do {
for try await players in sharedObservation.values() {
// Called on the cooperative thread pool
print("Fresh players", players)
}
} catch {
// Handle error
}
```
As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control over the execution of the database fetch:
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main actor, when the observation starts, so that the initial value can be notified immediately.
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the actor that starts the observation, so that the initial value can be notified immediately.
- With the default `.async` scheduling, the initial fetch is always performed asynchronously. It never blocks the main thread.
- With the default `.async` scheduling, the initial fetch is always performed asynchronously. It never blocks the actor that starts the observation.
- By default, fresh values are fetched immediately after the database was changed. In particular, modifying the database on the main thread triggers a fetch on the main thread as well.
@@ -194,13 +163,16 @@ let sharedObservation = ValueObservation
.shared(in: dbQueue)
```
`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. As a replacement, you may for example use Combine apis:
Like `ValueObservation`, a shared observation notifies each client on the actor that starts it with ``SharedValueObservation/start(isolation:onError:onChange:)``, so that clients on distinct actors can share a single observation. The `scheduling` argument of ``shared(in:scheduling:extent:)`` applies to all clients: with the `.immediate` scheduling, each client is notified of its initial value immediately when it starts.
`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. Apply such operators to the `ValueObservation`, before it is shared:
```swift
let cancellable = try sharedObservation
.publisher() // Turn shared observation into a Combine Publisher
.map { ... } // The map operator from Combine
.sink(...)
// SharedValueObservation<Int>
let sharedObservation = ValueObservation
.tracking { db in try Player.fetchAll(db) }
.map { players in players.count }
.shared(in: dbQueue)
```
@@ -315,13 +287,12 @@ When needed, you can help GRDB optimize observations and reduce database content
### Accessing Observed Values
- ``start(in:scheduling:onError:onChange:)-t62r``
- ``start(in:scheduling:onError:onChange:)-4mqbs``
- ``start(in:scheduling:isolation:onError:onChange:)``
- ``publisher(in:scheduling:)``
- ``values(in:scheduling:bufferingPolicy:)``
- ``values(in:bufferingPolicy:)``
- ``DatabaseCancellable``
- ``IsolatedValueObservationScheduling``
- ``ValueObservationScheduler``
- ``ValueObservationMainActorScheduler``
### Mapping Values
@@ -46,40 +46,36 @@ The following sections describe, with more details, how GRDB interacts with Swif
### Shorthand Closure Notation
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
In the Swift 5 language mode, the compiler emits a warning when an asynchronous database access is written with the shorthand closure notation:
```swift
// Standard closure:
let count = try await writer.read { db in
try Player.fetchCount(db)
let players = try await writer.read { db in
try Player.fetchAll(db)
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
// ⚠️ Converting a value of type '(Database) throws -> [Player]' to
// type '(Database) throws -> sending [Player]' risks causing
// data races
let players = try await writer.read(Player.fetchAll)
```
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
**To avoid this warning**, use a standard closure instead of the shorthand notation.
- **Using Xcode**
In the Swift 6 language mode, the compiler accepts the shorthand notation as long as the function and its result are `Sendable`:
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
```swift
struct Player: Sendable, TableRecord, FetchableRecord { }
- **In a SwiftPM package manifest**
// OK
let count = try await writer.read(Player.fetchCount)
let players = try await writer.read(Player.fetchAll)
```
Enable the `InferSendableFromCaptures` upcoming feature:
```swift
.target(
name: "MyTarget",
swiftSettings: [
.enableUpcomingFeature("InferSendableFromCaptures")
]
)
```
When the function is not `Sendable`, the compiler selects a synchronous database access instead of the intended asynchronous one: the `await` has no effect, the code blocks the current thread, and the compiler emits a warning "No 'async' operations occur within 'await' expression". To perform the intended asynchronous access without any warning, make the function `Sendable`, or write a standard closure.
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
Synchronous database accesses are not affected, and accept the shorthand closure notation in all language modes.
### Non-Sendable Configuration of Record Types
@@ -114,7 +110,7 @@ extension Player: FetchableRecord, PersistableRecord {
### Non-Sendable Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checking, the compiler emits an error or a warning when the application reads or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checking, the compiler emits an error or a warning when the application reads or observes records of a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
By default, Swift classes are not Sendable. They are not thread-safe. With GRDB, record classes will typically trigger compiler diagnostics:
@@ -139,16 +135,6 @@ let observation = ValueObservation.tracking { db in
}
```
Writing a non-Sendable record is possible, as long as the record is not used after the write:
```swift
let player: Player
try await writer.write { db in
try player.insert(db)
}
// From here, any use of `player` is a compiler error.
```
#### The solution
The solution is to have the record type conform to `Sendable`.
@@ -220,7 +206,9 @@ Some people recommend avoiding long blocking jobs on the cooperative thread pool
```swift
func fetchPlayers() async throws -> [Player] {
try await writer.read(Player.fetchAll)
try await writer.read { db in
try Player.fetchAll(db)
}
}
```
@@ -229,7 +217,9 @@ But there are some scenarios where the compiler misses opportunities to use `awa
```swift
Task {
// The compiler does not spot the missing `await`
let players = try writer.read(Player.fetchAll)
let players = try writer.read { db in
try Player.fetchAll(db)
}
}
```
@@ -382,7 +382,7 @@ public struct DatabaseMigrator: Sendable {
/// from succeeding.
public func asyncMigrate(
_ writer: any DatabaseWriter,
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
completion: sending @escaping (Result<Database, Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
@@ -65,8 +65,7 @@ public struct TableOptions: OptionSet, Sendable {
///
/// ### Define Other Constraints
///
/// - ``check(_:)-6u1za``
/// - ``check(_:)-jpcg``
/// - ``check(_:)``
/// - ``check(sql:)``
/// - ``constraint(literal:)``
/// - ``constraint(sql:)``
+9 -2
View File
@@ -134,7 +134,11 @@ final class Pool<T: Sendable>: Sendable {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
func asyncGet(_ execute: sending @escaping (Result<ElementAndRelease, Error>) -> Void) {
// The function is `sending`, and executed only once: it is safe to
// execute it on the semaphore dispatch queue.
nonisolated(unsafe) let execute = execute
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -214,7 +218,10 @@ final class Pool<T: Sendable>: Sendable {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
func asyncBarrier(execute barrier: sending @escaping () -> Void) {
// The function is `sending`, and executed only once: it is safe to
// execute it on the barrier dispatch queue.
nonisolated(unsafe) let barrier = barrier
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
@@ -6,21 +6,12 @@ extension ValueObservation {
/// equivalent, for purposes of filtering. Return true from this closure
/// to indicate that the second element is a duplicate of the first.
public func removeDuplicates(
by predicate: sending @escaping (Reducer.Value, Reducer.Value) -> Bool
by predicate: @escaping @Sendable (Reducer.Value, Reducer.Value) -> Bool
) -> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>> {
// The predicate is marked `sending`, which allows us to statically
// determine that it will have no other uses after this call.
// (according to <https://github.com/swiftlang/swift-evolution/blob/main/proposals/0433-mutex.md#interactions-with-swift-concurrency>)
//
// And because `predicate` will only be used serially, in the
// reducer queue of `ValueObservation` observers, we can say that
// this is safe.
//
// Anyway if we would not accept non-sendable closures, we could
// not deal with `Equatable.==`...
nonisolated(unsafe) let predicate = predicate
return mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) }
// The predicate must be Sendable, because it is shared by all
// observations started from the returned `ValueObservation`, and
// those observations can run concurrently.
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) }
}
}
@@ -70,7 +61,7 @@ extension ValueObservation where Reducer.Value: Equatable {
public func removeDuplicates()
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: ==) }
mapReducer { base in ValueReducers.RemoveDuplicates(base, predicate: { $0 == $1 }) }
}
}
@@ -82,9 +73,9 @@ extension ValueReducers {
public struct RemoveDuplicates<Base: ValueReducer>: ValueReducer {
private var base: Base
private var previousValue: Base.Value?
private var predicate: (Base.Value, Base.Value) -> Bool
private var predicate: @Sendable (Base.Value, Base.Value) -> Bool
init(_ base: Base, predicate: @escaping (Base.Value, Base.Value) -> Bool) {
init(_ base: Base, predicate: @escaping @Sendable (Base.Value, Base.Value) -> Bool) {
self.base = base
self.predicate = predicate
}
@@ -83,16 +83,14 @@ extension ValueObservation {
/// .shared(in: dbQueue, extent: .observationLifetime)
/// ```
///
/// By default, fresh values are dispatched asynchronously on the
/// main dispatch queue. You can change this behavior by providing a
/// scheduler.
///
/// For example, the ``ValueObservationMainActorScheduler/immediate``
/// scheduler notifies all values on the main dispatch queue, and
/// notifies the first one immediately when the
/// ``SharedValueObservation/start(onError:onChange:)`` method is called.
/// The `immediate` scheduling requires that the observation starts from the
/// main thread (a fatal error is raised otherwise):
/// A client started with
/// ``SharedValueObservation/start(isolation:onError:onChange:)`` is
/// notified on the actor that starts it, so that clients on distinct
/// actors can share a single observation. By default, each client is
/// notified of its initial value asynchronously. The
/// ``IsolatedValueObservationScheduling/immediate`` scheduling
/// notifies each client of its initial value immediately, when
/// it starts:
///
/// ```swift
/// let observation = ValueObservation.tracking { db in
@@ -103,30 +101,48 @@ extension ValueObservation {
/// in: dbQueue,
/// scheduling: .immediate)
///
/// let cancellable = sharedObservation.start { error in
/// // handle error
/// } onChange: { (players: [Player]) in
/// print("Fresh players: \(players)")
/// @MainActor func startObservation() {
/// cancellable = sharedObservation.start { error in
/// // handle error
/// } onChange: { (players: [Player]) in
/// print("Fresh players: \(players)")
/// }
/// // <- here "Fresh players" is already printed.
/// }
/// // <- here "Fresh players" is already printed.
/// ```
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A Scheduler. By default, fresh values are
/// dispatched asynchronously on the main queue.
/// - parameter scheduling: Determines when the initial value is
/// notified. By default, it is notified asynchronously.
/// - parameter extent: The extent of the shared database observation.
/// - returns: A `SharedValueObservation`
public func shared(
in reader: any DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
scheduling: IsolatedValueObservationScheduling = .async,
extent: SharedValueObservationExtent = .whileObserved)
-> SharedValueObservation<Reducer.Value>
where Reducer: ValueReducer
{
SharedValueObservation(scheduling: scheduler, extent: extent) { onError, onChange in
// The upstream observation notifies the clients of the shared
// observation directly: each client notifies values with its
// own scheduler.
let scheduler = DirectValueObservationScheduler(
immediate: scheduling.immediateInitialValue)
return SharedValueObservation(scheduling: scheduling, extent: extent) { onError, onChange in
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
}
}
@available(*, unavailable, message: "Use IsolatedValueObservationScheduling: .async or .immediate.")
public func shared(
in reader: any DatabaseReader,
scheduling scheduler: some ValueObservationScheduler,
extent: SharedValueObservationExtent = .whileObserved)
-> SharedValueObservation<Reducer.Value>
where Reducer: ValueReducer
{
fatalError("unavailable")
}
}
/// A shared value observation saves database resources by sharing a single
@@ -165,15 +181,21 @@ extension ValueObservation {
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// ```
public final class SharedValueObservation<Element: Sendable>: @unchecked Sendable {
// @unchecked Sendable because state is protected by `lock`.
private let scheduler: any ValueObservationScheduler
// @unchecked Sendable because state is protected by `condition`.
private let scheduling: IsolatedValueObservationScheduling
private let extent: SharedValueObservationExtent
private let startObservation: ValueObservationStart<Element>
// Clients are notified outside of the lock, so that a client can be
// cancelled from any thread during a notification without deadlock.
private let lock = NSLock()
// protected by lock
// Protects the state below. Clients are notified outside of the
// lock, so that a client can be cancelled from any thread during a
// notification without deadlock.
//
// A condition lets a client that needs an immediate initial value
// wait until the upstream observation, started by another client
// from another thread, has fetched its initial value.
private let condition = NSCondition()
// protected by condition
private var clients: [Client]
private var currentSubscription: ValueObservationSubscription? // nil when not observing
private var lastResult: Result<Element, Error>?
@@ -188,49 +210,68 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
var cancellable: AnyDatabaseCancellable?
}
/// A client receives the events of the shared observation, and
/// notifies them with its own scheduler.
///
/// The events received while the client is starting are notified
/// when the client finishes starting, so that the first one can be
/// notified synchronously, from the caller of `start`.
private final class Client: Sendable {
private let scheduler: any ValueObservationScheduler
private let onError: @Sendable (Error) -> Void
private let onChange: @Sendable (Element) -> Void
private let stateMutex = Mutex(State())
private struct State {
var isCancelled = false
/// True when a ValueObservation event was notified, and we must
/// not notify the last result of the shared observation as the
/// initial event.
var shouldDiscardInitialResult = false
var isStarting = true
/// The events received while the client is starting.
var pendingEvents: [Result<Element, Error>] = []
}
init(
scheduler: some ValueObservationScheduler,
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Element) -> Void
) {
self.scheduler = scheduler
self.onError = onError
self.onChange = onChange
}
/// Notifies the last result of the shared observation as the initial
/// value, unless a ValueObservation event was already notified.
func notifyInitial(_ result: Result<Element, Error>) {
guard shouldNotifyInitialResult() else { return }
switch result {
case let .failure(error):
onError(error)
case let .success(value):
onChange(value)
/// Notifies an event, unless the client is starting. In this case,
/// the event is notified when the client finishes starting.
func receive(_ result: Result<Element, Error>) {
let shouldSchedule = stateMutex.withLock { state in
if state.isCancelled {
return false
}
if state.isStarting {
state.pendingEvents.append(result)
return false
}
return true
}
if shouldSchedule {
scheduler.schedule { self.notify(result) }
}
}
/// Notifies a ValueObservation event.
func notifyChange(_ value: Element) {
guard shouldNotifyValueObservationEvent() else { return }
onChange(value)
}
/// Notifies a ValueObservation event.
func notifyError(_ error: Error) {
guard shouldNotifyValueObservationEvent() else { return }
onError(error)
/// Notifies the events received while the client was starting.
/// The first one is the initial event of the client.
///
/// After this method returns, events are notified as soon as they
/// are received.
func finishStart() {
var isInitialEvent = true
while let result = nextPendingEvent() {
if isInitialEvent {
isInitialEvent = false
scheduler.scheduleInitial { self.notify(result) }
} else {
scheduler.schedule { self.notify(result) }
}
}
}
/// After this method returns, no new notification starts.
@@ -238,32 +279,35 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
stateMutex.withLock { $0.isCancelled = true }
}
/// Returns whether a ValueObservation event should be notified.
private func shouldNotifyValueObservationEvent() -> Bool {
/// Returns the next pending event, or stops the starting phase
/// if there is none.
private func nextPendingEvent() -> Result<Element, Error>? {
stateMutex.withLock { state in
if state.isCancelled { return false }
// After a ValueObservation event, we must ignore the
// initial result.
state.shouldDiscardInitialResult = true
return true
if state.pendingEvents.isEmpty {
state.isStarting = false
return nil
}
return state.pendingEvents.removeFirst()
}
}
/// Returns whether the initial result should be notified: the client
/// is not cancelled, and the initial result should not be discarded.
private func shouldNotifyInitialResult() -> Bool {
stateMutex.withLock { state in
!state.isCancelled && !state.shouldDiscardInitialResult
private func notify(_ result: Result<Element, Error>) {
if stateMutex.withLock({ $0.isCancelled }) { return }
switch result {
case let .failure(error):
onError(error)
case let .success(value):
onChange(value)
}
}
}
fileprivate init(
scheduling scheduler: some ValueObservationScheduler,
scheduling: IsolatedValueObservationScheduling,
extent: SharedValueObservationExtent,
startObservation: @escaping ValueObservationStart<Element>)
{
self.scheduler = scheduler
self.scheduling = scheduling
self.extent = extent
self.startObservation = startObservation
self.clients = []
@@ -288,32 +332,77 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
/// }
/// ```
///
/// The `onError` and `onChange` closures are called on the actor
/// that starts the observation (`isolation`). The first value is
/// notified immediately, before this method returns, if the shared
/// observation was created with the
/// ``IsolatedValueObservationScheduling/immediate`` scheduling.
///
/// This method must be called from an actor. In synchronous code that
/// runs on the main thread, start the observation from the main actor
/// with `MainActor.assumeIsolated`. Elsewhere, consider iterating
/// ``values(bufferingPolicy:)``.
///
/// - parameter isolation: The actor that starts the observation.
/// - parameter onError: The closure to execute when the observation fails.
/// - parameter onChange: The closure to execute on receipt of a
/// fresh value.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency public func start(
public func start(
isolation: isolated any Actor = #isolation,
onError: @escaping (Error) -> Void,
onChange: @escaping (Element) -> Void)
-> AnyDatabaseCancellable
{
let scheduler = ActorValueObservationScheduler(
scheduling: scheduling,
isolation: isolation)
// Safe because the scheduler calls the closures on the actor.
nonisolated(unsafe) let onError = onError
nonisolated(unsafe) let onChange = onChange
return start(
scheduler: scheduler,
onError: { error in onError(error) },
onChange: { value in onChange(value) })
}
/// Starts observing the database, and notifies events with
/// the provided scheduler.
func start(
scheduler: some ValueObservationScheduler,
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Element) -> Void)
-> AnyDatabaseCancellable
{
let client = Client(onError: onError, onChange: onChange)
let (newSubscription, lastResult) = lock.withLock {
let client = Client(scheduler: scheduler, onError: onError, onChange: onChange)
let newSubscription: ValueObservationSubscription? = condition.withLock {
// An immediate initial value requires the result of the initial
// fetch. When the upstream observation is being started by
// another thread, wait for this result.
//
// The upstream observation is never being started by the
// current thread, because clients are not notified until the
// upstream observation has started.
while scheduling.immediateInitialValue
&& currentSubscription != nil
&& lastResult == nil
{
condition.wait()
}
// State change
clients.append(client)
// Support for reentrancy: a shared immediate observation is
// started from the first value notification of that same shared
// immediate observation. Yeah, users are nasty.
// In this case, self.currentSubscription has no cancellable yet,
// because we are still waiting for the upstream ValueObservation
// to start. But we must not start another one.
if currentSubscription != nil {
return (ValueObservationSubscription?.none, self.lastResult)
// Notify the last result as the initial event, if any.
if let lastResult {
client.receive(lastResult)
}
return nil
}
let newSubscription = ValueObservationSubscription()
currentSubscription = newSubscription
return (newSubscription, nil)
return newSubscription
}
// Side effect
@@ -335,7 +424,9 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
// The upstream observation may have been stopped, and maybe
// replaced, while it was starting (for example, if the initial
// fetch fails). In this case, discard its cancellable.
let discardedCancellable: AnyDatabaseCancellable? = lock.withLock {
let discardedCancellable: AnyDatabaseCancellable? = condition.withLock {
// Wake up clients that wait for the initial result.
defer { condition.broadcast() }
guard currentSubscription === newSubscription else {
return cancellable
}
@@ -343,15 +434,10 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
return nil
}
discardedCancellable?.cancel()
} else if let lastResult {
// Notify last result as an initial value. A fresher result may
// have been scheduled before, and already delivered to the
// client: in this case, the last result is not notified.
scheduler.scheduleInitial {
client.notifyInitial(lastResult)
}
}
client.finishStart()
return AnyDatabaseCancellable {
// Retain shared observation (self) until client cancels
self.handleCancel(client)
@@ -376,15 +462,22 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
/// print("fresh players: \(players)")
/// }
/// ```
///
/// The publisher notifies values on the main dispatch queue. The first
/// value is notified immediately, on subscription, if the shared
/// observation was created with the
/// ``IsolatedValueObservationScheduling/immediate`` scheduling.
public func publisher() -> DatabasePublishers.Value<Element> {
DatabasePublishers.Value { onError, onChange in
self.start(onError: onError, onChange: onChange)
let scheduler = MainQueueValueObservationScheduler(
immediate: scheduling.immediateInitialValue)
return DatabasePublishers.Value { onError, onChange in
self.start(scheduler: scheduler, onError: onError, onChange: onChange)
}
}
#endif
private func handleError(_ error: Error, from source: ValueObservationSubscription) {
let (notifiedClients, stoppedCancellable) = lock.withLock {
let (notifiedClients, stoppedCancellable) = condition.withLock {
guard source === currentSubscription else {
return ([Client](), AnyDatabaseCancellable?.none)
}
@@ -405,12 +498,12 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
// Side effects
stoppedCancellable?.cancel()
for client in notifiedClients {
client.notifyError(error)
client.receive(.failure(error))
}
}
private func handleChange(_ value: Element, from source: ValueObservationSubscription) {
let notifiedClients = lock.withLock {
let notifiedClients = condition.withLock {
guard source === currentSubscription else {
return [Client]()
}
@@ -422,7 +515,7 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
// Side effect
for client in notifiedClients {
client.notifyChange(value)
client.receive(.success(value))
}
}
@@ -431,7 +524,7 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
// is currently in progress.
client.cancel()
let stoppedCancellable = lock.withLock {
let stoppedCancellable = condition.withLock {
// State change
clients.removeFirst(where: { $0 === client })
if clients.isEmpty && extent == .whileObserved {
@@ -475,7 +568,12 @@ extension SharedValueObservation {
-> AsyncValueObservation<Element>
{
AsyncValueObservation(bufferingPolicy: bufferingPolicy) { onError, onChange in
self.start(onError: onError, onChange: onChange)
// The callbacks only feed an AsyncThrowingStream: perform
// them directly, without any extra thread hop.
self.start(
scheduler: DirectValueObservationScheduler(),
onError: onError,
onChange: onChange)
}
}
}
@@ -90,36 +90,12 @@ extension ValueObservation: Refinable {
// MARK: - Starting Observation
/// Starts observing the database.
/// Starts observing the database, and notifies fresh values
/// according to the scheduler.
///
/// The observation lasts until the returned cancellable is cancelled
/// or deallocated.
///
/// For example:
///
/// ```swift
/// let observation = ValueObservation.tracking { db in
/// try Player.fetchAll(db)
/// }
///
/// let cancellable = observation.start(
/// in: dbQueue,
/// scheduling: .async(onQueue: .main))
/// { error in
/// // handle error
/// } onChange: { (players: [Player]) in
/// print("Fresh players: \(players)")
/// }
/// ```
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A ValueObservationScheduler.
/// - parameter onError: The closure to execute when the
/// observation fails.
/// - parameter onChange: The closure to execute on receipt of a
/// fresh value.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency public func start(
func start(
in reader: any DatabaseReader,
scheduling scheduler: some ValueObservationScheduler,
onError: @escaping @Sendable (Error) -> Void,
@@ -138,7 +114,7 @@ extension ValueObservation: Refinable {
}
/// Starts observing the database and notifies fresh values on the
/// main actor.
/// actor that starts the observation.
///
/// The observation lasts until the returned cancellable is cancelled
/// or deallocated.
@@ -146,23 +122,37 @@ extension ValueObservation: Refinable {
/// For example:
///
/// ```swift
/// let observation = ValueObservation.tracking { db in
/// try Player.fetchAll(db)
/// }
/// @MainActor final class PlayerModel {
/// var players: [Player] = []
/// private var cancellable: AnyDatabaseCancellable?
///
/// let cancellable = observation.start(in: dbQueue) { error in
/// // handle error
/// } onChange: { (players: [Player]) in
/// print("Fresh players: \(players)")
/// func observePlayers(in reader: any DatabaseReader) {
/// let observation = ValueObservation.tracking { db in
/// try Player.fetchAll(db)
/// }
///
/// cancellable = observation.start(in: reader) { error in
/// // handle error
/// } onChange: { [unowned self] players in
/// self.players = players
/// }
/// }
/// }
/// ```
///
/// By default, fresh values are dispatched asynchronously on the
/// main actor. Pass `.immediate` if the first value should be notified
/// immediately when the observation starts:
/// The `onError` and `onChange` closures are called in order, on the
/// actor that starts the observation, so they can access the state of
/// this actor. They do not need to be `Sendable`.
///
/// By default, fresh values are notified asynchronously. Pass
/// `.immediate` if the first value should be notified immediately,
/// before this method returns:
///
/// ```swift
/// let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
/// let cancellable = observation.start(
/// in: dbQueue,
/// scheduling: .immediate)
/// { error in
/// // handle error
/// } onChange: { (players: [Player]) in
/// print("Fresh players: \(players)")
@@ -170,37 +160,45 @@ extension ValueObservation: Refinable {
/// // <- here "Fresh players" is already printed.
/// ```
///
/// This method must be called from an actor. Synchronous nonisolated
/// code that runs on the main thread can call it from
/// `MainActor.assumeIsolated`. Other nonisolated code can iterate the
/// asynchronous sequence returned by
/// ``values(in:bufferingPolicy:)``.
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A ValueObservationMainActorScheduler.
/// By default, fresh values are dispatched asynchronously on the
/// main actor.
/// - parameter scheduling: Determines when fresh values are notified.
/// By default, they are notified asynchronously.
/// - parameter isolation: The actor on which `onError` and `onChange`
/// are called. By default, it is the caller's actor.
/// - parameter onError: The closure to execute when the
/// observation fails.
/// - parameter onChange: The closure to execute on receipt of a
/// fresh value.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency @MainActor public func start(
public func start(
in reader: any DatabaseReader,
scheduling scheduler: some ValueObservationMainActorScheduler = .mainActor,
onError: @escaping @MainActor (Error) -> Void,
onChange: @escaping @MainActor (Reducer.Value) -> Void)
scheduling: IsolatedValueObservationScheduling = .async,
isolation: isolated any Actor = #isolation,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
where Reducer: ValueReducer
{
let regularScheduler: some ValueObservationScheduler = scheduler
let scheduler = ActorValueObservationScheduler(
scheduling: scheduling,
isolation: isolation)
// The callbacks are only called from the actor: either
// synchronously, from this method (immediate scheduling), or
// from the actions of the scheduler.
nonisolated(unsafe) let onError = onError
nonisolated(unsafe) let onChange = onChange
return start(
in: reader,
scheduling: regularScheduler,
onError: { error in
MainActor.assumeIsolated {
onError(error)
}
},
onChange: { value in
MainActor.assumeIsolated {
onChange(value)
}
})
scheduling: scheduler,
onError: { error in onError(error) },
onChange: { value in onChange(value) })
}
// MARK: - Debugging
@@ -343,21 +341,35 @@ extension ValueObservation {
/// ```
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A ValueObservationScheduler. By default,
/// fresh values are dispatched on the cooperative thread pool.
/// - parameter bufferingPolicy: see the documentation
/// of `AsyncThrowingStream`.
public func values(
in reader: any DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .task,
bufferingPolicy: AsyncValueObservation<Reducer.Value>.BufferingPolicy = .unbounded)
-> AsyncValueObservation<Reducer.Value>
where Reducer: ValueReducer
{
AsyncValueObservation(bufferingPolicy: bufferingPolicy) { onError, onChange in
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
// The callbacks only feed an AsyncThrowingStream: perform
// them directly, without any extra thread hop.
self.start(
in: reader,
scheduling: DirectValueObservationScheduler(),
onError: onError,
onChange: onChange)
}
}
@available(*, unavailable, message: "Remove the scheduling argument.")
public func values(
in reader: any DatabaseReader,
scheduling scheduler: some ValueObservationScheduler,
bufferingPolicy: AsyncValueObservation<Reducer.Value>.BufferingPolicy = .unbounded)
-> AsyncValueObservation<Reducer.Value>
where Reducer: ValueReducer
{
fatalError("unavailable")
}
}
/// An asynchronous sequence of values observed by a ``ValueObservation``.
@@ -472,7 +484,7 @@ extension ValueObservation {
/// main dispatch queue. You can change this behavior by providing a
/// scheduler.
///
/// For example, the ``ValueObservationMainActorScheduler/immediate``
/// For example, the ``ValueObservationScheduler/immediate``
/// scheduler notifies all values on the main dispatch queue, and
/// notifies the first one immediately when the observation starts. The
/// `immediate` scheduling requires that the observation starts from the
@@ -3,6 +3,12 @@ import Foundation
/// A type that determines when `ValueObservation` notifies its fresh values.
///
/// Schedulers are used by
/// ``ValueObservation/publisher(in:scheduling:)``. The
/// ``ValueObservation/start(in:scheduling:isolation:onError:onChange:)``
/// and ``ValueObservation/shared(in:scheduling:extent:)`` methods accept
/// an ``IsolatedValueObservationScheduling`` instead.
///
/// ## Topics
///
/// ### Built-In Schedulers
@@ -13,11 +19,11 @@ import Foundation
/// - ``task``
/// - ``task(priority:)``
/// - ``AsyncValueObservationScheduler``
/// - ``ImmediateValueObservationScheduler``
/// - ``TaskValueObservationScheduler``
public protocol ValueObservationScheduler: Sendable {
/// Returns whether the initial value should be immediately notified.
///
/// If the result is true, then this method was called on the main thread.
/// Returns whether the initial value should be immediately notified,
/// synchronously, when the observation starts.
func immediateInitialValue() -> Bool
func schedule(_ action: @escaping @Sendable () -> Void)
@@ -33,26 +39,148 @@ extension ValueObservationScheduler {
}
}
// MARK: - ValueObservationMainActorScheduler
// MARK: - IsolatedValueObservationScheduling
/// A type that determines when `ValueObservation` notifies its fresh
/// values, on the main actor.
/// A value that determines when a `ValueObservation` notifies its fresh
/// values, on the actor that starts the observation.
///
/// See ``ValueObservation/start(in:scheduling:isolation:onError:onChange:)``
/// and ``ValueObservation/shared(in:scheduling:extent:)``.
///
/// ## Topics
///
/// ### Built-In Schedulers
/// ### Built-In Scheduling
///
/// - ``async``
/// - ``immediate``
/// - ``ValueObservationScheduler/mainActor``
/// - ``ImmediateValueObservationScheduler``
/// - ``DelayedMainActorValueObservationScheduler``
public protocol ValueObservationMainActorScheduler: ValueObservationScheduler {
func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void)
public struct IsolatedValueObservationScheduling: Sendable {
var immediateInitialValue: Bool
/// All values are asynchronously notified on the actor that starts
/// the observation.
public static var async: Self {
IsolatedValueObservationScheduling(immediateInitialValue: false)
}
/// All values are notified on the actor that starts the observation.
/// The first value is immediately notified when the observation starts.
///
/// The actor is blocked until the first value is fetched: use this
/// scheduling for fast database requests only.
public static var immediate: Self {
IsolatedValueObservationScheduling(immediateInitialValue: true)
}
/// All values are asynchronously notified on the actor that starts
/// the observation.
@available(*, deprecated, renamed: "async")
public static var mainActor: Self { .async }
}
extension ValueObservationMainActorScheduler {
public func schedule(_ action: @escaping @Sendable () -> Void) {
scheduleOnMainActor(action)
// MARK: - ActorValueObservationScheduler
/// A scheduler that notifies values on an actor.
///
/// It must be created from the actor, because the initial value is
/// notified synchronously, from the caller of `ValueObservation.start`,
/// when `immediateInitialValue` is true.
final class ActorValueObservationScheduler: ValueObservationScheduler {
typealias Action = @Sendable () -> Void
private enum Target {
case mainQueue
case task(AsyncStream<Action>.Continuation)
}
private let immediate: Bool
private let target: Target
init(
scheduling: IsolatedValueObservationScheduling,
isolation: isolated any Actor)
{
self.immediate = scheduling.immediateInitialValue
if isolation === MainActor.shared {
// Fast path
self.target = .mainQueue
} else {
// A single task executes all actions, in order, on the actor.
let (stream, continuation) = AsyncStream.makeStream(of: Action.self)
Task {
await Self.perform(stream, isolation: isolation)
}
self.target = .task(continuation)
}
}
deinit {
if case let .task(continuation) = target {
continuation.finish()
}
}
private static func perform(
_ actions: AsyncStream<Action>,
isolation: isolated any Actor
) async {
for await action in actions {
action()
}
}
func immediateInitialValue() -> Bool {
immediate
}
func schedule(_ action: @escaping @Sendable () -> Void) {
switch target {
case .mainQueue:
DispatchQueue.main.async(execute: action)
case let .task(continuation):
continuation.yield(action)
}
}
}
// MARK: - DirectValueObservationScheduler
/// A scheduler that performs actions on the thread that schedules them.
///
/// Actions are performed in the order of the `schedule(_:)` calls,
/// because observers schedule notifications from a serial
/// dispatch queue.
///
/// This scheduler is only suitable for actions that are thread-safe and
/// do not block, such as feeding an `AsyncThrowingStream`, or dispatching
/// values to the clients of a `SharedValueObservation`. It avoids a
/// thread hop between the observer and the consumer of values.
struct DirectValueObservationScheduler: ValueObservationScheduler {
/// Whether the initial value is fetched and notified synchronously,
/// on the thread that starts the observation.
var immediate = false
func immediateInitialValue() -> Bool { immediate }
func schedule(_ action: @escaping @Sendable () -> Void) {
action()
}
}
// MARK: - MainQueueValueObservationScheduler
/// A scheduler that notifies values on the main dispatch queue.
///
/// Unlike `ImmediateValueObservationScheduler`, it can notify the initial
/// value synchronously from any thread.
struct MainQueueValueObservationScheduler: ValueObservationScheduler {
/// Whether the initial value is notified synchronously, on the thread
/// that starts the observation.
var immediate: Bool
func immediateInitialValue() -> Bool { immediate }
func schedule(_ action: @escaping @Sendable () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
@@ -84,13 +212,13 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
/// try Player.fetchAll(db)
/// }
///
/// let cancellable = observation.start(
/// in: dbQueue,
/// scheduling: .async(onQueue: .main),
/// onError: { error in ... },
/// onChange: { (players: [Player]) in
/// let cancellable = observation
/// .publisher(in: dbQueue, scheduling: .async(onQueue: .main))
/// .sink { completion in
/// // handle completion
/// } receiveValue: { (players: [Player]) in
/// print("fresh players: \(players)")
/// })
/// }
/// ```
///
/// - warning: Make sure you provide a serial queue, because a
@@ -99,6 +227,14 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
public static func async(onQueue queue: DispatchQueue) -> AsyncValueObservationScheduler {
AsyncValueObservationScheduler(queue: queue)
}
/// A scheduler that asynchronously notifies fresh values on the
/// main dispatch queue.
///
/// It is equivalent to `.async(onQueue: .main)`.
public static var mainActor: AsyncValueObservationScheduler {
AsyncValueObservationScheduler(queue: .main)
}
}
// MARK: - ImmediateValueObservationScheduler
@@ -106,7 +242,7 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
/// A scheduler that notifies all values on the main actor. The
/// first value is immediately notified when the `ValueObservation`
/// is started.
public struct ImmediateValueObservationScheduler: ValueObservationMainActorScheduler {
public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
public init() { }
public func immediateInitialValue() -> Bool {
@@ -116,7 +252,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationMainActorSched
return true
}
public func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
@@ -133,47 +269,18 @@ extension ValueObservationScheduler where Self == ImmediateValueObservationSched
/// try Player.fetchAll(db)
/// }
///
/// let cancellable = observation.start(
/// in: dbQueue,
/// scheduling: .immediate,
/// onError: { error in ... },
/// onChange: { (players: [Player]) in
/// let cancellable = observation
/// .publisher(in: dbQueue, scheduling: .immediate)
/// .sink { completion in
/// // handle completion
/// } receiveValue: { (players: [Player]) in
/// print("fresh players: \(players)")
/// })
/// }
/// // <- here "fresh players" is already printed.
/// ```
///
/// - important: this scheduler requires that the observation is started
/// from the main actor. A fatal error is raised otherwise.
public static var immediate: ImmediateValueObservationScheduler {
ImmediateValueObservationScheduler()
}
}
extension ValueObservationMainActorScheduler where Self == ImmediateValueObservationScheduler {
/// A scheduler that notifies all values on the main actor. The
/// first value is immediately notified when the `ValueObservation`
/// is started.
///
/// For example:
///
/// ```swift
/// let observation = ValueObservation.tracking { db in
/// try Player.fetchAll(db)
/// }
///
/// let cancellable = observation.start(
/// in: dbQueue,
/// scheduling: .immediate,
/// onError: { error in ... },
/// onChange: { (players: [Player]) in
/// print("fresh players: \(players)")
/// })
/// // <- here "fresh players" is already printed.
/// ```
///
/// - important: this scheduler requires that the observation is started
/// from the main actor. A fatal error is raised otherwise.
/// from the main thread. A fatal error is raised otherwise.
public static var immediate: ImmediateValueObservationScheduler {
ImmediateValueObservationScheduler()
}
@@ -223,23 +330,3 @@ extension ValueObservationScheduler where Self == TaskValueObservationScheduler
TaskValueObservationScheduler(priority: priority)
}
}
// MARK: - DelayedMainActorValueObservationScheduler
/// A scheduler that notifies all values on the cooperative thread pool.
public final class DelayedMainActorValueObservationScheduler: ValueObservationMainActorScheduler {
public func immediateInitialValue() -> Bool {
false
}
public func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
extension ValueObservationScheduler where Self == DelayedMainActorValueObservationScheduler {
/// A scheduler that notifies all values on the main actor.
public static var mainActor: DelayedMainActorValueObservationScheduler {
DelayedMainActorValueObservationScheduler()
}
}
@@ -15,7 +15,7 @@ import SQLite3
import XCTest
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
import GRDBTestSupportC
#endif
class DatabasePoolTests: GRDBTestCase {
@@ -2,4 +2,4 @@
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#include "../GRDBTestSupport/include/getThreadsCount.h"
#include "../GRDBTestSupportC/include/getThreadsCount.h"
@@ -0,0 +1,307 @@
import XCTest
import GRDB
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
/// A non-Sendable recorder of observed values.
private final class ValueRecorder {
var values: [Int] = []
var errors: [any Error] = []
}
private struct TestError: Error { }
private let insertCount = 50
private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
private func createTable(_ writer: any DatabaseWriter) throws {
try writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Crashes if the current task is not isolated to the given actor.
private func assertIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
private func assertOrderedValues(_ values: [Int], file: StaticString = #filePath, line: UInt = #line) {
XCTAssertEqual(values.last, insertCount, file: file, line: line)
XCTAssertEqual(values, values.sorted(), "Values are not notified in order", file: file, line: line)
}
private actor ObservingActor {
let recorder = ValueRecorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
var errors: [any Error] { recorder.errors }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
assertIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
let cancellable = observation.start { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Returns the errors notified when the observation starts.
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
let cancellable = observation.start { error in
assertIsolation(self)
self.recorder.errors.append(error)
} onChange: { _ in
XCTFail("Unexpected value")
}
cancellable.cancel()
return recorder.errors
}
}
class SharedValueObservationIsolationTests: GRDBTestCase {
private func writers() throws -> [any DatabaseWriter] {
let writers: [any DatabaseWriter] = try [makeDatabaseQueue(), makeDatabasePool()]
for writer in writers {
try createTable(writer)
}
return writers
}
// MARK: - Main Actor
@MainActor
func testMainActorAsyncScheduling() async throws {
for writer in try writers() {
let observation = countObservation.shared(in: writer)
let recorder = ValueRecorder()
var cancellable: AnyDatabaseCancellable?
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
assertIsolation(MainActor.shared)
recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
// Asynchronous scheduling: no value yet.
XCTAssertTrue(recorder.values.isEmpty)
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable?.cancel()
assertOrderedValues(recorder.values)
}
}
@MainActor
func testMainActorImmediateScheduling() throws {
for writer in try writers() {
let observation = countObservation.shared(in: writer, scheduling: .immediate)
// The first client starts the shared observation.
let recorder1 = ValueRecorder()
let cancellable1 = observation.start { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(MainActor.shared)
recorder1.values.append(count)
}
// Immediate scheduling: the initial value is notified.
XCTAssertEqual(recorder1.values, [0])
// The second client shares the observation.
let recorder2 = ValueRecorder()
let cancellable2 = observation.start { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(MainActor.shared)
recorder2.values.append(count)
}
// Immediate scheduling: the initial value is notified.
XCTAssertEqual(recorder2.values, [0])
cancellable1.cancel()
cancellable2.cancel()
}
}
@MainActor
func testMainActorImmediateError() throws {
for writer in try writers() {
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let recorder = ValueRecorder()
let cancellable = observation.start { error in
assertIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
XCTFail("Unexpected value")
}
// Immediate scheduling: the error is notified.
XCTAssertEqual(recorder.errors.count, 1)
XCTAssertTrue(recorder.errors.first is TestError)
cancellable.cancel()
}
}
// Synchronous nonisolated code that runs on the main thread starts
// observations from the main actor.
func testNonisolatedCodeOnMainThread() throws {
XCTAssertTrue(Thread.isMainThread)
for writer in try writers() {
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let values = MainActor.assumeIsolated {
let recorder = ValueRecorder()
let cancellable = observation.start { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(MainActor.shared)
recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
XCTAssertEqual(values, [0])
}
}
// MARK: - Actor
func testActorAsyncScheduling() async throws {
for writer in try writers() {
let observation = countObservation.shared(in: writer)
let model = ObservingActor()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
let values = await model.values
assertOrderedValues(values)
}
}
func testActorImmediateScheduling() async throws {
for writer in try writers() {
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let model = ObservingActor()
let values = await model.valuesNotifiedOnStart(observation)
XCTAssertEqual(values, [0])
}
}
func testActorImmediateError() async throws {
for writer in try writers() {
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let model = ObservingActor()
let errors = await model.errorsNotifiedOnStart(observation)
XCTAssertEqual(errors.count, 1)
XCTAssertTrue(errors.first is TestError)
}
}
// MARK: - Distinct Actors
// Clients on distinct actors share a single observation. Each one is
// notified on its own actor.
func testDistinctActors() async throws {
for scheduling in [IsolatedValueObservationScheduling.async, .immediate] {
for writer in try writers() {
try await writer.write { try $0.execute(sql: "DELETE FROM t") }
let observation = countObservation.shared(in: writer, scheduling: scheduling)
let model1 = ObservingActor()
let model2 = ObservingActor()
async let observing1: Void = model1.observe(observation)
async let observing2: Void = model2.observe(observation)
try await performInsertions(writer)
_ = try await (observing1, observing2)
let values1 = await model1.values
let values2 = await model2.values
assertOrderedValues(values1)
assertOrderedValues(values2)
}
}
}
// Clients that start an immediate shared observation concurrently,
// from distinct actors, are all notified of the initial value.
func testConcurrentImmediateScheduling() async throws {
for writer in try writers() {
let observation = countObservation.shared(
in: writer,
scheduling: .immediate,
extent: .observationLifetime)
let valuesList = await withTaskGroup(of: [Int].self) { group in
for _ in 0..<20 {
group.addTask {
await ObservingActor().valuesNotifiedOnStart(observation)
}
}
var valuesList: [[Int]] = []
for await values in group {
valuesList.append(values)
}
return valuesList
}
XCTAssertEqual(valuesList.count, 20)
for values in valuesList {
XCTAssertEqual(values, [0])
}
}
}
}
@@ -1,7 +1,7 @@
import XCTest
import GRDB
@testable import GRDB // @testable ONLY for start(scheduler:onError:onChange:)
class SharedValueObservationTests: GRDBTestCase {
@MainActor class SharedValueObservationTests: GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testInitFromAnyDatabaseReader(reader: any DatabaseReader) {
@@ -262,7 +262,7 @@ class SharedValueObservationTests: GRDBTestCase {
.print(to: log)
.shared(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
extent: .observationLifetime)
XCTAssertEqual(log.flush(), [])
@@ -356,7 +356,7 @@ class SharedValueObservationTests: GRDBTestCase {
.print(to: log)
.shared(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
extent: .observationLifetime)
XCTAssertEqual(log.flush(), [])
@@ -437,7 +437,7 @@ class SharedValueObservationTests: GRDBTestCase {
.print(to: log)
.shared(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
extent: .whileObserved)
XCTAssertEqual(log.flush(), [])
@@ -531,7 +531,6 @@ class SharedValueObservationTests: GRDBTestCase {
.print(to: log)
.shared(
in: dbQueue,
scheduling: .task,
extent: .observationLifetime)
XCTAssertEqual(log.flush(), [])
@@ -543,6 +542,7 @@ class SharedValueObservationTests: GRDBTestCase {
exp1.expectedFulfillmentCount = 2
exp1.assertForOverFulfill = false
let cancellable1 = sharedObservation!.start(
scheduler: .task,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values1Mutex.withLock { $0.append(value) }
@@ -562,6 +562,7 @@ class SharedValueObservationTests: GRDBTestCase {
exp2.expectedFulfillmentCount = 2
exp2.assertForOverFulfill = false
let cancellable2 = sharedObservation!.start(
scheduler: .task,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values2Mutex.withLock { $0.append(value) }
@@ -584,6 +585,7 @@ class SharedValueObservationTests: GRDBTestCase {
exp3.expectedFulfillmentCount = 2
exp3.assertForOverFulfill = false
let cancellable3 = sharedObservation!.start(
scheduler: .task,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values3Mutex.withLock { $0.append(value) }
@@ -611,41 +613,6 @@ class SharedValueObservationTests: GRDBTestCase {
XCTAssertEqual(log.flush(), ["cancel"])
}
#if canImport(Combine)
func test_task_publisher() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
let publisher = ValueObservation
.tracking(Table("player").fetchCount)
.shared(in: dbQueue, scheduling: .task)
.publisher()
do {
let recorder = publisher.record()
try XCTAssert(recorder.availableElements.get().isEmpty)
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 0)
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
}
do {
let recorder = publisher.record()
// Don't assert that no element is available yet: the shared
// observation notifies its last value from the `.task`
// scheduler, which can deliver it before the assertion runs.
// try XCTAssert(recorder.availableElements.get().isEmpty) <- WRONG
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2)
}
}
#endif
func test_task_whileObserved() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
@@ -660,7 +627,6 @@ class SharedValueObservationTests: GRDBTestCase {
.print(to: log)
.shared(
in: dbQueue,
scheduling: .task,
extent: .whileObserved)
XCTAssertEqual(log.flush(), [])
@@ -672,6 +638,7 @@ class SharedValueObservationTests: GRDBTestCase {
exp1.expectedFulfillmentCount = 2
exp1.assertForOverFulfill = false
let cancellable1 = sharedObservation!.start(
scheduler: .task,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values1Mutex.withLock { $0.append(value) }
@@ -691,6 +658,7 @@ class SharedValueObservationTests: GRDBTestCase {
exp2.expectedFulfillmentCount = 2
exp2.assertForOverFulfill = false
let cancellable2 = sharedObservation!.start(
scheduler: .task,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values2Mutex.withLock { $0.append(value) }
@@ -713,6 +681,7 @@ class SharedValueObservationTests: GRDBTestCase {
exp3.expectedFulfillmentCount = 2
exp3.assertForOverFulfill = false
let cancellable3 = sharedObservation!.start(
scheduler: .task,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values3Mutex.withLock { $0.append(value) }
@@ -867,24 +836,6 @@ class SharedValueObservationTests: GRDBTestCase {
}
}
func testAsyncAwait_task() async throws {
let dbQueue = try makeDatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
let values = ValueObservation
.tracking(Table("player").fetchCount)
.shared(in: dbQueue, scheduling: .task)
.values()
for try await value in values {
XCTAssertEqual(value, 0)
break
}
}
// Regression test: a client can be cancelled from another thread while
// the shared observation is notifying a fresh value.
@@ -907,13 +858,13 @@ class SharedValueObservationTests: GRDBTestCase {
.tracking(Table("player").fetchCount)
.shared(
in: dbQueue,
scheduling: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
extent: .observationLifetime)
let cancellableMutex: Mutex<AnyDatabaseCancellable?> = Mutex(nil)
let cancellationDidCompleteMutex: Mutex<Bool?> = Mutex(nil)
let exp = expectation(description: "")
let cancellable = sharedObservation.start(
scheduler: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
guard value == 1 else { return }
@@ -950,7 +901,6 @@ class SharedValueObservationTests: GRDBTestCase {
}
.shared(
in: dbQueue,
scheduling: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
extent: .observationLifetime)
let cancellableMutex: Mutex<AnyDatabaseCancellable?> = Mutex(nil)
@@ -958,6 +908,7 @@ class SharedValueObservationTests: GRDBTestCase {
let initialValueExp = expectation(description: "initial value")
let errorExp = expectation(description: "error")
let cancellable = sharedObservation.start(
scheduler: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
onError: { _ in
cancellationDidCompleteMutex.store(
Self.cancelFromOtherThreadAndWait(cancellableMutex.load()))
@@ -990,7 +941,6 @@ class SharedValueObservationTests: GRDBTestCase {
.tracking(Table("player").fetchCount)
.shared(
in: dbQueue,
scheduling: .async(onQueue: queue),
extent: .observationLifetime)
let initialValuesExp = expectation(description: "initial values")
@@ -1001,6 +951,7 @@ class SharedValueObservationTests: GRDBTestCase {
// Client 1 blocks the notification of the second value until
// client 2 is cancelled.
let cancellable1 = sharedObservation.start(
scheduler: .async(onQueue: queue),
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
if value == 0 {
@@ -1013,6 +964,7 @@ class SharedValueObservationTests: GRDBTestCase {
let values2Mutex: Mutex<[Int]> = Mutex([])
let cancellable2 = sharedObservation.start(
scheduler: .async(onQueue: queue),
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values2Mutex.withLock { $0.append(value) }
@@ -1053,7 +1005,6 @@ class SharedValueObservationTests: GRDBTestCase {
}
.shared(
in: dbQueue,
scheduling: .async(onQueue: queue),
extent: .observationLifetime)
let initialValuesExp = expectation(description: "initial values")
@@ -1064,6 +1015,7 @@ class SharedValueObservationTests: GRDBTestCase {
// Client 1 blocks the notification of the error until
// client 2 is cancelled.
let cancellable1 = sharedObservation.start(
scheduler: .async(onQueue: queue),
onError: { _ in
notificationDidStartSemaphore.signal()
_ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5)
@@ -1074,6 +1026,7 @@ class SharedValueObservationTests: GRDBTestCase {
let error2Mutex: Mutex<Error?> = Mutex(nil)
let cancellable2 = sharedObservation.start(
scheduler: .async(onQueue: queue),
onError: { error in
error2Mutex.store(error)
},
@@ -1108,11 +1061,11 @@ class SharedValueObservationTests: GRDBTestCase {
.tracking(Table("player").fetchCount)
.shared(
in: dbQueue,
scheduling: .async(onQueue: queue),
extent: .observationLifetime)
let initialValueExp = expectation(description: "initial value")
let cancellable1 = sharedObservation.start(
scheduler: .async(onQueue: queue),
onError: { XCTFail("Unexpected error \($0)") },
onChange: { _ in initialValueExp.fulfill() })
wait(for: [initialValueExp], timeout: 5)
@@ -1125,6 +1078,7 @@ class SharedValueObservationTests: GRDBTestCase {
let values2Mutex: Mutex<[Int]> = Mutex([])
let cancellable2 = sharedObservation.start(
scheduler: .async(onQueue: queue),
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
values2Mutex.withLock { $0.append(value) }
@@ -1205,12 +1159,12 @@ class SharedValueObservationTests: GRDBTestCase {
.tracking(Table("player").fetchCount)
.shared(
in: dbQueue,
scheduling: scheduler,
extent: .observationLifetime)
// Client 1 makes 0 the last value.
let values1Mutex: Mutex<[Int]> = Mutex([])
let cancellable1 = sharedObservation.start(
scheduler: scheduler,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in values1Mutex.withLock { $0.append(value) } })
XCTAssertTrue(scheduler.waitForScheduledActions(count: 1))
@@ -1225,6 +1179,7 @@ class SharedValueObservationTests: GRDBTestCase {
// value, after the fresh value 1.
let values2Mutex: Mutex<[Int]> = Mutex([])
let cancellable2 = sharedObservation.start(
scheduler: scheduler,
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in values2Mutex.withLock { $0.append(value) } })
XCTAssertTrue(scheduler.waitForScheduledActions(count: 2))
@@ -1241,7 +1196,7 @@ class SharedValueObservationTests: GRDBTestCase {
/// Waiting for the other thread models a notification callback that
/// waits for a resource held by a thread that is cancelling the client.
/// A timeout reveals a deadlock, without hanging the test suite.
private static func cancelFromOtherThreadAndWait(_ cancellable: AnyDatabaseCancellable?) -> Bool {
nonisolated private static func cancelFromOtherThreadAndWait(_ cancellable: AnyDatabaseCancellable?) -> Bool {
let semaphore = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
cancellable?.cancel()
@@ -0,0 +1,251 @@
import XCTest
import GRDB
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
/// A non-Sendable recorder of observed values.
private final class ValueRecorder {
var values: [Int] = []
var errors: [any Error] = []
}
private struct TestError: Error { }
private let insertCount = 50
private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
private func createTable(_ writer: any DatabaseWriter) throws {
try writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Crashes if the current task is not isolated to the given actor.
private func assertIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
private func assertOrderedValues(_ values: [Int], file: StaticString = #filePath, line: UInt = #line) {
XCTAssertEqual(values.last, insertCount, file: file, line: line)
XCTAssertEqual(values, values.sorted(), "Values are not notified in order", file: file, line: line)
}
private actor ObservingActor {
let recorder = ValueRecorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
var errors: [any Error] { recorder.errors }
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
assertIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Returns the errors notified when the observation starts.
func errorsNotifiedOnStart(_ writer: any DatabaseWriter) -> [any Error] {
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
assertIsolation(self)
self.recorder.errors.append(error)
} onChange: { _ in
XCTFail("Unexpected value")
}
cancellable.cancel()
return recorder.errors
}
}
class ValueObservationIsolationTests: GRDBTestCase {
private func writers() throws -> [any DatabaseWriter] {
let writers: [any DatabaseWriter] = try [makeDatabaseQueue(), makeDatabasePool()]
for writer in writers {
try createTable(writer)
}
return writers
}
// MARK: - Main Actor
@MainActor
func testMainActorAsyncScheduling() async throws {
for writer in try writers() {
let recorder = ValueRecorder()
var cancellable: AnyDatabaseCancellable?
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
assertIsolation(MainActor.shared)
recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
// Asynchronous scheduling: no value yet.
XCTAssertTrue(recorder.values.isEmpty)
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable?.cancel()
assertOrderedValues(recorder.values)
}
}
@MainActor
func testMainActorImmediateScheduling() throws {
for writer in try writers() {
let recorder = ValueRecorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(MainActor.shared)
recorder.values.append(count)
}
// Immediate scheduling: the initial value is notified.
XCTAssertEqual(recorder.values, [0])
cancellable.cancel()
}
}
@MainActor
func testMainActorImmediateError() throws {
for writer in try writers() {
let recorder = ValueRecorder()
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
assertIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
XCTFail("Unexpected value")
}
// Immediate scheduling: the error is notified.
XCTAssertEqual(recorder.errors.count, 1)
XCTAssertTrue(recorder.errors.first is TestError)
cancellable.cancel()
}
}
// Synchronous nonisolated code that runs on the main thread starts
// observations from the main actor.
func testNonisolatedCodeOnMainThread() throws {
XCTAssertTrue(Thread.isMainThread)
for writer in try writers() {
let values = MainActor.assumeIsolated {
let recorder = ValueRecorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
XCTFail("Unexpected error: \(error)")
} onChange: { count in
assertIsolation(MainActor.shared)
recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
XCTAssertEqual(values, [0])
}
}
// MARK: - Actor
func testActorAsyncScheduling() async throws {
for writer in try writers() {
let model = ObservingActor()
try await model.observe(writer, scheduling: .async)
let values = await model.values
assertOrderedValues(values)
}
}
func testActorImmediateScheduling() async throws {
for writer in try writers() {
let model = ObservingActor()
let values = await model.valuesNotifiedOnStart(writer)
XCTAssertEqual(values, [0])
}
}
func testActorImmediateSchedulingThenChanges() async throws {
for writer in try writers() {
let model = ObservingActor()
try await model.observe(writer, scheduling: .immediate)
let values = await model.values
XCTAssertEqual(values.first, 0)
assertOrderedValues(values)
}
}
func testActorImmediateError() async throws {
for writer in try writers() {
let model = ObservingActor()
let errors = await model.errorsNotifiedOnStart(writer)
XCTAssertEqual(errors.count, 1)
XCTAssertTrue(errors.first is TestError)
}
}
}
@@ -1,8 +1,8 @@
import XCTest
import Dispatch
@testable import GRDB
import GRDB
class ValueObservationPrintTests: GRDBTestCase {
@MainActor class ValueObservationPrintTests: GRDBTestCase {
class TestStream: TextOutputStream {
private var stringsMutex: Mutex<[String]> = Mutex([])
var strings: [String] { stringsMutex.load() }
@@ -38,7 +38,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbReader,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
@@ -113,7 +113,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbReader,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in expectation.fulfill() },
onChange: { _ in })
withExtendedLifetime(cancellable) {
@@ -192,7 +192,7 @@ class ValueObservationPrintTests: GRDBTestCase {
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbWriter,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in
try! dbWriter.write { db in
@@ -270,7 +270,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbWriter,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in expectation.fulfill() },
onChange: { _ in })
withExtendedLifetime(cancellable) {
@@ -329,7 +329,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbWriter,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in expectation.fulfill() },
onChange: { _ in
try! dbWriter.write { db in
@@ -436,7 +436,7 @@ class ValueObservationPrintTests: GRDBTestCase {
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
@@ -534,7 +534,7 @@ class ValueObservationPrintTests: GRDBTestCase {
expectation.expectedFulfillmentCount = 3
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in
try! dbQueue.write { db in
@@ -581,7 +581,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
@@ -617,7 +617,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
@@ -646,7 +646,7 @@ class ValueObservationPrintTests: GRDBTestCase {
expectation.expectedFulfillmentCount = 2
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in
try! dbQueue.write { db in
@@ -668,7 +668,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in expectation.fulfill() },
onChange: { _ in
try! dbQueue.write { db in
@@ -692,7 +692,7 @@ class ValueObservationPrintTests: GRDBTestCase {
let expectation = self.expectation(description: "")
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { _ in },
onChange: { _ in
expectation.fulfill()
@@ -1,7 +1,7 @@
import XCTest
@testable import GRDB
@testable import GRDB // @testable ONLY for recordingSelection
class ValueObservationRegionRecordingTests: GRDBTestCase {
@MainActor class ValueObservationRegionRecordingTests: GRDBTestCase {
func testRecordingSelectedRegion() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
@@ -200,7 +200,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
let observer = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
resultsMutex.withLock { $0.append(count) }
@@ -1,8 +1,8 @@
import XCTest
import Dispatch
@testable import GRDB
@testable import GRDB // @testable ONLY for ValueObservation(trackingMode:makeReducer:)
class ValueObservationTests: GRDBTestCase {
@MainActor class ValueObservationTests: GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testStartFromAnyDatabaseReader(reader: any DatabaseReader) {
@@ -377,7 +377,7 @@ class ValueObservationTests: GRDBTestCase {
let observedCountsMutex: Mutex<[Int]> = Mutex([])
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCountsMutex.withLock { $0.append(count) }
@@ -475,7 +475,7 @@ class ValueObservationTests: GRDBTestCase {
let observedCountsMutex: Mutex<[Int]> = Mutex([])
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
scheduling: .async,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCountsMutex.withLock { $0.append(count) }
@@ -1055,7 +1055,10 @@ class ValueObservationTests: GRDBTestCase {
let observationCount = 100
dbConfiguration.maximumReaderCount = 5
func test(_ writer: some DatabaseWriter, scheduling scheduler: some ValueObservationScheduler) throws {
func test(
_ writer: some DatabaseWriter,
scheduling scheduler: IsolatedValueObservationScheduling
) throws {
try writer.write {
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
@@ -1102,9 +1105,9 @@ class ValueObservationTests: GRDBTestCase {
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .immediate) }
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .immediate) }
try Test(test).run { try (DatabaseQueue(), .async(onQueue: .main)) }
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async(onQueue: .main)) }
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async(onQueue: .main)) }
try Test(test).run { try (DatabaseQueue(), .async) }
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async) }
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async) }
}
// An attempt at finding a regression test for <https://github.com/groue/GRDB.swift/issues/1362>
@@ -1113,7 +1116,10 @@ class ValueObservationTests: GRDBTestCase {
let observationCount = 100
dbConfiguration.maximumReaderCount = 5
func test(_ writer: some DatabaseWriter, scheduling scheduler: some ValueObservationScheduler) throws {
func test(
_ writer: some DatabaseWriter,
scheduling scheduler: IsolatedValueObservationScheduling
) throws {
try writer.write {
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
@@ -1163,9 +1169,9 @@ class ValueObservationTests: GRDBTestCase {
}
}
try Test(test).run { try (DatabaseQueue(), .async(onQueue: .main)) }
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async(onQueue: .main)) }
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async(onQueue: .main)) }
try Test(test).run { try (DatabaseQueue(), .async) }
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async) }
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async) }
try Test(test).run { try (DatabaseQueue(), .immediate) }
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .immediate) }
@@ -1,5 +1,10 @@
import Foundation
#if canImport(Combine)
import Combine
#endif
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
private class NonSendable {
@@ -10,80 +15,18 @@ private class NonSendable {
}
}
// MARK: - Database readers and writers
/// The kinds of database readers whose async methods are tested.
enum ReaderKind: CaseIterable {
case queue
case pool
case snapshot
case snapshotPool
}
/// The kinds of database writers whose async methods are tested.
enum WriterKind: CaseIterable {
case queue
case pool
}
private func withTemporaryDirectory(
_ body: (URL) async throws -> Void
) async throws {
let directoryURL = URL.temporaryDirectory
.appending(path: "GRDBNonSendableTests-\(UUID().uuidString)", directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directoryURL) }
try await body(directoryURL)
}
private func withDatabaseReader(
_ kind: ReaderKind,
_ body: (any DatabaseReader) async throws -> Void
) async throws {
switch kind {
case .queue:
try await body(DatabaseQueue())
case .pool, .snapshot, .snapshotPool:
try await withTemporaryDirectory { directoryURL in
let dbPool = try DatabasePool(path: directoryURL.appending(path: "db.sqlite").path)
switch kind {
case .pool:
try await body(dbPool)
case .snapshot:
try await body(dbPool.makeSnapshot())
case .snapshotPool:
try await body(dbPool.makeSnapshotPool())
case .queue:
fatalError()
}
}
}
}
private func withDatabaseWriter(
_ kind: WriterKind,
_ body: (any DatabaseWriter) async throws -> Void
) async throws {
switch kind {
case .queue:
try await body(DatabaseQueue())
case .pool:
try await withTemporaryDirectory { directoryURL in
try await body(DatabasePool(path: directoryURL.appending(path: "db.sqlite").path))
}
}
}
// MARK: - Non-Sendable inputs
@Suite struct NonSendableInputTests {
@Test func non_sendable_type_in_synchronous_database_access() throws {
let dbQueue = try DatabaseQueue()
let input = NonSendable(value: 0)
let output = try dbQueue.read { _ in
input
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_in_synchronous_database_access(kind: ReaderKind) throws {
try withDatabaseReader(kind) { reader in
let input = NonSendable(value: 0)
let output = try reader.read { _ in
input
}
#expect(input === output)
}
#expect(input === output)
}
@Test(arguments: ReaderKind.allCases)
@@ -211,3 +154,193 @@ private func withDatabaseWriter(
}
}
}
// MARK: - Non-Sendable callbacks
@Suite struct NonSendableCallbackTests {
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_sent_to_databaseReader_asyncRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { reader in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
reader.asyncRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_sent_to_databaseReader_asyncUnsafeRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { reader in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
reader.asyncUnsafeRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncBarrierWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
writer.asyncBarrierWriteWithoutTransaction { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = await withCheckedContinuation { continuation in
let nonSendable = NonSendable(value: 0)
writer.asyncWriteWithoutTransaction { _ in
continuation.resume(returning: nonSendable.value)
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncWrite(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
let input = NonSendable(value: 0)
let output = NonSendable(value: 0)
writer.asyncWrite { _ in
NonSendable(value: input.value + 1)
} completion: { _, result in
continuation.resume(with: result.map { nonSendable in
output.value = nonSendable.value + 1
return output.value
})
}
}
#expect(value == 2)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_spawnConcurrentRead(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
writer.asyncWriteWithoutTransaction { _ in
let nonSendable = NonSendable(value: 0)
writer.spawnConcurrentRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_database_afterNextTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
writer.asyncWriteWithoutTransaction { db in
let nonSendable = NonSendable(value: 0)
db.afterNextTransaction { _ in
nonSendable.value += 1
continuation.resume(returning: nonSendable.value)
}
do {
try db.inTransaction {
try db.execute(sql: "CREATE TABLE t(a)")
return .commit
}
} catch {
continuation.resume(throwing: error)
}
}
}
#expect(value == 1)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseRegionObservation_start(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(a)")
}
var cancellable: AnyDatabaseCancellable?
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
cancellable = observation.start(in: writer) { error in
continuation.resume(throwing: error)
} onChange: { _ in
nonSendable.value += 1
continuation.resume(returning: nonSendable.value)
}
writer.asyncWriteWithoutTransaction { db in
try? db.execute(sql: "INSERT INTO t VALUES (1)")
}
}
cancellable?.cancel()
#expect(value == 1)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseMigrator_asyncMigrate(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let migrator = DatabaseMigrator()
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
migrator.asyncMigrate(writer) { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
#if canImport(Combine)
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_writePublisher_updates(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let nonSendable = NonSendable(value: 0)
let publisher = writer.writePublisher { _ in
nonSendable.value += 1
return nonSendable.value
} thenRead: { _, value in
value + 1
}
var values: [Int] = []
for try await value in publisher.values {
values.append(value)
}
#expect(values == [2])
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_returned_from_databaseWriter_writePublisher_updates(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let publisher = writer.writePublisher { _ in
NonSendable(value: 1)
} thenRead: { _, nonSendable in
nonSendable.value += 1
return nonSendable.value
}
var values: [Int] = []
for try await value in publisher.values {
values.append(value)
}
#expect(values == [2])
}
}
#endif
}
@@ -0,0 +1,406 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
//
// The callbacks of the tested observations are not Sendable: they mutate
// non-Sendable values and actor-isolated state.
//
// This file is identical in all Swift 6 test targets. Declarations are
// explicitly isolated, or explicitly nonisolated, so that they do not
// depend on the default isolation of the test target.
/// A non-Sendable recorder of observed values.
nonisolated private final class Recorder {
var values: [Int] = []
var errors: [any Error] = []
}
nonisolated private struct TestError: Error { }
nonisolated private let insertCount = 50
/// Creates the observed table.
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
/// Performs `insertCount` distinct insertions.
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Observes the number of rows in the `t` table.
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
/// An observation that always fails.
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
/// Crashes if the current task is not isolated to the given actor.
nonisolated private func expectIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
/// Expects observed values to be ordered, and to end with `insertCount`.
nonisolated private func expectOrderedValues(_ values: [Int]) {
#expect(values.first != nil)
#expect(values.last == insertCount)
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
}
// MARK: - Main Actor
@MainActor private final class MainActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
nonisolated init() { }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(MainActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
}
@Suite @MainActor struct MainActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling_is_the_default(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer)
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
pending?.resume()
pending = nil
}
// Asynchronous scheduling: no value yet.
#expect(recorder.values.isEmpty)
}
#expect(recorder.values.first == 0)
#expect(recorder.values.allSatisfy { $0 == 0 })
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = MainActorModel()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
// The first client starts the shared observation.
let recorder1 = Recorder()
let cancellable1 = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder1.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder1.values == [0])
// The second client shares the observation.
let recorder2 = Recorder()
let cancellable2 = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder2.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder2.values == [0])
cancellable1.cancel()
cancellable2.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) throws {
try withDatabaseWriter(kind) { writer in
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let recorder = Recorder()
let cancellable = observation.start { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
// Immediate scheduling: the error is notified.
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable.cancel()
}
}
}
// MARK: - Actor
private actor Model {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
let cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Returns the errors notified when the observation starts.
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
let cancellable = observation.start { error in
expectIsolation(self)
self.recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
cancellable.cancel()
return recorder.errors
}
}
@Suite struct ActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = Model()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
await expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let model = Model()
let values = await model.valuesNotifiedOnStart(observation)
#expect(values == [0])
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let model = Model()
let errors = await model.errorsNotifiedOnStart(observation)
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
// Clients that start an immediate shared observation concurrently,
// from distinct actors, are all notified of the initial value.
@Test(arguments: WriterKind.allCases)
func concurrent_immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(
in: writer,
scheduling: .immediate,
extent: .observationLifetime)
let valuesList = await withTaskGroup(of: [Int].self) { group in
for _ in 0..<20 {
group.addTask {
await Model().valuesNotifiedOnStart(observation)
}
}
var valuesList: [[Int]] = []
for await values in group {
valuesList.append(values)
}
return valuesList
}
#expect(valuesList.count == 20)
for values in valuesList {
#expect(values == [0])
}
}
}
}
// MARK: - Global Actor
@globalActor actor SharedValueObservationTestGlobalActor {
static let shared = SharedValueObservationTestGlobalActor()
}
@SharedValueObservationTestGlobalActor private final class GlobalActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
nonisolated init() { }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(SharedValueObservationTestGlobalActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
}
@Suite @SharedValueObservationTestGlobalActor struct GlobalActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = GlobalActorModel()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let recorder = Recorder()
let cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(SharedValueObservationTestGlobalActor.shared)
recorder.values.append(count)
}
#expect(recorder.values == [0])
cancellable.cancel()
}
}
}
// MARK: - Distinct Actors
// Clients on distinct actors share a single observation. Each one is
// notified on its own actor.
@Suite nonisolated struct DistinctActorsSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases, [
IsolatedValueObservationScheduling.async,
IsolatedValueObservationScheduling.immediate,
])
func clients_on_distinct_actors(
kind: WriterKind,
scheduling: IsolatedValueObservationScheduling
) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: scheduling)
let mainActorModel = MainActorModel()
let actorModel = Model()
let globalActorModel = GlobalActorModel()
async let observing1: Void = mainActorModel.observe(observation)
async let observing2: Void = actorModel.observe(observation)
async let observing3: Void = globalActorModel.observe(observation)
try await performInsertions(writer)
_ = try await (observing1, observing2, observing3)
await expectOrderedValues(mainActorModel.values)
await expectOrderedValues(actorModel.values)
await expectOrderedValues(globalActorModel.values)
}
}
}
@@ -0,0 +1,142 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for the shorthand notation in asynchronous database accesses,
// such as `try await reader.read(Player.fetchCount)`.
//
// In the Swift 6 language mode, the compiler would silently select a
// synchronous database access if the shorthand notation were not supported
// by an asynchronous database access. To make sure the asynchronous access
// is selected, tests check that a cancelled task throws `CancellationError`.
// Synchronous database accesses ignore task cancellation.
nonisolated private struct Player: TableRecord {
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
}
/// Runs `operation` in a cancelled task, and expects a `CancellationError`.
private func expectCancellationError(
_ operation: @escaping @Sendable () async throws -> Void
) async {
let task = Task {
withUnsafeCurrentTask { $0?.cancel() }
try await operation()
}
await #expect(throws: CancellationError.self) {
try await task.value
}
}
/// Reads from a generic database reader.
private func fetchCount(_ reader: some DatabaseReader) async throws -> Int {
try await reader.read(Player.fetchCount)
}
// MARK: - Tests
@Suite struct ShorthandNotationTests {
@Test(arguments: ReaderKind.allCases)
func databaseReader_read(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write(Player.createTable)
} test: { reader in
let count = try await reader.read(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await reader.read(Player.fetchCount)
}
}
}
@Test(arguments: ReaderKind.allCases)
func databaseReader_unsafeRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write(Player.createTable)
} test: { reader in
let count = try await reader.unsafeRead(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await reader.unsafeRead(Player.fetchCount)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_write(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let deletedCount = try await writer.write(Player.deleteAll)
#expect(deletedCount == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.write(Player.deleteAll)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_writeWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let count = try await writer.writeWithoutTransaction(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.writeWithoutTransaction(Player.fetchCount)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_barrierWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let count = try await writer.barrierWriteWithoutTransaction(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.barrierWriteWithoutTransaction(Player.fetchCount)
}
}
}
@Test func concrete_and_generic_database_accesses() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
let count1 = try await dbQueue.read(Player.fetchCount)
let count2 = try await fetchCount(dbQueue)
#expect(count1 == 0)
#expect(count2 == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await dbQueue.read(Player.fetchCount)
}
await expectCancellationError {
_ = try await fetchCount(dbQueue)
}
}
}
@@ -0,0 +1,398 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
//
// The callbacks of the tested observations are not Sendable: they mutate
// non-Sendable values and actor-isolated state.
//
// This file is identical in all Swift 6 test targets. Declarations are
// explicitly isolated, or explicitly nonisolated, so that they do not
// depend on the default isolation of the test target.
/// A non-Sendable recorder of observed values.
nonisolated private final class Recorder {
var values: [Int] = []
var errors: [any Error] = []
}
nonisolated private struct TestError: Error { }
nonisolated private let insertCount = 50
/// Creates the observed table.
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
/// Performs `insertCount` distinct insertions.
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Observes the number of rows in the `t` table.
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
/// An observation that always fails.
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
/// Crashes if the current task is not isolated to the given actor.
nonisolated private func expectIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
/// Expects observed values to be ordered, and to end with `insertCount`.
nonisolated private func expectOrderedValues(_ values: [Int]) {
#expect(values.first != nil)
#expect(values.last == insertCount)
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
}
// MARK: - Main Actor
@MainActor private final class MainActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(MainActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
}
@Suite @MainActor struct MainActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling_is_the_default(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
pending?.resume()
pending = nil
}
// Asynchronous scheduling: no value yet.
#expect(recorder.values.isEmpty)
}
#expect(recorder.values.first == 0)
#expect(recorder.values.allSatisfy { $0 == 0 })
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = MainActorModel()
try await model.observe(writer, scheduling: .async)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder.values == [0])
cancellable.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = MainActorModel()
try await model.observe(writer, scheduling: .immediate)
#expect(model.recorder.values.first == 0)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func async_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { continuation in
cancellable = failingObservation.start(in: writer) { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
continuation.resume()
} onChange: { _ in
Issue.record("Unexpected value")
}
// Asynchronous scheduling: no error yet.
#expect(recorder.errors.isEmpty)
}
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) throws {
try withDatabaseWriter(kind) { writer in
let recorder = Recorder()
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
// Immediate scheduling: the error is notified.
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable.cancel()
}
}
}
// MARK: - Actor
private actor Model {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
var errors: [any Error] { recorder.errors }
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Observes until an error is notified.
func observeError(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async {
await withCheckedContinuation { continuation in
cancellable = failingObservation.start(in: writer, scheduling: scheduling) { error in
expectIsolation(self)
self.recorder.errors.append(error)
continuation.resume()
} onChange: { _ in
Issue.record("Unexpected value")
}
}
cancellable = nil
}
}
@Suite struct ActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
try await model.observe(writer, scheduling: .async)
await expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
let values = await model.valuesNotifiedOnStart(writer)
#expect(values == [0])
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
try await model.observe(writer, scheduling: .immediate)
let values = await model.values
#expect(values.first == 0)
expectOrderedValues(values)
}
}
@Test(arguments: WriterKind.allCases)
func async_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let model = Model()
await model.observeError(writer, scheduling: .async)
let errors = await model.errors
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let model = Model()
await model.observeError(writer, scheduling: .immediate)
let errors = await model.errors
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
}
// MARK: - Global Actor
@globalActor actor ValueObservationTestGlobalActor {
static let shared = ValueObservationTestGlobalActor()
}
@ValueObservationTestGlobalActor private final class GlobalActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(ValueObservationTestGlobalActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
}
@Suite @ValueObservationTestGlobalActor struct GlobalActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = GlobalActorModel()
try await model.observe(writer, scheduling: .async)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(ValueObservationTestGlobalActor.shared)
recorder.values.append(count)
}
#expect(recorder.values == [0])
cancellable.cancel()
}
}
}
@@ -1,5 +1,10 @@
import Foundation
#if canImport(Combine)
import Combine
#endif
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
nonisolated private class NonSendable {
@@ -9,81 +14,18 @@ nonisolated private class NonSendable {
self.value = value
}
}
// MARK: - Database readers and writers
/// The kinds of database readers whose async methods are tested.
nonisolated enum ReaderKind: CaseIterable {
case queue
case pool
case snapshot
case snapshotPool
}
/// The kinds of database writers whose async methods are tested.
nonisolated enum WriterKind: CaseIterable {
case queue
case pool
}
private func withTemporaryDirectory(
_ body: (URL) async throws -> Void
) async throws {
let directoryURL = URL.temporaryDirectory
.appending(path: "GRDBNonSendableTests-\(UUID().uuidString)", directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directoryURL) }
try await body(directoryURL)
}
private func withDatabaseReader(
_ kind: ReaderKind,
_ body: (any DatabaseReader) async throws -> Void
) async throws {
switch kind {
case .queue:
try await body(DatabaseQueue())
case .pool, .snapshot, .snapshotPool:
try await withTemporaryDirectory { directoryURL in
let dbPool = try DatabasePool(path: directoryURL.appending(path: "db.sqlite").path)
switch kind {
case .pool:
try await body(dbPool)
case .snapshot:
try await body(dbPool.makeSnapshot())
case .snapshotPool:
try await body(dbPool.makeSnapshotPool())
case .queue:
fatalError()
}
}
}
}
private func withDatabaseWriter(
_ kind: WriterKind,
_ body: (any DatabaseWriter) async throws -> Void
) async throws {
switch kind {
case .queue:
try await body(DatabaseQueue())
case .pool:
try await withTemporaryDirectory { directoryURL in
try await body(DatabasePool(path: directoryURL.appending(path: "db.sqlite").path))
}
}
}
// MARK: - Non-Sendable inputs
@Suite struct NonSendableInputTests {
@Test func non_sendable_type_in_synchronous_database_access() throws {
let dbQueue = try DatabaseQueue()
let input = NonSendable(value: 0)
let output = try dbQueue.read { _ in
input
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_in_synchronous_database_access(kind: ReaderKind) throws {
try withDatabaseReader(kind) { reader in
let input = NonSendable(value: 0)
let output = try reader.read { _ in
input
}
#expect(input === output)
}
#expect(input === output)
}
@Test(arguments: ReaderKind.allCases)
@@ -211,3 +153,193 @@ private func withDatabaseWriter(
}
}
}
// MARK: - Non-Sendable callbacks
@Suite struct NonSendableCallbackTests {
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_sent_to_databaseReader_asyncRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { reader in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
reader.asyncRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_sent_to_databaseReader_asyncUnsafeRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { reader in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
reader.asyncUnsafeRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncBarrierWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
writer.asyncBarrierWriteWithoutTransaction { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = await withCheckedContinuation { continuation in
let nonSendable = NonSendable(value: 0)
writer.asyncWriteWithoutTransaction { _ in
continuation.resume(returning: nonSendable.value)
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncWrite(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
let input = NonSendable(value: 0)
let output = NonSendable(value: 0)
writer.asyncWrite { _ in
NonSendable(value: input.value + 1)
} completion: { _, result in
continuation.resume(with: result.map { nonSendable in
output.value = nonSendable.value + 1
return output.value
})
}
}
#expect(value == 2)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_spawnConcurrentRead(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
writer.asyncWriteWithoutTransaction { _ in
let nonSendable = NonSendable(value: 0)
writer.spawnConcurrentRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_database_afterNextTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
writer.asyncWriteWithoutTransaction { db in
let nonSendable = NonSendable(value: 0)
db.afterNextTransaction { _ in
nonSendable.value += 1
continuation.resume(returning: nonSendable.value)
}
do {
try db.inTransaction {
try db.execute(sql: "CREATE TABLE t(a)")
return .commit
}
} catch {
continuation.resume(throwing: error)
}
}
}
#expect(value == 1)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseRegionObservation_start(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(a)")
}
var cancellable: AnyDatabaseCancellable?
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
cancellable = observation.start(in: writer) { error in
continuation.resume(throwing: error)
} onChange: { _ in
nonSendable.value += 1
continuation.resume(returning: nonSendable.value)
}
writer.asyncWriteWithoutTransaction { db in
try? db.execute(sql: "INSERT INTO t VALUES (1)")
}
}
cancellable?.cancel()
#expect(value == 1)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseMigrator_asyncMigrate(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let migrator = DatabaseMigrator()
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
migrator.asyncMigrate(writer) { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
#if canImport(Combine)
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_writePublisher_updates(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let nonSendable = NonSendable(value: 0)
let publisher = writer.writePublisher { _ in
nonSendable.value += 1
return nonSendable.value
} thenRead: { _, value in
value + 1
}
var values: [Int] = []
for try await value in publisher.values {
values.append(value)
}
#expect(values == [2])
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_returned_from_databaseWriter_writePublisher_updates(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let publisher = writer.writePublisher { _ in
NonSendable(value: 1)
} thenRead: { _, nonSendable in
nonSendable.value += 1
return nonSendable.value
}
var values: [Int] = []
for try await value in publisher.values {
values.append(value)
}
#expect(values == [2])
}
}
#endif
}
@@ -0,0 +1,406 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
//
// The callbacks of the tested observations are not Sendable: they mutate
// non-Sendable values and actor-isolated state.
//
// This file is identical in all Swift 6 test targets. Declarations are
// explicitly isolated, or explicitly nonisolated, so that they do not
// depend on the default isolation of the test target.
/// A non-Sendable recorder of observed values.
nonisolated private final class Recorder {
var values: [Int] = []
var errors: [any Error] = []
}
nonisolated private struct TestError: Error { }
nonisolated private let insertCount = 50
/// Creates the observed table.
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
/// Performs `insertCount` distinct insertions.
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Observes the number of rows in the `t` table.
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
/// An observation that always fails.
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
/// Crashes if the current task is not isolated to the given actor.
nonisolated private func expectIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
/// Expects observed values to be ordered, and to end with `insertCount`.
nonisolated private func expectOrderedValues(_ values: [Int]) {
#expect(values.first != nil)
#expect(values.last == insertCount)
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
}
// MARK: - Main Actor
@MainActor private final class MainActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
nonisolated init() { }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(MainActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
}
@Suite @MainActor struct MainActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling_is_the_default(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer)
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
pending?.resume()
pending = nil
}
// Asynchronous scheduling: no value yet.
#expect(recorder.values.isEmpty)
}
#expect(recorder.values.first == 0)
#expect(recorder.values.allSatisfy { $0 == 0 })
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = MainActorModel()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
// The first client starts the shared observation.
let recorder1 = Recorder()
let cancellable1 = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder1.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder1.values == [0])
// The second client shares the observation.
let recorder2 = Recorder()
let cancellable2 = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder2.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder2.values == [0])
cancellable1.cancel()
cancellable2.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) throws {
try withDatabaseWriter(kind) { writer in
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let recorder = Recorder()
let cancellable = observation.start { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
// Immediate scheduling: the error is notified.
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable.cancel()
}
}
}
// MARK: - Actor
private actor Model {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
let cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Returns the errors notified when the observation starts.
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
let cancellable = observation.start { error in
expectIsolation(self)
self.recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
cancellable.cancel()
return recorder.errors
}
}
@Suite struct ActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = Model()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
await expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let model = Model()
let values = await model.valuesNotifiedOnStart(observation)
#expect(values == [0])
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let model = Model()
let errors = await model.errorsNotifiedOnStart(observation)
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
// Clients that start an immediate shared observation concurrently,
// from distinct actors, are all notified of the initial value.
@Test(arguments: WriterKind.allCases)
func concurrent_immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(
in: writer,
scheduling: .immediate,
extent: .observationLifetime)
let valuesList = await withTaskGroup(of: [Int].self) { group in
for _ in 0..<20 {
group.addTask {
await Model().valuesNotifiedOnStart(observation)
}
}
var valuesList: [[Int]] = []
for await values in group {
valuesList.append(values)
}
return valuesList
}
#expect(valuesList.count == 20)
for values in valuesList {
#expect(values == [0])
}
}
}
}
// MARK: - Global Actor
@globalActor actor SharedValueObservationTestGlobalActor {
static let shared = SharedValueObservationTestGlobalActor()
}
@SharedValueObservationTestGlobalActor private final class GlobalActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
nonisolated init() { }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(SharedValueObservationTestGlobalActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
}
@Suite @SharedValueObservationTestGlobalActor struct GlobalActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = GlobalActorModel()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let recorder = Recorder()
let cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(SharedValueObservationTestGlobalActor.shared)
recorder.values.append(count)
}
#expect(recorder.values == [0])
cancellable.cancel()
}
}
}
// MARK: - Distinct Actors
// Clients on distinct actors share a single observation. Each one is
// notified on its own actor.
@Suite nonisolated struct DistinctActorsSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases, [
IsolatedValueObservationScheduling.async,
IsolatedValueObservationScheduling.immediate,
])
func clients_on_distinct_actors(
kind: WriterKind,
scheduling: IsolatedValueObservationScheduling
) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: scheduling)
let mainActorModel = MainActorModel()
let actorModel = Model()
let globalActorModel = GlobalActorModel()
async let observing1: Void = mainActorModel.observe(observation)
async let observing2: Void = actorModel.observe(observation)
async let observing3: Void = globalActorModel.observe(observation)
try await performInsertions(writer)
_ = try await (observing1, observing2, observing3)
await expectOrderedValues(mainActorModel.values)
await expectOrderedValues(actorModel.values)
await expectOrderedValues(globalActorModel.values)
}
}
}
@@ -0,0 +1,142 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for the shorthand notation in asynchronous database accesses,
// such as `try await reader.read(Player.fetchCount)`.
//
// In the Swift 6 language mode, the compiler would silently select a
// synchronous database access if the shorthand notation were not supported
// by an asynchronous database access. To make sure the asynchronous access
// is selected, tests check that a cancelled task throws `CancellationError`.
// Synchronous database accesses ignore task cancellation.
nonisolated private struct Player: TableRecord {
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
}
/// Runs `operation` in a cancelled task, and expects a `CancellationError`.
private func expectCancellationError(
_ operation: @escaping @Sendable () async throws -> Void
) async {
let task = Task {
withUnsafeCurrentTask { $0?.cancel() }
try await operation()
}
await #expect(throws: CancellationError.self) {
try await task.value
}
}
/// Reads from a generic database reader.
private func fetchCount(_ reader: some DatabaseReader) async throws -> Int {
try await reader.read(Player.fetchCount)
}
// MARK: - Tests
@Suite struct ShorthandNotationTests {
@Test(arguments: ReaderKind.allCases)
func databaseReader_read(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write(Player.createTable)
} test: { reader in
let count = try await reader.read(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await reader.read(Player.fetchCount)
}
}
}
@Test(arguments: ReaderKind.allCases)
func databaseReader_unsafeRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write(Player.createTable)
} test: { reader in
let count = try await reader.unsafeRead(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await reader.unsafeRead(Player.fetchCount)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_write(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let deletedCount = try await writer.write(Player.deleteAll)
#expect(deletedCount == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.write(Player.deleteAll)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_writeWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let count = try await writer.writeWithoutTransaction(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.writeWithoutTransaction(Player.fetchCount)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_barrierWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let count = try await writer.barrierWriteWithoutTransaction(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.barrierWriteWithoutTransaction(Player.fetchCount)
}
}
}
@Test func concrete_and_generic_database_accesses() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
let count1 = try await dbQueue.read(Player.fetchCount)
let count2 = try await fetchCount(dbQueue)
#expect(count1 == 0)
#expect(count2 == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await dbQueue.read(Player.fetchCount)
}
await expectCancellationError {
_ = try await fetchCount(dbQueue)
}
}
}
@@ -0,0 +1,398 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
//
// The callbacks of the tested observations are not Sendable: they mutate
// non-Sendable values and actor-isolated state.
//
// This file is identical in all Swift 6 test targets. Declarations are
// explicitly isolated, or explicitly nonisolated, so that they do not
// depend on the default isolation of the test target.
/// A non-Sendable recorder of observed values.
nonisolated private final class Recorder {
var values: [Int] = []
var errors: [any Error] = []
}
nonisolated private struct TestError: Error { }
nonisolated private let insertCount = 50
/// Creates the observed table.
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
/// Performs `insertCount` distinct insertions.
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Observes the number of rows in the `t` table.
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
/// An observation that always fails.
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
/// Crashes if the current task is not isolated to the given actor.
nonisolated private func expectIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
/// Expects observed values to be ordered, and to end with `insertCount`.
nonisolated private func expectOrderedValues(_ values: [Int]) {
#expect(values.first != nil)
#expect(values.last == insertCount)
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
}
// MARK: - Main Actor
@MainActor private final class MainActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(MainActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
}
@Suite @MainActor struct MainActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling_is_the_default(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
pending?.resume()
pending = nil
}
// Asynchronous scheduling: no value yet.
#expect(recorder.values.isEmpty)
}
#expect(recorder.values.first == 0)
#expect(recorder.values.allSatisfy { $0 == 0 })
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = MainActorModel()
try await model.observe(writer, scheduling: .async)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder.values == [0])
cancellable.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = MainActorModel()
try await model.observe(writer, scheduling: .immediate)
#expect(model.recorder.values.first == 0)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func async_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { continuation in
cancellable = failingObservation.start(in: writer) { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
continuation.resume()
} onChange: { _ in
Issue.record("Unexpected value")
}
// Asynchronous scheduling: no error yet.
#expect(recorder.errors.isEmpty)
}
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) throws {
try withDatabaseWriter(kind) { writer in
let recorder = Recorder()
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
// Immediate scheduling: the error is notified.
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable.cancel()
}
}
}
// MARK: - Actor
private actor Model {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
var errors: [any Error] { recorder.errors }
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Observes until an error is notified.
func observeError(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async {
await withCheckedContinuation { continuation in
cancellable = failingObservation.start(in: writer, scheduling: scheduling) { error in
expectIsolation(self)
self.recorder.errors.append(error)
continuation.resume()
} onChange: { _ in
Issue.record("Unexpected value")
}
}
cancellable = nil
}
}
@Suite struct ActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
try await model.observe(writer, scheduling: .async)
await expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
let values = await model.valuesNotifiedOnStart(writer)
#expect(values == [0])
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
try await model.observe(writer, scheduling: .immediate)
let values = await model.values
#expect(values.first == 0)
expectOrderedValues(values)
}
}
@Test(arguments: WriterKind.allCases)
func async_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let model = Model()
await model.observeError(writer, scheduling: .async)
let errors = await model.errors
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let model = Model()
await model.observeError(writer, scheduling: .immediate)
let errors = await model.errors
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
}
// MARK: - Global Actor
@globalActor actor ValueObservationTestGlobalActor {
static let shared = ValueObservationTestGlobalActor()
}
@ValueObservationTestGlobalActor private final class GlobalActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(ValueObservationTestGlobalActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
}
@Suite @ValueObservationTestGlobalActor struct GlobalActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = GlobalActorModel()
try await model.observe(writer, scheduling: .async)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(ValueObservationTestGlobalActor.shared)
recorder.values.append(count)
}
#expect(recorder.values == [0])
cancellable.cancel()
}
}
}
@@ -1,5 +1,10 @@
import Foundation
#if canImport(Combine)
import Combine
#endif
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
private class NonSendable {
@@ -10,101 +15,18 @@ private class NonSendable {
}
}
private class NonSendableRecord:
Codable, Identifiable,
FetchableRecord, PersistableRecord
{
var id: Int64
init(id: Int64) {
self.id = id
}
static func createTable(_ db: Database) throws {
try db.create(table: databaseTableName) { t in
t.autoIncrementedPrimaryKey("id")
}
}
}
// MARK: - Database readers and writers
/// The kinds of database readers whose async methods are tested.
enum ReaderKind: CaseIterable {
case queue
case pool
case snapshot
case snapshotPool
}
/// The kinds of database writers whose async methods are tested.
enum WriterKind: CaseIterable {
case queue
case pool
}
private func withTemporaryDirectory(
_ body: (URL) async throws -> Void
) async throws {
let directoryURL = URL.temporaryDirectory
.appending(path: "GRDBNonSendableTests-\(UUID().uuidString)", directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directoryURL) }
try await body(directoryURL)
}
private func withDatabaseReader(
_ kind: ReaderKind,
setup: (any DatabaseWriter) async throws -> Void = { _ in },
test: (any DatabaseReader) async throws -> Void
) async throws {
switch kind {
case .queue:
let dbQueue = try DatabaseQueue()
try await setup(dbQueue)
try await test(dbQueue)
case .pool, .snapshot, .snapshotPool:
try await withTemporaryDirectory { directoryURL in
let dbPool = try DatabasePool(path: directoryURL.appending(path: "db.sqlite").path)
try await setup(dbPool)
switch kind {
case .pool:
try await test(dbPool)
case .snapshot:
try await test(dbPool.makeSnapshot())
case .snapshotPool:
try await test(dbPool.makeSnapshotPool())
case .queue:
fatalError()
}
}
}
}
private func withDatabaseWriter(
_ kind: WriterKind,
_ body: (any DatabaseWriter) async throws -> Void
) async throws {
switch kind {
case .queue:
try await body(DatabaseQueue())
case .pool:
try await withTemporaryDirectory { directoryURL in
try await body(DatabasePool(path: directoryURL.appending(path: "db.sqlite").path))
}
}
}
// MARK: - Non-Sendable inputs
@Suite struct NonSendableInputTests {
@Test func non_sendable_type_in_synchronous_database_access() throws {
let dbQueue = try DatabaseQueue()
let input = NonSendable(value: 0)
let output = try dbQueue.read { _ in
input
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_in_synchronous_database_access(kind: ReaderKind) throws {
try withDatabaseReader(kind) { reader in
let input = NonSendable(value: 0)
let output = try reader.read { _ in
input
}
#expect(input === output)
}
#expect(input === output)
}
@Test(arguments: ReaderKind.allCases)
@@ -233,21 +155,192 @@ private func withDatabaseWriter(
}
}
// MARK: - Non-Sendable record results
// MARK: - Non-Sendable callbacks
@Suite struct NonSendableRecordResultTests {
@Suite struct NonSendableCallbackTests {
@Test(arguments: ReaderKind.allCases)
func non_sendable_record_returned_from_read(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write { db in
try NonSendableRecord.createTable(db)
try NonSendableRecord(id: 1).insert(db)
func non_sendable_type_sent_to_databaseReader_asyncRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { reader in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
reader.asyncRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
} test: { reader in
let record = try await reader.read { db in
try NonSendableRecord.find(db, id: 1)
}
#expect(record.id == 1)
#expect(value == 0)
}
}
@Test(arguments: ReaderKind.allCases)
func non_sendable_type_sent_to_databaseReader_asyncUnsafeRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { reader in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
reader.asyncUnsafeRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncBarrierWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
writer.asyncBarrierWriteWithoutTransaction { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = await withCheckedContinuation { continuation in
let nonSendable = NonSendable(value: 0)
writer.asyncWriteWithoutTransaction { _ in
continuation.resume(returning: nonSendable.value)
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_asyncWrite(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
let input = NonSendable(value: 0)
let output = NonSendable(value: 0)
writer.asyncWrite { _ in
NonSendable(value: input.value + 1)
} completion: { _, result in
continuation.resume(with: result.map { nonSendable in
output.value = nonSendable.value + 1
return output.value
})
}
}
#expect(value == 2)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_spawnConcurrentRead(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
writer.asyncWriteWithoutTransaction { _ in
let nonSendable = NonSendable(value: 0)
writer.spawnConcurrentRead { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
}
#expect(value == 0)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_database_afterNextTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let value = try await withCheckedThrowingContinuation { continuation in
writer.asyncWriteWithoutTransaction { db in
let nonSendable = NonSendable(value: 0)
db.afterNextTransaction { _ in
nonSendable.value += 1
continuation.resume(returning: nonSendable.value)
}
do {
try db.inTransaction {
try db.execute(sql: "CREATE TABLE t(a)")
return .commit
}
} catch {
continuation.resume(throwing: error)
}
}
}
#expect(value == 1)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseRegionObservation_start(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(a)")
}
var cancellable: AnyDatabaseCancellable?
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
cancellable = observation.start(in: writer) { error in
continuation.resume(throwing: error)
} onChange: { _ in
nonSendable.value += 1
continuation.resume(returning: nonSendable.value)
}
writer.asyncWriteWithoutTransaction { db in
try? db.execute(sql: "INSERT INTO t VALUES (1)")
}
}
cancellable?.cancel()
#expect(value == 1)
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseMigrator_asyncMigrate(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let migrator = DatabaseMigrator()
let value = try await withCheckedThrowingContinuation { continuation in
let nonSendable = NonSendable(value: 0)
migrator.asyncMigrate(writer) { dbResult in
continuation.resume(with: dbResult.map { _ in nonSendable.value })
}
}
#expect(value == 0)
}
}
#if canImport(Combine)
@Test(arguments: WriterKind.allCases)
func non_sendable_type_sent_to_databaseWriter_writePublisher_updates(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let nonSendable = NonSendable(value: 0)
let publisher = writer.writePublisher { _ in
nonSendable.value += 1
return nonSendable.value
} thenRead: { _, value in
value + 1
}
var values: [Int] = []
for try await value in publisher.values {
values.append(value)
}
#expect(values == [2])
}
}
@Test(arguments: WriterKind.allCases)
func non_sendable_type_returned_from_databaseWriter_writePublisher_updates(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let publisher = writer.writePublisher { _ in
NonSendable(value: 1)
} thenRead: { _, nonSendable in
nonSendable.value += 1
return nonSendable.value
}
var values: [Int] = []
for try await value in publisher.values {
values.append(value)
}
#expect(values == [2])
}
}
#endif
}
@@ -0,0 +1,406 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
//
// The callbacks of the tested observations are not Sendable: they mutate
// non-Sendable values and actor-isolated state.
//
// This file is identical in all Swift 6 test targets. Declarations are
// explicitly isolated, or explicitly nonisolated, so that they do not
// depend on the default isolation of the test target.
/// A non-Sendable recorder of observed values.
nonisolated private final class Recorder {
var values: [Int] = []
var errors: [any Error] = []
}
nonisolated private struct TestError: Error { }
nonisolated private let insertCount = 50
/// Creates the observed table.
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
/// Performs `insertCount` distinct insertions.
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Observes the number of rows in the `t` table.
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
/// An observation that always fails.
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
/// Crashes if the current task is not isolated to the given actor.
nonisolated private func expectIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
/// Expects observed values to be ordered, and to end with `insertCount`.
nonisolated private func expectOrderedValues(_ values: [Int]) {
#expect(values.first != nil)
#expect(values.last == insertCount)
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
}
// MARK: - Main Actor
@MainActor private final class MainActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
nonisolated init() { }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(MainActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
}
@Suite @MainActor struct MainActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling_is_the_default(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer)
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
pending?.resume()
pending = nil
}
// Asynchronous scheduling: no value yet.
#expect(recorder.values.isEmpty)
}
#expect(recorder.values.first == 0)
#expect(recorder.values.allSatisfy { $0 == 0 })
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = MainActorModel()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
// The first client starts the shared observation.
let recorder1 = Recorder()
let cancellable1 = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder1.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder1.values == [0])
// The second client shares the observation.
let recorder2 = Recorder()
let cancellable2 = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder2.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder2.values == [0])
cancellable1.cancel()
cancellable2.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) throws {
try withDatabaseWriter(kind) { writer in
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let recorder = Recorder()
let cancellable = observation.start { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
// Immediate scheduling: the error is notified.
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable.cancel()
}
}
}
// MARK: - Actor
private actor Model {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
let cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Returns the errors notified when the observation starts.
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
let cancellable = observation.start { error in
expectIsolation(self)
self.recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
cancellable.cancel()
return recorder.errors
}
}
@Suite struct ActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = Model()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
await expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let model = Model()
let values = await model.valuesNotifiedOnStart(observation)
#expect(values == [0])
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
let model = Model()
let errors = await model.errorsNotifiedOnStart(observation)
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
// Clients that start an immediate shared observation concurrently,
// from distinct actors, are all notified of the initial value.
@Test(arguments: WriterKind.allCases)
func concurrent_immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(
in: writer,
scheduling: .immediate,
extent: .observationLifetime)
let valuesList = await withTaskGroup(of: [Int].self) { group in
for _ in 0..<20 {
group.addTask {
await Model().valuesNotifiedOnStart(observation)
}
}
var valuesList: [[Int]] = []
for await values in group {
valuesList.append(values)
}
return valuesList
}
#expect(valuesList.count == 20)
for values in valuesList {
#expect(values == [0])
}
}
}
}
// MARK: - Global Actor
@globalActor actor SharedValueObservationTestGlobalActor {
static let shared = SharedValueObservationTestGlobalActor()
}
@SharedValueObservationTestGlobalActor private final class GlobalActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
nonisolated init() { }
/// Observes until `insertCount` is observed.
func observe(_ observation: SharedValueObservation<Int>) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = observation.start { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(SharedValueObservationTestGlobalActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
}
cancellable = nil
}
}
@Suite @SharedValueObservationTestGlobalActor struct GlobalActorSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .async)
let model = GlobalActorModel()
async let observing: Void = model.observe(observation)
try await performInsertions(writer)
try await observing
expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: .immediate)
let recorder = Recorder()
let cancellable = observation.start { error in
Issue.record(error)
} onChange: { count in
expectIsolation(SharedValueObservationTestGlobalActor.shared)
recorder.values.append(count)
}
#expect(recorder.values == [0])
cancellable.cancel()
}
}
}
// MARK: - Distinct Actors
// Clients on distinct actors share a single observation. Each one is
// notified on its own actor.
@Suite nonisolated struct DistinctActorsSharedValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases, [
IsolatedValueObservationScheduling.async,
IsolatedValueObservationScheduling.immediate,
])
func clients_on_distinct_actors(
kind: WriterKind,
scheduling: IsolatedValueObservationScheduling
) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let observation = countObservation.shared(in: writer, scheduling: scheduling)
let mainActorModel = MainActorModel()
let actorModel = Model()
let globalActorModel = GlobalActorModel()
async let observing1: Void = mainActorModel.observe(observation)
async let observing2: Void = actorModel.observe(observation)
async let observing3: Void = globalActorModel.observe(observation)
try await performInsertions(writer)
_ = try await (observing1, observing2, observing3)
await expectOrderedValues(mainActorModel.values)
await expectOrderedValues(actorModel.values)
await expectOrderedValues(globalActorModel.values)
}
}
}
@@ -0,0 +1,142 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for the shorthand notation in asynchronous database accesses,
// such as `try await reader.read(Player.fetchCount)`.
//
// In the Swift 6 language mode, the compiler would silently select a
// synchronous database access if the shorthand notation were not supported
// by an asynchronous database access. To make sure the asynchronous access
// is selected, tests check that a cancelled task throws `CancellationError`.
// Synchronous database accesses ignore task cancellation.
private struct Player: TableRecord {
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
}
/// Runs `operation` in a cancelled task, and expects a `CancellationError`.
private func expectCancellationError(
_ operation: @escaping @Sendable () async throws -> Void
) async {
let task = Task {
withUnsafeCurrentTask { $0?.cancel() }
try await operation()
}
await #expect(throws: CancellationError.self) {
try await task.value
}
}
/// Reads from a generic database reader.
private func fetchCount(_ reader: some DatabaseReader) async throws -> Int {
try await reader.read(Player.fetchCount)
}
// MARK: - Tests
@Suite struct ShorthandNotationTests {
@Test(arguments: ReaderKind.allCases)
func databaseReader_read(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write(Player.createTable)
} test: { reader in
let count = try await reader.read(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await reader.read(Player.fetchCount)
}
}
}
@Test(arguments: ReaderKind.allCases)
func databaseReader_unsafeRead(kind: ReaderKind) async throws {
try await withDatabaseReader(kind) { writer in
try await writer.write(Player.createTable)
} test: { reader in
let count = try await reader.unsafeRead(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await reader.unsafeRead(Player.fetchCount)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_write(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let deletedCount = try await writer.write(Player.deleteAll)
#expect(deletedCount == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.write(Player.deleteAll)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_writeWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let count = try await writer.writeWithoutTransaction(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.writeWithoutTransaction(Player.fetchCount)
}
}
}
@Test(arguments: WriterKind.allCases)
func databaseWriter_barrierWriteWithoutTransaction(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
try await writer.write(Player.createTable)
} test: { writer in
let count = try await writer.barrierWriteWithoutTransaction(Player.fetchCount)
#expect(count == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await writer.barrierWriteWithoutTransaction(Player.fetchCount)
}
}
}
@Test func concrete_and_generic_database_accesses() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
let count1 = try await dbQueue.read(Player.fetchCount)
let count2 = try await fetchCount(dbQueue)
#expect(count1 == 0)
#expect(count2 == 0)
// If this fails, the synchronous overload is selected by the compiler
await expectCancellationError {
_ = try await dbQueue.read(Player.fetchCount)
}
await expectCancellationError {
_ = try await fetchCount(dbQueue)
}
}
}
@@ -0,0 +1,398 @@
import Foundation
import GRDB
#if SWIFT_PACKAGE
import GRDBTestSupport
#endif
import Testing
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
// which notifies fresh values on the actor that starts the observation.
//
// The callbacks of the tested observations are not Sendable: they mutate
// non-Sendable values and actor-isolated state.
//
// This file is identical in all Swift 6 test targets. Declarations are
// explicitly isolated, or explicitly nonisolated, so that they do not
// depend on the default isolation of the test target.
/// A non-Sendable recorder of observed values.
nonisolated private final class Recorder {
var values: [Int] = []
var errors: [any Error] = []
}
nonisolated private struct TestError: Error { }
nonisolated private let insertCount = 50
/// Creates the observed table.
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
try await writer.write { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
}
}
/// Performs `insertCount` distinct insertions.
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
for _ in 0..<insertCount {
try await writer.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
}
}
/// Observes the number of rows in the `t` table.
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
try Table("t").fetchCount(db)
}
/// An observation that always fails.
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
throw TestError()
}
/// Crashes if the current task is not isolated to the given actor.
nonisolated private func expectIsolation(_ actor: some Actor) {
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
actor.preconditionIsolated()
}
}
/// Expects observed values to be ordered, and to end with `insertCount`.
nonisolated private func expectOrderedValues(_ values: [Int]) {
#expect(values.first != nil)
#expect(values.last == insertCount)
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
}
// MARK: - Main Actor
@MainActor private final class MainActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(MainActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
}
@Suite @MainActor struct MainActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling_is_the_default(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
pending?.resume()
pending = nil
}
// Asynchronous scheduling: no value yet.
#expect(recorder.values.isEmpty)
}
#expect(recorder.values.first == 0)
#expect(recorder.values.allSatisfy { $0 == 0 })
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = MainActorModel()
try await model.observe(writer, scheduling: .async)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(MainActor.shared)
recorder.values.append(count)
}
// Immediate scheduling: the initial value is notified.
#expect(recorder.values == [0])
cancellable.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = MainActorModel()
try await model.observe(writer, scheduling: .immediate)
#expect(model.recorder.values.first == 0)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func async_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
await withCheckedContinuation { continuation in
cancellable = failingObservation.start(in: writer) { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
continuation.resume()
} onChange: { _ in
Issue.record("Unexpected value")
}
// Asynchronous scheduling: no error yet.
#expect(recorder.errors.isEmpty)
}
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable?.cancel()
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) throws {
try withDatabaseWriter(kind) { writer in
let recorder = Recorder()
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
expectIsolation(MainActor.shared)
recorder.errors.append(error)
} onChange: { _ in
Issue.record("Unexpected value")
}
// Immediate scheduling: the error is notified.
#expect(recorder.errors.count == 1)
#expect(recorder.errors.first is TestError)
cancellable.cancel()
}
}
}
// MARK: - Actor
private actor Model {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
var values: [Int] { recorder.values }
var errors: [any Error] { recorder.errors }
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
/// Returns the values notified when the observation starts.
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(self)
self.recorder.values.append(count)
}
cancellable.cancel()
return recorder.values
}
/// Observes until an error is notified.
func observeError(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async {
await withCheckedContinuation { continuation in
cancellable = failingObservation.start(in: writer, scheduling: scheduling) { error in
expectIsolation(self)
self.recorder.errors.append(error)
continuation.resume()
} onChange: { _ in
Issue.record("Unexpected value")
}
}
cancellable = nil
}
}
@Suite struct ActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
try await model.observe(writer, scheduling: .async)
await expectOrderedValues(model.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
let values = await model.valuesNotifiedOnStart(writer)
#expect(values == [0])
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = Model()
try await model.observe(writer, scheduling: .immediate)
let values = await model.values
#expect(values.first == 0)
expectOrderedValues(values)
}
}
@Test(arguments: WriterKind.allCases)
func async_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let model = Model()
await model.observeError(writer, scheduling: .async)
let errors = await model.errors
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_error(kind: WriterKind) async throws {
try await withDatabaseWriter(kind) { writer in
let model = Model()
await model.observeError(writer, scheduling: .immediate)
let errors = await model.errors
#expect(errors.count == 1)
#expect(errors.first is TestError)
}
}
}
// MARK: - Global Actor
@globalActor actor ValueObservationTestGlobalActor {
static let shared = ValueObservationTestGlobalActor()
}
@ValueObservationTestGlobalActor private final class GlobalActorModel {
let recorder = Recorder()
var cancellable: AnyDatabaseCancellable?
/// Observes until `insertCount` is observed.
func observe(
_ writer: any DatabaseWriter,
scheduling: IsolatedValueObservationScheduling
) async throws {
var insertions: Task<Void, any Error>?
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// ValueObservation may notify consecutive identical
// values: resume the continuation only once.
var pending = Optional(continuation)
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
pending?.resume(throwing: error)
pending = nil
} onChange: { count in
expectIsolation(ValueObservationTestGlobalActor.shared)
self.recorder.values.append(count)
if count == insertCount {
pending?.resume()
pending = nil
}
}
insertions = Task {
try await performInsertions(writer)
}
}
try await insertions?.value
cancellable = nil
}
}
@Suite @ValueObservationTestGlobalActor struct GlobalActorValueObservationIsolationTests {
@Test(arguments: WriterKind.allCases)
func async_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let model = GlobalActorModel()
try await model.observe(writer, scheduling: .async)
expectOrderedValues(model.recorder.values)
}
}
@Test(arguments: WriterKind.allCases)
func immediate_scheduling(kind: WriterKind) async throws {
try await withDatabaseWriter(kind, setup: createTable) { writer in
let recorder = Recorder()
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
Issue.record(error)
} onChange: { count in
expectIsolation(ValueObservationTestGlobalActor.shared)
recorder.values.append(count)
}
#expect(recorder.values == [0])
cancellable.cancel()
}
}
}
+152
View File
@@ -0,0 +1,152 @@
// This file is compiled with the GRDBTestSupport target of the GRDB Swift
// package, but also with test targets of Xcode projects. Because those
// Xcode test targets may have varying settings regarding default isolation
// and approachable concurrency, we declare explicitly methods as
// `nonisolated` and closure arguments as `nonisolated(nonsending)`.
import Foundation
import GRDB
/// The kinds of database readers available for tests
nonisolated public enum ReaderKind: CaseIterable, Sendable {
case queue
case pool
case snapshot
case snapshotPool
}
/// The kinds of database writers available for tests
nonisolated public enum WriterKind: CaseIterable, Sendable {
case queue
case pool
}
nonisolated public func withTemporaryDirectory(
_ body: (URL) throws -> Void
) throws {
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("GRDBTestSupport-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directoryURL) }
try body(directoryURL)
}
nonisolated(nonsending) public func withTemporaryDirectory(
_ body: nonisolated(nonsending) (URL) async throws -> Void
) async throws {
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("GRDBTestSupport-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directoryURL) }
try await body(directoryURL)
}
nonisolated public func withDatabaseWriter(
_ kind: WriterKind,
setup: (any DatabaseWriter) throws -> Void = { _ in },
test: (any DatabaseWriter) throws -> Void
) throws {
try withTemporaryDirectory { directoryURL in
let dbWriter: any DatabaseWriter = switch kind {
case .queue: try makeDatabaseQueue(in: directoryURL)
case .pool: try makeDatabasePool(in: directoryURL)
}
try setup(dbWriter)
try test(dbWriter)
}
}
nonisolated(nonsending) public func withDatabaseWriter(
_ kind: WriterKind,
setup: nonisolated(nonsending) (any DatabaseWriter) async throws -> Void = { _ in },
test: nonisolated(nonsending) (any DatabaseWriter) async throws -> Void
) async throws {
try await withTemporaryDirectory { directoryURL in
let dbWriter: any DatabaseWriter = switch kind {
case .queue: try makeDatabaseQueue(in: directoryURL)
case .pool: try makeDatabasePool(in: directoryURL)
}
try await setup(dbWriter)
try await test(dbWriter)
}
}
nonisolated public func withDatabaseReader(
_ kind: ReaderKind,
setup: (any DatabaseWriter) throws -> Void = { _ in },
test: (any DatabaseReader) throws -> Void
) throws {
try withTemporaryDirectory { directoryURL in
switch kind {
case .queue:
let dbQueue = try makeDatabaseQueue(in: directoryURL)
try setup(dbQueue)
try test(dbQueue)
case .pool:
let dbPool = try makeDatabasePool(in: directoryURL)
try setup(dbPool)
try test(dbPool)
case .snapshot:
let dbPool = try makeDatabasePool(in: directoryURL)
try setup(dbPool)
try test(dbPool.makeSnapshot())
case .snapshotPool:
let dbPool = try makeDatabasePool(in: directoryURL)
try setup(dbPool)
try test(dbPool.makeSnapshotPool())
}
}
}
nonisolated(nonsending) public func withDatabaseReader(
_ kind: ReaderKind,
setup: nonisolated(nonsending) (any DatabaseWriter) async throws -> Void = { _ in },
test: nonisolated(nonsending) (any DatabaseReader) async throws -> Void
) async throws {
try await withTemporaryDirectory { directoryURL in
switch kind {
case .queue:
let dbQueue = try makeDatabaseQueue(in: directoryURL)
try await setup(dbQueue)
try await test(dbQueue)
case .pool:
let dbPool = try makeDatabasePool(in: directoryURL)
try await setup(dbPool)
try await test(dbPool)
case .snapshot:
let dbPool = try makeDatabasePool(in: directoryURL)
try await setup(dbPool)
try await test(dbPool.makeSnapshot())
case .snapshotPool:
let dbPool = try makeDatabasePool(in: directoryURL)
try await setup(dbPool)
try await test(dbPool.makeSnapshotPool())
}
}
}
// MARK: - Private
/// The configuration of test databases.
///
/// When `GRDBCIPHER_USE_ENCRYPTION` is set, databases are encrypted.
nonisolated private func makeConfiguration() -> Configuration {
var config = Configuration()
#if GRDBCIPHER_USE_ENCRYPTION
config.prepareDatabase { db in
try db.usePassphrase("secret")
}
#endif
return config
}
nonisolated private func makeDatabaseQueue(in directoryURL: URL) throws -> DatabaseQueue {
try DatabaseQueue(
path: directoryURL.appendingPathComponent("db.sqlite").path,
configuration: makeConfiguration())
}
nonisolated private func makeDatabasePool(in directoryURL: URL) throws -> DatabasePool {
try DatabasePool(
path: directoryURL.appendingPathComponent("db.sqlite").path,
configuration: makeConfiguration())
}