Compare commits

...
Author SHA1 Message Date
Gwendal Roué b44628b9cd Add missing SendableMetatype requirements 2025-07-25 07:27:28 +02:00
Gwendal Roué 8ba1bc9a96 Merge branch 'development' 2025-07-23 13:27:07 +02:00
Gwendal Roué c4e39285a0 v7.6.1 2025-07-23 13:27:01 +02:00
Gwendal Roué 1622b72b62 Merge pull request #1797 from groue/dev/cancellation-fix
Fix race condition regarding Task cancellation
2025-07-23 13:24:52 +02:00
Gwendal Roué 215128390d Fix race condition: prevent cancellation from cancelling other database accesses after database accesses has completed
Before this change, cancelling a database access could cancel *another* database access 😱
2025-07-23 12:01:58 +02:00
Gwendal Roué c5283a0bd9 Warn against the incompatibility between custom SQLite builds and SPM
Addresses https://github.com/groue/GRDB.swift/issues/1709#issuecomment-3100503200
2025-07-22 07:47:41 +02:00
Gwendal Roué fb68849bfb Merge branch 'development' 2025-07-20 18:11:22 +02:00
Gwendal Roué c2bddde88a v7.6.0 2025-07-20 17:21:28 +02:00
Gwendal Roué b4a21d63b2 Merge pull request #1796 from groue/dev/public-RowDecodingError
Throwing row accessors
2025-07-20 17:13:49 +02:00
Gwendal Roué 6ca38eda3b Give TableAliasBase a location in DocC 2025-07-20 14:38:15 +02:00
Gwendal Roué d76922fe1a Document throwing accessors for records and record collections 2025-07-20 14:38:15 +02:00
Gwendal Roué a46f3b69e9 Document throwing row accessors 2025-07-20 14:38:15 +02:00
Gwendal Roué b572982e34 Document RowDecodingError 2025-07-20 13:11:42 +02:00
Gwendal Roué 5a8b025ee8 TODO: test throwing row accessors of record collections and sets 2025-07-20 13:00:12 +02:00
Gwendal Roué 9a1914a813 Test throwing record row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué 4a92263c5e Test throwing column row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué f72d0cecb2 Document throwing row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué 24e0f5ddeb Make throwing row accessors public 2025-07-20 13:00:12 +02:00
Gwendal Roué 2b1b56ea47 Make RowDecodingError public 2025-07-20 13:00:12 +02:00
Gwendal Roué ad704c58e5 Hide implementation of RowDecodingError
Turn the enum into a struct so that it can be made public without exposing internal details
2025-07-20 13:00:12 +02:00
Gwendal Roué 3f928bcf9c Merge pull request #1794 from groue/dev/actor-access
Access task locals from asynchronous database accesses
2025-07-19 17:15:25 +02:00
Gwendal Roué c91c183354 Async database accesses are no longer escaping and no longer need to capture self 2025-07-19 16:42:17 +02:00
Gwendal Roué c666393e63 AppDatabase can be a struct, so let it be a struct 2025-07-19 16:42:17 +02:00
Gwendal Roué d242421862 Async methods accept a non-escaping closure 2025-07-19 16:42:17 +02:00
Gwendal Roué 7a1e65b142 Remove late cancellation checks
I'm slowly changing my mind about this.
2025-07-19 15:27:08 +02:00
Gwendal Roué fb4578a7d6 Delete unused code 2025-07-19 15:26:46 +02:00
Gwendal Roué 6069e6d683 DatabasePool.barrierWriteWithoutTransaction can access task locals 2025-07-19 15:26:44 +02:00
Gwendal Roué a703da9b27 Async version of Pool.barrier { ... } 2025-07-19 14:25:50 +02:00
Gwendal Roué 684266b7b8 DispatchQueueActor supports barriers in concurrent DispatchQueue 2025-07-19 14:25:50 +02:00
Gwendal Roué b24fb76610 Failing test for task locals with DatabaseWriter (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué cbbd0cb945 Add asserts about expected ends of transaction 2025-07-19 14:25:50 +02:00
Gwendal Roué dd4227303a DatabasePool unsafeRead can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 69b786dc9e Allow COMMIT from a cancelled read-only access. 2025-07-19 14:25:50 +02:00
Gwendal Roué 9dd8b2cef7 Add failing test for task locals access from unsafeRead (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué c5ac6cdaa6 DatabaseSnapshotPool reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué e154a652dc Don't check for reentrancy from async Pool.read
One can't call an async function from a database access anywau
2025-07-19 14:25:50 +02:00
Gwendal Roué 41d4f23a83 DatabasePool reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 27b7400979 Async version of Pool.get() 2025-07-19 14:25:50 +02:00
Gwendal Roué e6847886db Extract DispatchQueueActor
We'll probably need it in order to access pool elements with support for task locals
2025-07-19 14:25:50 +02:00
Gwendal Roué c064515247 DatabaseQueue and DatabaseSnapshot reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 96236a3d44 Turn Database.cancel into a sendable closure 2025-07-19 14:25:50 +02:00
Gwendal Roué 01cd49b4ec Failing test for task locals (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué 9db14cb893 Merge pull request #1776 from Jason-Abbott/development
Add custom build instruction for hardened runtime
2025-06-11 09:22:36 +02:00
Jason Abbott b26f60eae0 Add custom build instruction for hardened runtime 2025-06-10 18:45:29 -06:00
Gwendal Roué 79a41dcbbb Merge pull request #1773 from Jason-Abbott/development 2025-06-01 10:24:09 +02:00
Jason Abbott c7d50486ad Merge branch 'groue:development' into development 2025-05-30 12:05:03 -06:00
Jason Abbott 93292d88f4 Make DatabasePreUpdateEvent.Kind Sendable, matching DatabaseEvent.Kind, and also duplicate comments from DatabaseEvent.Kind while here 2025-05-30 12:02:23 -06:00
Gwendal Roué be22e0a2d0 Merge pull request #1768 from groue/dev/throwing-closures
All closures that accept DatabaseComponents can throw
2025-05-12 20:58:47 +02:00
Gwendal Roué d1a2cb0948 All closures that accept DatabaseComponents can throw 2025-05-12 20:33:18 +02:00
53 changed files with 1222 additions and 811 deletions

No files matched your search

+17
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
- `7.5.x` Releases - [7.5.0](#750)
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
- `7.3.x` Releases - [7.3.0](#730)
@@ -137,6 +138,22 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.6.1
Released July 23, 2025
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
## 7.6.0
Released July 20, 2025
- **New**: All closures that accept DatabaseComponents can throw by [@groue](https://github.com/groue) in [#1768](https://github.com/groue/GRDB.swift/pull/1768)
- **New**: Add Sendable conformance to DatabasePreUpdateEvent.Kind, matching DatabaseEvent.Kind by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1773](https://github.com/groue/GRDB.swift/pull/1773)
- **New**: Add custom build instruction for hardened runtime by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1776](https://github.com/groue/GRDB.swift/pull/1776)
- **New**: Access task locals from asynchronous database accesses by [@groue](https://github.com/groue) in [#1794](https://github.com/groue/GRDB.swift/pull/1794)
- **New**: Throwing row accessors by [@groue](https://github.com/groue) in [#1796](https://github.com/groue/GRDB.swift/pull/1796)
## 7.5.0
Released May 11, 2025
+8 -9
View File
@@ -2186,26 +2186,25 @@ struct BookInfo: FetchableRecord {
init(row: Row) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
coverImage = row["coverImage"]
author = try row.decode(forKey: "author")
country = try row.decodeIfPresent(forKey: "country")
coverImage = try row.decodeIfPresent(forKey: "coverImage")
}
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
```
You are already familiar with row subscripts to decode [database values](../README.md#column-values):
When you extract a record from a row, GRDB looks up the tree of **association keys**:
```swift
let name: String = row["name"]
let author = try row.decode(Author.self, forKey: "author")
```
When you extract a record instead of a value from a row, GRDB looks up the tree of **association keys**. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil:
If the key is not found, or only associated with columns that are all NULL, an optional record is decoded as nil:
```swift
let author: Author = row["author"]
let country: Country? = row["country"]
let country = try row.decodeIfPresent(Country.self, forKey: "country")
```
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
@@ -2221,7 +2220,7 @@ struct AuthorInfo: FetchableRecord {
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
books = try row.decode(forKey: "books")
}
}
+32 -26
View File
@@ -9,18 +9,20 @@ A custom SQLite build can activate extra SQLite features, and extra GRDB feature
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB git repository, checkout the latest tagged version:
```sh
cd [GRDB directory]
git checkout [latest tag]
git submodule update --init SQLiteCustom/src
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
@@ -28,31 +30,31 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
4. Create four files in the `GRDBCustomSQLite` folder:
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is one space between -D and the option name.
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
```c
// As many #define as there are custom SQLite compilation options
#define SQLITE_ENABLE_SNAPSHOT
#define SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
```sh
# License: MIT License
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
@@ -61,52 +63,52 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
# PROJECT PATHS
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
#######################################################
# The path to the folder containing GRDBCustom.xcodeproj:
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
# The path to your custom "SQLiteLib-USER.xcconfig":
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
# The path to your custom "GRDBCustomSQLite-USER.h":
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
#######################################################
#
#######################################################
if [ ! -d "$GRDB_SOURCE_PATH" ];
then
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
exit 1
fi
SyncFileChanges () {
SOURCE=$1
DESTINATIONPATH=$2
DESTINATIONFILENAME=$3
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
if [ ! -f "$SOURCE" ];
then
echo "error: Source file missing: $SOURCE"
exit 1
fi
rsync -a "$SOURCE" "$DESTINATION"
}
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
echo "Finished syncing"
```
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
@@ -116,17 +118,21 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
```sh
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
```
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
Select your application target in the "Provide build settings from" menu.
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
(The build error without this exception is "Library not loaded ... different Team IDs")
Now you can use GRDB with your custom SQLite build:
```swift
@@ -12,7 +12,7 @@ import os.log
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
final class AppDatabase: Sendable {
struct AppDatabase: Sendable {
/// Access to the database.
///
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
@@ -130,7 +130,7 @@ extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() async throws {
try await dbWriter.write { [self] db in
try await dbWriter.write { db in
if try Player.all().isEmpty(db) {
// When database is empty, insert new random players
try createRandomPlayers(db)
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.5.0'
s.version = '7.6.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+5 -1
View File
@@ -273,6 +273,7 @@
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */; };
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
@@ -769,6 +770,7 @@
56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = "<group>"; };
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = "<group>"; };
56AACAA722ACED7100A40F2A /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
@@ -1595,13 +1597,13 @@
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
@@ -1611,6 +1613,7 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -2180,6 +2183,7 @@
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */,
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */,
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
+31 -15
View File
@@ -1149,7 +1149,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// See <https://www.sqlite.org/c3ref/interrupt.html>
func interrupt() {
sqlite3_interrupt(sqliteConnection)
if let sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
// MARK: - Database Suspension
@@ -1223,22 +1225,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Cancels the current database access. All statements but ROLLBACK
/// will throw `CancellationError`, until `uncancel()` is called.
///
/// This method can be called from any thread.
func cancel() {
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
/// Returns a closure that cancels the current database access.
/// Most statements will throw `CancellationError`, until `uncancel()`
/// is called.
var cancel: @Sendable () -> Void {
// Workaround the fact that SQLiteConnection is not Sendable.
struct Connection: @unchecked Sendable {
var sqliteConnection: SQLiteConnection?
}
let connection = Connection(sqliteConnection: sqliteConnection)
return { [suspensionMutex, connection] in
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
}
suspension.isCancelled = true
return suspension.interruptsWhenCancelled
}
suspension.isCancelled = true
return suspension.interruptsWhenCancelled
}
if needsInterrupt {
interrupt()
if needsInterrupt {
if let sqliteConnection = connection.sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
}
}
@@ -1318,6 +1329,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
// Commits when read-only are just like rollbacks above.
if statement.transactionEffect == .commitTransaction && isReadOnly {
return
}
// Suspension should not prevent adjusting the read-only mode.
// See <https://github.com/groue/GRDB.swift/issues/1715>.
if statement.isQueryOnlyPragma {
+1 -1
View File
@@ -464,7 +464,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate {
public protocol DatabaseAggregate: SendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+47 -68
View File
@@ -352,40 +352,24 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
releaseReader(.reuse)
}
do {
let result = try dbAccess.inDatabase(db) {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -403,7 +387,9 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
do {
@@ -436,35 +422,16 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(.reuse)
}
do {
let result = try dbAccess.inDatabase(db) {
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
return try await readerPool.get { reader in
try await reader.execute { db in
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -584,7 +551,9 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
try? db.commit() // Ignore commit error
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
do {
@@ -802,7 +771,7 @@ extension DatabasePool: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -818,22 +787,32 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
asyncBarrierWriteWithoutTransaction { dbResult in
do {
try dbAccess.checkCancellation()
let db = try dbResult.get()
let result = try dbAccess.inDatabase(db) {
try updates(db)
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// Pool.barrier does not support async calls (yet?).
// So we perform cancellation checks just as in
// the async version of SerializedDatabase.execute().
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await readerPool.barrier {
try Task.checkCancellation()
return try writer.sync { db in
defer {
cancelMutex.store(nil)
db.uncancel()
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try updates(db)
}
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
+8 -6
View File
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -248,8 +248,9 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -272,7 +273,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
@@ -296,8 +297,9 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore error because we can not notify it.
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -385,7 +387,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -396,7 +398,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
+6 -6
View File
@@ -22,14 +22,14 @@ import Dispatch
/// ### Reading from the Database
///
/// - ``read(_:)-3806d``
/// - ``read(_:)-4d1da``
/// - ``read(_:)-5mfwu``
/// - ``readPublisher(receiveOn:value:)``
/// - ``asyncRead(_:)``
///
/// ### Unsafe Methods
///
/// - ``unsafeRead(_:)-5i7tf``
/// - ``unsafeRead(_:)-5gsav``
/// - ``unsafeRead(_:)-90w0p``
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
@@ -215,7 +215,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
@@ -319,7 +319,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -652,7 +652,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -669,7 +669,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
+2 -2
View File
@@ -201,7 +201,7 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -212,7 +212,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & SendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+4 -2
View File
@@ -113,7 +113,9 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
}
@@ -152,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
@@ -173,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
+14 -25
View File
@@ -294,36 +294,25 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(self.poolCompletion(db))
}
do {
let result = try dbAccess.inDatabase(db) {
try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
let (reader, releaseReader) = try await readerPool.get()
var readerCompletion: PoolCompletion?
defer {
// readerCompletion might be null in cancelled database accesses
releaseReader(readerCompletion ?? .reuse)
}
let (result, completion) = try await reader.execute { db in
let result = Result { try value(db) }
let completion = poolCompletion(db)
return (result, completion)
}
readerCompletion = completion
return try result.get()
}
public func asyncRead(
@@ -353,7 +342,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
+10 -10
View File
@@ -22,18 +22,18 @@ import Dispatch
/// ### Writing into the Database
///
/// - ``write(_:)-76inz``
/// - ``write(_:)-3db50``
/// - ``write(_:)-4gnqx``
/// - ``writePublisher(receiveOn:updates:)``
/// - ``writePublisher(receiveOn:updates:thenRead:)``
/// - ``writeWithoutTransaction(_:)-4qh1w``
/// - ``writeWithoutTransaction(_:)-67mri``
/// - ``writeWithoutTransaction(_:)-18zhj``
/// - ``asyncWrite(_:completion:)``
/// - ``asyncWriteWithoutTransaction(_:)``
///
/// ### Exclusive Access to the Database
///
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
///
/// ### Reading from the Latest Committed Database State
@@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -640,7 +640,7 @@ extension DatabaseWriter {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
public func write<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writeWithoutTransaction { db in
var result: T?
@@ -885,7 +885,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -902,7 +902,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
@@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@@ -947,7 +947,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
+45
View File
@@ -0,0 +1,45 @@
import Dispatch
/// An actor that runs in a DispatchQueue.
///
/// Inspired by <https://forums.swift.org/t/using-dispatchqueue-as-actors-serial-executor-under-linux/75260/3>
actor DispatchQueueActor {
private let executor: DispatchQueueExecutor
/// - precondition: the queue is serial, or flags contains `.barrier`.
init(queue: DispatchQueue, flags: DispatchWorkItemFlags = []) {
self.executor = DispatchQueueExecutor(queue: queue, flags: flags)
}
nonisolated var unownedExecutor: UnownedSerialExecutor {
executor.asUnownedSerialExecutor()
}
func execute<T>(_ work: () throws -> T) rethrows -> T {
try work()
}
}
private final class DispatchQueueExecutor: SerialExecutor {
private let queue: DispatchQueue
private let flags: DispatchWorkItemFlags
init(queue: DispatchQueue, flags: DispatchWorkItemFlags) {
self.queue = queue
self.flags = flags
}
func enqueue(_ job: UnownedJob) {
queue.async(flags: flags) {
job.runSynchronously(on: self.asUnownedSerialExecutor())
}
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
}
func checkIsolated() {
dispatchPrecondition(condition: .onQueue(queue))
}
}
+358 -113
View File
@@ -52,6 +52,8 @@ import Foundation
/// - ``subscript(_:)-9c1fw``
/// - ``subscript(_:)-3jhwm``
/// - ``subscript(_:)-7krrg``
/// - ``decode(_:atIndex:)-33ykh``
/// - ``decode(_:atIndex:)-3btwn``
/// - ``withUnsafeData(atIndex:_:)``
/// - ``dataNoCopy(atIndex:)``
///
@@ -61,7 +63,8 @@ import Foundation
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``coalesce(_:)-359k7``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-4i1o4``
/// - ``decode(_:forColumn:)-4rhs4``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
@@ -70,6 +73,9 @@ import Foundation
/// - ``subscript(_:)-9txgm``
/// - ``subscript(_:)-2esg7``
/// - ``subscript(_:)-wl9a``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-1ljuo``
/// - ``decode(_:forColumn:)-47qeg``
/// - ``withUnsafeData(at:_:)``
/// - ``dataNoCopy(_:)``
///
@@ -84,6 +90,10 @@ import Foundation
/// - ``subscript(_:)-8god3``
/// - ``subscript(_:)-jwnx``
/// - ``subscript(_:)-6ge6t``
/// - ``decode(_:forKey:)-9bbd3``
/// - ``decode(_:forKey:)-2w6lc``
/// - ``decode(_:forKey:)-2soc2``
/// - ``decodeIfPresent(_:forKey:)``
/// - ``PrefetchedRowsView``
/// - ``ScopesTreeView``
/// - ``ScopesView``
@@ -119,6 +129,10 @@ import Foundation
///
/// - ``RowAdapter``
///
/// ### Errors
///
/// - ``RowDecodingError``
///
/// ### Supporting Types
///
/// - ``RowCursor``
@@ -452,7 +466,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
try! decode(Value.self, forColumn: columnName)
}
/// Returns the value at given column, converted to the requested type.
@@ -489,7 +503,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
try! decode(Value.self, forColumn: columnName)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
@@ -533,7 +547,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
try! decode(Value.self, forKey: column.name)
try! decode(Value.self, forColumn: column)
}
/// Returns the value at given column, converted to the requested type.
@@ -573,7 +587,7 @@ extension Row {
-> Value
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
try! decode(Value.self, forKey: column.name)
try! decode(Value.self, forColumn: column)
}
/// Calls the given closure with the `Data` at given index.
@@ -739,12 +753,13 @@ extension Row {
// MARK: - Extracting Records
/// The record associated to the given scope.
/// Returns the record associated to the given key.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
@@ -769,26 +784,28 @@ extension Row {
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author = bookRow["author"]
/// let country: Country = bookRow["country"]
/// let book = try Book(row: row)
/// let author: Author = row["author"]
/// let country: Country = row["country"]
/// ```
///
/// See also: ``scopesTree``
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
try! decode(Record.self, forKey: scope)
}
/// The eventual record associated to the given scope.
/// Returns the eventual record associated to the given key.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
@@ -809,25 +826,26 @@ extension Row {
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// // Fetch a book, with its eventual author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author? = bookRow["author"]
/// let country: Country? = bookRow["country"]
/// let book = try Book(row: row)
/// let author: Author? = row["author"]
/// let country: Country? = row["country"]
/// ```
///
/// See also: ``scopesTree``
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
try! decodeIfPresent(Record.self, forKey: scope)
}
/// A collection of prefetched records associated to the given
/// Returns a collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
@@ -843,10 +861,10 @@ extension Row {
/// struct Book: TableRecord, FetchableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: [Book] = author["books"]
/// let author = try Author(row: row)
/// let books: [Book] = row["books"]
/// ```
///
/// See also: ``prefetchedRows``
@@ -861,7 +879,8 @@ extension Row {
try! decode(Records.self, forKey: key)
}
/// A set prefetched records associated to the given association key.
/// Returns the set of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
@@ -876,10 +895,10 @@ extension Row {
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: Set<Book> = author["books"]
/// let author = try Author(row: row)
/// let books: Set<Book> = row["books"]
/// ```
///
/// See also: ``prefetchedRows``
@@ -935,7 +954,8 @@ extension Row {
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopesTree``.
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
public var scopes: ScopesView {
impl.scopes(prefetchedRows: prefetchedRows)
}
@@ -1065,10 +1085,28 @@ extension Row {
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score = try row.decode(Int.self, atIndex: 0) // 42
/// let score: Int = try row.decode(atIndex: 0) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
/// let name: String = try row.decode(atIndex: 0) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = try row.decode(atIndex: 0) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible>(
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
@@ -1082,13 +1120,37 @@ extension Row {
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: "score") // 42
/// let score: Int = try row.decode(forColumn: "score") // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
/// let name: String = try row.decode(forColumn: "name") // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: "name") // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: "missing") // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible>(
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
forColumn columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
@@ -1100,6 +1162,47 @@ extension Row {
}
return try Value.decode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forColumn column: some ColumnExpression)
throws -> Value
{
try decode(type, forColumn: column.name)
}
}
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
@@ -1114,11 +1217,29 @@ extension Row {
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score = try row.decode(Int.self, atIndex: 0) // 42
/// let score: Int = try row.decode(atIndex: 0) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
/// let name: String = try row.decode(atIndex: 0) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = try row.decode(atIndex: 0) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inline(__always)
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
@@ -1136,13 +1257,37 @@ extension Row {
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: "score") // 42
/// let score: Int = try row.decode(forColumn: "score") // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
/// let name: String = try row.decode(forColumn: "name") // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: "name") // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: "missing") // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
forColumn columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
@@ -1155,6 +1300,51 @@ extension Row {
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forColumn column: some ColumnExpression)
throws -> Value
{
try decode(type, forColumn: column.name)
}
// Support for fast decoding in scoped rows
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
@@ -1187,37 +1377,51 @@ extension Row {
// MARK: - Throwing Record Decoding Methods
extension Row {
/// Returns the eventual record associated with the given scope.
/// Returns the eventual record associated to the given key.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// The result is nil if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// let author: Author? = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
/// struct Country: TableRecord, FetchableRecord { }
///
/// Associated records stored in nested associations are available, too:
/// // Fetch a book, with its eventual author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
/// let book = try Book(row: row)
/// let author: Author? = try row.decode(forKey: "author")
/// let country: Country? = try row.decode(forKey: "country")
/// ```
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// let country: Country? = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// Nil is returned if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decodeIfPresent<Record: FetchableRecord>(
/// - parameter type: The decoded type.
/// - parameter scope: A scope identifier.
/// - throws: Any error that happens during the decoding.
public func decodeIfPresent<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record?
@@ -1228,37 +1432,48 @@ extension Row {
return try Record(row: scopedRow)
}
/// Returns the record associated with the given scope.
/// Returns the record associated to the given key.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// For example:
///
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// let author: Author = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
/// struct Country: TableRecord, FetchableRecord { }
///
/// Associated records stored in nested associations are available, too:
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
/// let book = try Book(row: row)
/// let author: Author = try row.decode(forKey: "author")
/// let country: Country = try row.decode(forKey: "country")
/// ```
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// let country: Country = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// A fatal error is raised if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decode<Record: FetchableRecord>(
/// - parameter type: The decoded type.
/// - parameter scope: A scope identifier.
/// - throws: Any error that happens during the decoding.
public func decode<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record
@@ -1300,20 +1515,34 @@ extension Row {
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
extension Row {
/// Returns the records encoded in the given prefetched rows.
/// Returns a collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
/// struct Book: TableRecord, FetchableRecord { }
///
/// let books: [Book] = row["books"]
/// print(books[0].title)
/// // Prints "Moby-Dick"
func decode<Collection>(
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: row)
/// let books: [Book] = try row.decode(forKey: "books")
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter type: The type of the decoded collection.
/// - parameter key: An association key.
/// - throws: Any error that happens during the decoding.
public func decode<Collection>(
_ type: Collection.Type = Collection.self,
forKey key: String)
throws -> Collection
@@ -1321,6 +1550,7 @@ extension Row {
Collection: RangeReplaceableCollection,
Collection.Element: FetchableRecord
{
// TODO: test independently
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
@@ -1351,24 +1581,39 @@ extension Row {
return collection
}
/// Returns the set of records encoded in the given prefetched rows.
/// Returns the set of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let books: Set<Book> = row["books"]
/// print(books.first!.title)
/// // Prints "Moby-Dick"
func decode<Record: FetchableRecord & Hashable>(
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: row)
/// let books: Set<Book> = try row.decode(forKey: "books")
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter type: The type of the decoded set.
/// - parameter key: An association key.
/// - throws: Any error that happens during the decoding.
public func decode<Record: FetchableRecord & Hashable>(
_ type: Set<Record>.Type = Set<Record>.self,
forKey key: String)
throws -> Set<Record>
{
// TODO: test independently
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
+32 -16
View File
@@ -23,9 +23,21 @@ enum RowKey: Hashable, Sendable {
case prefetchKey(String)
}
/// A decoding error
@usableFromInline
enum RowDecodingError: Error {
/// A decoding error thrown when decoding a database row.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// // RowDecodingError: could not decode String from database value NULL.
/// let name = try row.decode(String.self, forColumn: "name")
/// ```
public struct RowDecodingError: Error {
enum Impl {
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
}
@usableFromInline
struct Context: CustomDebugStringConvertible, Sendable {
/// A description of what went wrong, for debugging purposes.
@@ -55,17 +67,19 @@ enum RowDecodingError: Error {
}
}
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
var impl: Impl
var context: Context {
switch self {
switch impl {
case .keyNotFound(_, let context),
.valueMismatch(_, let context):
return context
}
}
static func valueMismatch(_ type: Any.Type, _ context: Context) -> Self {
self.init(impl: .valueMismatch(type, context))
}
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
static func valueMismatch(
@@ -74,11 +88,10 @@ enum RowDecodingError: Error {
databaseValue: DatabaseValue)
-> Self
{
valueMismatch(
type,
RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
"""))
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
""")
return self.init(impl: .valueMismatch(type, context))
}
/// Convenience method that builds the
@@ -115,11 +128,15 @@ enum RowDecodingError: Error {
/// error message.
@usableFromInline
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
keyNotFound(
self.init(impl: .keyNotFound(
.columnName(columnName),
RowDecodingError.Context(decodingContext: context, debugDescription: """
column not found: \(String(reflecting: columnName))
"""))
""")))
}
static func keyNotFound(_ rowKey: RowKey, _ context: Context) -> Self {
self.init(impl: .keyNotFound(rowKey, context))
}
}
@@ -167,8 +184,7 @@ struct RowDecodingContext {
}
extension RowDecodingError: CustomStringConvertible {
@usableFromInline
var description: String {
public var description: String {
let context = self.context
let row = context.row
var chunks: [String] = []
+18 -116
View File
@@ -5,6 +5,9 @@ final class SerializedDatabase {
/// The database connection
private let db: Database
/// The actor that performs asynchronous accesses
private let actor: DispatchQueueActor
/// The database configuration
var configuration: Configuration { db.configuration }
@@ -55,6 +58,8 @@ final class SerializedDatabase {
} else {
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
}
self.actor = DispatchQueueActor(queue: queue)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
do {
@@ -245,20 +250,22 @@ final class SerializedDatabase {
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @escaping @Sendable (Database) throws -> T
_ block: @Sendable (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
self.async { db in
do {
let result = try dbAccess.inDatabase(db) {
try block(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try await actor.execute {
defer {
cancelMutex.store(nil)
db.uncancel()
preconditionNoUnsafeTransactionLeft(db)
}
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try block(db)
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
@@ -305,108 +312,3 @@ final class SerializedDatabase {
// It happens the job of SerializedDatabase is precisely to provide thread-safe
// access to `Database`.
extension SerializedDatabase: @unchecked Sendable { }
// MARK: - Task Cancellation Support
enum DatabaseAccessCancellationState: @unchecked Sendable {
// @unchecked Sendable because database is only accessed from its
// dispatch queue.
case notConnected
case connected(Database)
case cancelled
case expired
}
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
/// Supports Task cancellation in async database accesses.
///
/// Usage:
///
/// ```swift
/// let dbAccess = CancellableDatabaseAccess()
/// return try dbAccess.withCancellableContinuation { continuation in
/// asyncDatabaseAccess { db in
/// do {
/// let result = try dbAccess.inDatabase(db) {
/// // Perform database operations
/// }
/// continuation.resume(returning: result)
/// } catch {
/// continuation.resume(throwing: error)
/// }
/// }
/// }
/// ```
extension CancellableDatabaseAccess: DatabaseCancellable {
convenience init() {
self.init(.notConnected)
}
func cancel() {
withLock { state in
switch state {
case let .connected(db):
db.cancel()
state = .cancelled
case .notConnected:
state = .cancelled
case .cancelled, .expired:
break
}
}
}
func withCancellableContinuation<Value>(
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
) async throws -> Value {
try await withTaskCancellationHandler {
try checkCancellation()
return try await withUnsafeThrowingContinuation { continuation in
fn(continuation)
}
} onCancel: {
cancel()
}
}
func checkCancellation() throws {
try withLock { state in
if case .cancelled = state {
throw CancellationError()
}
}
}
/// Wraps a full database access with cancellation support. When this
/// method returns, the database is NOT cancelled.
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
try withLock { state in
switch state {
case .connected, .expired:
fatalError("Can't use a CancellableDatabaseAccess twice")
case .notConnected:
state = .connected(db)
case .cancelled:
throw CancellationError()
}
}
return try throwingFirstError {
try work()
} finally: {
let cancelled = withLock { state in
if case .cancelled = state {
db.uncancel()
return true
} else {
state = .expired
return false
}
}
if cancelled {
throw CancellationError()
}
}
}
}
+8 -8
View File
@@ -1252,16 +1252,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
public struct DatabasePreUpdateEvent {
/// An event kind
public enum Kind: CInt {
/// SQLITE_INSERT
case insert = 18
/// An event kind.
public enum Kind: CInt, Sendable {
/// An insertion event
case insert = 18 // SQLITE_INSERT
/// SQLITE_DELETE
case delete = 9
/// A deletion event
case delete = 9 // SQLITE_DELETE
/// SQLITE_UPDATE
case update = 23
/// An update event
case update = 23 // SQLITE_UPDATE
}
/// The event kind
+1 -1
View File
@@ -97,7 +97,7 @@ try dbQueue.write { db in
}
```
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
@@ -305,13 +305,13 @@ extension AssociationToOne {
///
/// ### Building Association Aggregates
///
/// - ``average(_:)-4n3up``
/// - ``average(_:)-1ehdb``
/// - ``count``
/// - ``isEmpty``
/// - ``max(_:)-1upp8``
/// - ``min(_:)-7xc49``
/// - ``sum(_:)-5p74s``
/// - ``total(_:)-hudm``
/// - ``max(_:)-a32j``
/// - ``min(_:)-41jp8``
/// - ``sum(_:)-47yg7``
/// - ``total(_:)-6dd9d``
///
/// - ``AssociationAggregate``
///
@@ -179,11 +179,11 @@ extension AssociationToMany {
/// }
/// ```
public func average(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
average(expression(RowDecoder.databaseComponents))
try average(expression(RowDecoder.databaseComponents))
}
/// Returns the maximum value of the given expression in associated records.
@@ -276,11 +276,11 @@ extension AssociationToMany {
/// }
/// ```
public func max(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
max(expression(RowDecoder.databaseComponents))
try max(expression(RowDecoder.databaseComponents))
}
/// Returns the minimum value of the given expression in associated records.
@@ -373,11 +373,11 @@ extension AssociationToMany {
/// }
/// ```
public func min(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
min(expression(RowDecoder.databaseComponents))
try min(expression(RowDecoder.databaseComponents))
}
/// Returns the sum of the given expression in associated records.
@@ -434,7 +434,7 @@ extension AssociationToMany {
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `SUM` SQL function.
/// See also ``AssociationToMany/total(_:)-hudm`` and
/// See also ``AssociationToMany/total(_:)-6dd9d`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
@@ -478,11 +478,11 @@ extension AssociationToMany {
/// }
/// ```
public func sum(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
sum(expression(RowDecoder.databaseComponents))
try sum(expression(RowDecoder.databaseComponents))
}
/// Returns the sum of the given expression in associated records.
@@ -541,7 +541,7 @@ extension AssociationToMany {
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `TOTAL` SQL function.
/// See also ``AssociationToMany/sum(_:)-5p74s`` and
/// See also ``AssociationToMany/sum(_:)-47yg7`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
@@ -585,11 +585,11 @@ extension AssociationToMany {
/// }
/// ```
public func total(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
total(expression(RowDecoder.databaseComponents))
try total(expression(RowDecoder.databaseComponents))
}
}
@@ -57,7 +57,7 @@
/// ### Changing The Type of Fetched Results
///
/// - ``asRequest(of:)``
/// - ``select(_:as:)-74lsr``
/// - ``select(_:as:)-4cj9h``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
@@ -228,12 +228,12 @@ extension QueryInterfaceRequest: SelectionRequest {
///
/// Any previous selection is discarded.
public func select<T>(
_ selection: (DatabaseComponents) -> any SQLSelectable,
as type: T.Type = T.self)
-> QueryInterfaceRequest<T>
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
as type: T.Type = T.self
) rethrows -> QueryInterfaceRequest<T>
where RowDecoder: TableRecord
{
select(selection).asRequest(of: T.self)
try select(selection).asRequest(of: T.self)
}
/// Defines the result columns with an SQL string, and defines the type of
@@ -360,7 +360,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
where RowDecoder: Identifiable & SendableMetatype
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
@@ -702,8 +702,8 @@ extension QueryInterfaceRequest {
/// - precondition: The result of `select` is not empty.
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
@@ -887,8 +887,8 @@ extension QueryInterfaceRequest {
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
@@ -1059,7 +1059,7 @@ extension QueryInterfaceRequest {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) -> ColumnAssignment
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
{
@@ -1094,7 +1094,7 @@ extension QueryInterfaceRequest {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment]
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
{
@@ -1208,9 +1208,9 @@ extension QueryInterfaceRequest {
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
@@ -1303,8 +1303,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1382,8 +1382,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> [RowDecoder]
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1453,8 +1453,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Set<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1532,9 +1532,9 @@ extension QueryInterfaceRequest {
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
@@ -1629,8 +1629,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1710,8 +1710,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> [RowDecoder]
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1783,8 +1783,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Set<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -22,11 +22,11 @@ public protocol TypedRequest<RowDecoder> {
///
/// ### The SELECT Clause
///
/// - ``annotated(with:)-56y26``
/// - ``annotated(with:)-9nuwi``
/// - ``annotated(with:)-9wodv``
/// - ``annotated(with:)-69r3``
/// - ``annotatedWhenConnected(with:)``
/// - ``select(_:)-90gu2``
/// - ``select(_:)-4iv1w``
/// - ``select(_:)-270ge``
/// - ``select(_:)-4jw13``
/// - ``select(literal:)``
/// - ``select(sql:arguments:)``
/// - ``selectWhenConnected(_:)``
@@ -246,9 +246,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// .select(\.score)
/// ```
public func select(
_ selection: (DatabaseComponents) -> any SQLSelectable
) -> Self {
select(selection(Self.RowDecoder.databaseComponents))
_ selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> Self {
try select(selection(Self.RowDecoder.databaseComponents))
}
/// Defines the result columns.
@@ -276,9 +276,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// .select { [$0.score] }
/// ```
public func select(
_ selection: (DatabaseComponents) -> [any SQLSelectable]
) -> Self {
select(selection(Self.RowDecoder.databaseComponents))
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> Self {
try select(selection(Self.RowDecoder.databaseComponents))
}
/// Appends a result column to the selected columns.
@@ -302,9 +302,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
public func annotated(
with selection: (DatabaseComponents) -> any SQLSelectable
) -> Self {
annotated(with: selection(Self.RowDecoder.databaseComponents))
with selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> Self {
try annotated(with: selection(Self.RowDecoder.databaseComponents))
}
/// Appends result columns to the selected columns.
@@ -328,9 +328,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
public func annotated(
with selection: (DatabaseComponents) -> [any SQLSelectable]
) -> Self {
annotated(with: selection(Self.RowDecoder.databaseComponents))
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> Self {
try annotated(with: selection(Self.RowDecoder.databaseComponents))
}
}
@@ -346,7 +346,7 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// ### The WHERE and JOIN ON Clauses
///
/// - ``all()``
/// - ``filter(_:)-5l0gu``
/// - ``filter(_:)-7j0nw``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
/// - ``filterWhenConnected(_:)``
@@ -463,9 +463,9 @@ extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
/// let request = Player.all().filter { $0.name == name }
/// ```
public func filter(
_ predicate: (DatabaseComponents) -> any SQLSpecificExpressible
) -> Self {
filter(predicate(Self.RowDecoder.databaseComponents))
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
) rethrows -> Self {
try filter(predicate(Self.RowDecoder.databaseComponents))
}
}
@@ -964,15 +964,15 @@ extension TableRequest where Self: AggregatingRequest {
///
/// ### The GROUP BY Clause
///
/// - ``group(_:)-9z116``
/// - ``group(_:)-43p07``
/// - ``group(_:)-5soxm``
/// - ``group(_:)-32exm``
/// - ``group(literal:)``
/// - ``group(sql:arguments:)``
/// - ``groupWhenConnected(_:)``
///
/// ### The HAVING Clause
///
/// - ``having(_:)-6zfvb``
/// - ``having(_:)-27hlo``
/// - ``having(literal:)``
/// - ``having(sql:arguments:)``
/// - ``havingWhenConnected(_:)``
@@ -1199,16 +1199,16 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
///
/// Any previous grouping is discarded.
public func group(
_ expression: (DatabaseComponents) -> any SQLExpressible
) -> Self {
group(expression(Self.RowDecoder.databaseComponents))
_ expression: (DatabaseComponents) throws -> any SQLExpressible
) rethrows -> Self {
try group(expression(Self.RowDecoder.databaseComponents))
}
/// Returns an aggregate request grouped on the given SQL expressions.
public func group(
_ expressions: (DatabaseComponents) -> [any SQLExpressible]
) -> Self {
group(expressions(Self.RowDecoder.databaseComponents))
_ expressions: (DatabaseComponents) throws -> [any SQLExpressible]
) rethrows -> Self {
try group(expressions(Self.RowDecoder.databaseComponents))
}
/// Filters the aggregated groups with a boolean SQL expression.
@@ -1233,9 +1233,9 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
/// .having { max($0.score) > 1000 }
/// ```
public func having(
_ predicate: (DatabaseComponents) -> any SQLExpressible
) -> Self {
having(predicate(Self.RowDecoder.databaseComponents))
_ predicate: (DatabaseComponents) throws -> any SQLExpressible
) rethrows -> Self {
try having(predicate(Self.RowDecoder.databaseComponents))
}
}
@@ -1247,8 +1247,8 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
///
/// ### The ORDER BY Clause
///
/// - ``order(_:)-54bt8``
/// - ``order(_:)-7jcay``
/// - ``order(_:)-5q7wj``
/// - ``order(_:)-711zj``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderWhenConnected(_:)``
@@ -1454,9 +1454,9 @@ extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
/// .order(\.name)
/// ```
public func order(
_ ordering: (DatabaseComponents) -> any SQLOrderingTerm
) -> Self {
order(ordering(Self.RowDecoder.databaseComponents))
_ ordering: (DatabaseComponents) throws -> any SQLOrderingTerm
) rethrows -> Self {
try order(ordering(Self.RowDecoder.databaseComponents))
}
/// Sorts the fetched rows according to the given SQL ordering terms.
@@ -1485,9 +1485,9 @@ extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
/// .order { [$0.name] }
/// ```
public func order(
_ orderings: (DatabaseComponents) -> [any SQLOrderingTerm]
) -> Self {
order(orderings(Self.RowDecoder.databaseComponents))
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
) rethrows -> Self {
try order(orderings(Self.RowDecoder.databaseComponents))
}
}
@@ -1800,12 +1800,12 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The SELECT Clause
///
/// - ``SelectionRequest/annotated(with:)-56y26``
/// - ``SelectionRequest/annotated(with:)-9nuwi``
/// - ``SelectionRequest/annotated(with:)-9wodv``
/// - ``SelectionRequest/annotated(with:)-69r3``
/// - ``SelectionRequest/annotatedWhenConnected(with:)``
/// - ``distinct()``
/// - ``SelectionRequest/select(_:)-90gu2``
/// - ``SelectionRequest/select(_:)-4iv1w``
/// - ``SelectionRequest/select(_:)-270ge``
/// - ``SelectionRequest/select(_:)-4jw13``
/// - ``SelectionRequest/select(literal:)``
/// - ``SelectionRequest/select(sql:arguments:)``
/// - ``SelectionRequest/selectWhenConnected(_:)``
@@ -1813,7 +1813,7 @@ extension JoinableRequest where Self: SelectionRequest {
/// ### The WHERE Clause
///
/// - ``FilteredRequest/all()``
/// - ``FilteredRequest/filter(_:)-5l0gu``
/// - ``FilteredRequest/filter(_:)-7j0nw``
/// - ``TableRequest/filter(id:)``
/// - ``TableRequest/filter(ids:)``
/// - ``TableRequest/filter(key:)-1p9sq``
@@ -1829,21 +1829,21 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The GROUP BY and HAVING Clauses
///
/// - ``AggregatingRequest/group(_:)-9z116``
/// - ``AggregatingRequest/group(_:)-43p07``
/// - ``AggregatingRequest/group(_:)-5soxm``
/// - ``AggregatingRequest/group(_:)-32exm``
/// - ``AggregatingRequest/group(literal:)``
/// - ``AggregatingRequest/group(sql:arguments:)``
/// - ``TableRequest/groupByPrimaryKey()``
/// - ``AggregatingRequest/groupWhenConnected(_:)``
/// - ``AggregatingRequest/having(_:)-6zfvb``
/// - ``AggregatingRequest/having(_:)-27hlo``
/// - ``AggregatingRequest/having(literal:)``
/// - ``AggregatingRequest/having(sql:arguments:)``
/// - ``AggregatingRequest/havingWhenConnected(_:)``
///
/// ### The ORDER BY Clause
///
/// - ``OrderedRequest/order(_:)-54bt8``
/// - ``OrderedRequest/order(_:)-7jcay``
/// - ``OrderedRequest/order(_:)-5q7wj``
/// - ``OrderedRequest/order(_:)-711zj``
/// - ``OrderedRequest/order(literal:)``
/// - ``OrderedRequest/order(sql:arguments:)``
/// - ``OrderedRequest/orderWhenConnected(_:)``
+5 -5
View File
@@ -457,7 +457,7 @@ extension Table {
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
where RowDecoder: Identifiable & SendableMetatype
{
all().selectID()
}
@@ -1932,8 +1932,8 @@ extension Table {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) -> ColumnAssignment)
throws -> Int
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)])
@@ -1968,8 +1968,8 @@ extension Table {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Int
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -290,6 +290,12 @@ extension TableAliasBase {
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#table-aliases> for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// ## Topics
///
/// ## Supporting Types
///
/// - ``TableAliasBase``
@dynamicMemberLookup
public final class TableAlias<RowDecoder>: TableAliasBase, @unchecked Sendable {
init(tableName: String, userName: String? = nil)
@@ -78,9 +78,9 @@ extension TableRecord {
/// let request = Player.select(\.score)
/// ```
public static func select(
_ selection: (DatabaseComponents) -> any SQLSelectable
) -> QueryInterfaceRequest<Self> {
all().select(selection)
_ selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> QueryInterfaceRequest<Self> {
try all().select(selection)
}
/// Returns a request that selects the provided result columns.
@@ -94,9 +94,9 @@ extension TableRecord {
/// let request = Player.select { [$0.id, $0.score] }
/// ```
public static func select(
_ selection: (DatabaseComponents) -> [any SQLSelectable]
) -> QueryInterfaceRequest<Self> {
all().select(selection)
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> QueryInterfaceRequest<Self> {
try all().select(selection)
}
/// Returns a request that selects the provided SQL string.
@@ -217,11 +217,11 @@ extension TableRecord {
/// let maxScore = try request.fetchOne(db) // Int?
/// ```
public static func select<RowDecoder>(
_ selection: (DatabaseComponents) -> any SQLSelectable,
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
as type: RowDecoder.Type = RowDecoder.self
) rethrows -> QueryInterfaceRequest<RowDecoder>
{
all().select(selection, as: type)
try all().select(selection, as: type)
}
/// Returns a request that selects the provided SQL string, and defines the
@@ -395,9 +395,9 @@ extension TableRecord {
/// let request = Player.annotated { ($0.score + $0.bonus).forKey("totalScore") }
/// ```
public static func annotated(
with selection: (DatabaseComponents) -> any SQLSelectable
) -> QueryInterfaceRequest<Self> {
all().annotated(with: selection)
with selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> QueryInterfaceRequest<Self> {
try all().annotated(with: selection)
}
/// Returns a request with the provided result columns appended to the
@@ -415,9 +415,9 @@ extension TableRecord {
/// let request = Player.annotated { [($0.score + $0.bonus).forKey("totalScore")] }
/// ```
public static func annotated(
with selection: (DatabaseComponents) -> [any SQLSelectable]
) -> QueryInterfaceRequest<Self> {
all().annotated(with: selection)
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> QueryInterfaceRequest<Self> {
try all().annotated(with: selection)
}
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
@@ -453,9 +453,9 @@ extension TableRecord {
/// let request = Player.filter { $0.name == name }
/// ```
public static func filter(
_ predicate: (DatabaseComponents) -> any SQLSpecificExpressible
) -> QueryInterfaceRequest<Self> {
all().filter(predicate)
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
) rethrows -> QueryInterfaceRequest<Self> {
try all().filter(predicate)
}
/// Returns a request filtered by primary key.
@@ -632,9 +632,9 @@ extension TableRecord {
/// let request = Player.order(\.score.desc)
/// ```
public static func order(
_ orderings: (DatabaseComponents) -> any SQLOrderingTerm
) -> QueryInterfaceRequest<Self> {
all().order(orderings)
_ orderings: (DatabaseComponents) throws -> any SQLOrderingTerm
) rethrows -> QueryInterfaceRequest<Self> {
try all().order(orderings)
}
/// Returns a request sorted according to the given SQL ordering terms.
@@ -648,9 +648,9 @@ extension TableRecord {
/// let request = Player.order { [$0.score.desc, $0.name] }
/// ```
public static func order(
_ orderings: (DatabaseComponents) -> [any SQLOrderingTerm]
) -> QueryInterfaceRequest<Self> {
all().order(orderings)
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
) rethrows -> QueryInterfaceRequest<Self> {
try all().order(orderings)
}
/// Returns a request sorted by primary key.
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord {
public protocol EncodableRecord: SendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
+14 -14
View File
@@ -212,20 +212,20 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// swiftlint:disable comma
// swiftlint:disable line_length
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
// swiftlint:enable line_length
// swiftlint:enable comma
@@ -329,8 +329,8 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
@@ -578,8 +578,8 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(
+4 -4
View File
@@ -261,8 +261,8 @@ extension PersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
@@ -476,8 +476,8 @@ extension PersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(
+13 -15
View File
@@ -61,11 +61,11 @@ import Foundation
/// - ``all()``
/// - ``annotated(with:)-4xoen``
/// - ``annotated(with:)-8ce7u``
/// - ``annotated(with:)-9qvhi``
/// - ``annotated(with:)-12q5i``
/// - ``annotated(with:)-58am5``
/// - ``annotated(with:)-12jwq``
/// - ``annotated(withOptional:)``
/// - ``annotated(withRequired:)``
/// - ``filter(_:)-2l1zl``
/// - ``filter(_:)-4xvdh``
/// - ``filter(id:)``
/// - ``filter(ids:)``
/// - ``filter(key:)-9ey53``
@@ -84,15 +84,15 @@ import Foundation
/// - ``matching(_:)-22m4o``
/// - ``matching(_:)-1t8ph``
/// - ``none()``
/// - ``order(_:)-4h1zh``
/// - ``order(_:)-21efu``
/// - ``order(_:)-4j3ej``
/// - ``order(_:)-53dja``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderByPrimaryKey()``
/// - ``request(for:)``
/// - ``select(_:)-8pytw``
/// - ``select(_:)-3aslb``
/// - ``select(_:as:)-9s48t``
/// - ``select(_:)-1bgd1``
/// - ``select(_:)-8yqls``
/// - ``select(_:as:)-7zz91``
/// - ``select(literal:)``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
@@ -134,7 +134,7 @@ import Foundation
/// - ``select(_:as:)-tjh0``
/// - ``updateAll(_:onConflict:_:)-7vv9x``
/// - ``updateAll(_:onConflict:_:)-7atfw``
public protocol TableRecord {
public protocol TableRecord: SendableMetatype {
/// A type that defines columns.
///
/// For example:
@@ -783,9 +783,8 @@ extension TableRecord {
public static func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Int
{
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int {
try updateAll(db, onConflict: conflictResolution, assignments(databaseComponents))
}
@@ -816,9 +815,8 @@ extension TableRecord {
public static func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) -> ColumnAssignment)
throws -> Int
{
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int {
try updateAll(db, onConflict: conflictResolution, [assignment(databaseComponents)])
}
+2 -2
View File
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
self.attemptToFulfill = attemptToFulfill
}
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
@@ -35,7 +35,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
private class OnDemandFutureSubscription<Downstream: Subscriber & SendableMetatype>: Subscription, @unchecked Sendable {
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
+30
View File
@@ -63,7 +63,9 @@ final class Pool<T: Sendable>: Sendable {
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
private let barrierActor: DispatchQueueActor
private let semaphoreWaitingQueue: DispatchQueue // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
private let semaphoreWaitingActor: DispatchQueueActor
/// Creates a Pool.
///
@@ -83,7 +85,9 @@ final class Pool<T: Sendable>: Sendable {
self.itemsSemaphore = DispatchSemaphore(value: maximumCount)
self.itemsGroup = DispatchGroup()
self.barrierQueue = DispatchQueue(label: "GRDB.Pool.barrier", qos: qos, attributes: [.concurrent])
self.barrierActor = DispatchQueueActor(queue: barrierQueue, flags: [.barrier])
self.semaphoreWaitingQueue = DispatchQueue(label: "GRDB.Pool.wait", qos: qos)
self.semaphoreWaitingActor = DispatchQueueActor(queue: semaphoreWaitingQueue)
}
/// Returns a tuple (element, release)
@@ -114,6 +118,15 @@ final class Pool<T: Sendable>: Sendable {
}
}
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() async throws -> ElementAndRelease {
// See asyncGet(_:)
try await semaphoreWaitingActor.execute {
try self.get()
}
}
/// Eventually produces a tuple (element, release), where element is
/// intended to be used asynchronously.
///
@@ -141,6 +154,14 @@ final class Pool<T: Sendable>: Sendable {
return try block(element)
}
/// Performs an asynchronous block with an element. The element turns
/// available after the block has executed.
func get<U>(block: (T) async throws -> U) async throws -> U {
let (element, completion) = try await get()
defer { completion(.reuse) }
return try await block(element)
}
private func release(_ item: Item, completion: PoolCompletion) {
contentLock.withLock { content in
switch completion {
@@ -184,6 +205,15 @@ final class Pool<T: Sendable>: Sendable {
}
}
func barrier<R: Sendable>(
execute barrier: sending () throws -> sending R
) async rethrows -> sending R {
try await barrierActor.execute {
itemsGroup.wait()
return try barrier()
}
}
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
@@ -58,7 +58,7 @@ public protocol _ValueReducerFetcher: Sendable {
/// ### Supporting Types
///
/// - ``ValueReducers``
public protocol ValueReducer: _ValueReducer { }
public protocol ValueReducer: _ValueReducer, SendableMetatype { }
/// A namespace for concrete types that adopt the ``ValueReducer`` protocol.
public enum ValueReducers { }
+2 -2
View File
@@ -511,7 +511,7 @@ extension DatabasePublishers {
self.start = start
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = ValueSubscription(
start: start,
downstream: subscriber)
@@ -521,7 +521,7 @@ extension DatabasePublishers {
private class ValueSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & SendableMetatype,
Downstream.Failure == Error
{
// @unchecked Sendable because `cancellable` and `state` are
+5 -1
View File
@@ -262,6 +262,7 @@
56A8C2321D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */; };
56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; };
56AC93E12E291C9700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93E02E291C9700DB6C74 /* DispatchQueueActor.swift */; };
56AE6428222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; };
56AFEF3229969F7E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */; };
@@ -781,6 +782,7 @@
56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationUUIDTests.swift; sourceTree = "<group>"; };
56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = "<group>"; };
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = "<group>"; };
56AC93E02E291C9700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = "<group>"; };
@@ -1600,13 +1602,13 @@
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
56AC93E02E291C9700DB6C74 /* DispatchQueueActor.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */,
56A6EB2226076F6A00C27594 /* SQL.swift */,
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
56FBFED52210731000945324 /* SQLRequest.swift */,
@@ -1616,6 +1618,7 @@
56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56564F3828637C9900A19E9F /* WALSnapshot.swift */,
56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -2009,6 +2012,7 @@
566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
5656A8672295BD56001FF3FF /* HasOneAssociation.swift in Sources */,
566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56AC93E12E291C9700DB6C74 /* DispatchQueueActor.swift in Sources */,
5656A85F2295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */,
56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */,
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */,
+23 -2
View File
@@ -15,7 +15,7 @@
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: May 11, 2025 • [version 7.5.0](https://github.com/groue/GRDB.swift/tree/v7.5.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: July 23, 2025 • [version 7.6.1](https://github.com/groue/GRDB.swift/tree/v7.6.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
@@ -843,6 +843,13 @@ row[...] as Int
row[...] as Int?
```
Throwing accessors exist as well. Their use is not encouraged, because a database decoding error is a programming error. If an application stores invalid data in the database file, that is a bug that needs to be fixed:
```swift
let name = try row.decode(String.self, atIndex: 0)
let bookCount = try row.decode(Int.self, forColumn: "bookCount")
```
> **Warning**: avoid the `as!` and `as?` operators:
>
> ```swift
@@ -4984,12 +4991,13 @@ try dbQueue.write { db in
## Error Handling
GRDB can throw [DatabaseError](#databaseerror), [RecordError], or crash your program with a [fatal error](#fatal-errors).
GRDB can throw [DatabaseError](#databaseerror), [RecordError], [RowDecodingError], or crash your program with a [fatal error](#fatal-errors).
Considering that a local database is not some JSON loaded from a remote server, GRDB focuses on **trusted databases**. Dealing with [untrusted databases](#how-to-deal-with-untrusted-inputs) requires extra care.
- [DatabaseError](#databaseerror)
- [RecordError]
- [RowDecodingError]
- [Fatal Errors](#fatal-errors)
- [How to Deal with Untrusted Inputs](#how-to-deal-with-untrusted-inputs)
- [Error Log](#error-log)
@@ -5094,6 +5102,18 @@ do {
```
### RowDecodingError
📖 [`RowDecodingError`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowdecodingerror)
**RowDecodingError** is thrown when the application can not decode a value from a database row. For example:
```swift
let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
// RowDecodingError: could not decode String from database value NULL.
let name = try row.decode(String.self, forColumn: "name")
```
### Fatal Errors
**Fatal errors notify that the program, or the database, has to be changed.**
@@ -6111,6 +6131,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[persistence methods]: #persistence-methods
[Persistence Methods and the `RETURNING` clause]: #persistence-methods-and-the-returning-clause
[RecordError]: #recorderror
[RowDecodingError]: #rowdecodingerror
[Transactions and Savepoints]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions
[`DatabaseQueue`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
[Database queues]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.5.0</string>
<string>7.6.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -22,7 +22,10 @@ private struct PlayerWithRequiredTeam: FetchableRecord {
init(row: Row) throws {
player = try Player(row: row)
team = row[Player.teamScope]
let subscriptTeam: Team = row[Player.teamScope]
let decodedTeam: Team = try row.decode(forKey: Player.teamScope)
XCTAssertEqual(subscriptTeam.id, decodedTeam.id)
team = subscriptTeam
}
}
@@ -32,7 +35,10 @@ private struct PlayerWithOptionalTeam: FetchableRecord {
init(row: Row) throws {
player = try Player(row: row)
team = row[Player.teamScope]
let subscriptTeam: Team? = row[Player.teamScope]
let decodedTeam: Team? = try row.decodeIfPresent(forKey: Player.teamScope)
XCTAssertEqual(subscriptTeam?.id, decodedTeam?.id)
team = subscriptTeam
}
}
@@ -126,7 +126,7 @@ extension DatabaseDataDecodingStrategyTests {
XCTFail("Unexpected Data")
}
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Data from database value "invalid" - \
@@ -208,7 +208,7 @@ extension DatabaseDateDecodingStrategyTests {
XCTFail("Unexpected Date")
}
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "Yesterday" - \
@@ -254,7 +254,7 @@ extension DatabaseDateDecodingStrategyTests {
} catch let error as RowDecodingError {
// Decoding from DatabaseValue does not work:
// "Yesterday" is not decoded as 0.
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "Yesterday" - \
@@ -298,7 +298,7 @@ extension DatabaseDateDecodingStrategyTests {
} catch let error as RowDecodingError {
// Decoding from DatabaseValue does not work:
// "Yesterday" is not decoded as 0.
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "Yesterday" - \
@@ -352,7 +352,7 @@ extension DatabaseDateDecodingStrategyTests {
} catch let error as RowDecodingError {
// Decoding from DatabaseValue does not work:
// "Yesterday" is not decoded as 0.
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "Yesterday" - \
@@ -397,7 +397,7 @@ extension DatabaseDateDecodingStrategyTests {
XCTFail("Unexpected Date")
}
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "Yesterday" - \
@@ -443,7 +443,7 @@ extension DatabaseDateDecodingStrategyTests {
XCTFail("Unexpected Date")
}
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "Yesterday" - \
@@ -480,7 +480,7 @@ extension DatabaseDateDecodingStrategyTests {
XCTFail("Unexpected Date")
}
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value "invalid" - \
+46 -14
View File
@@ -1,6 +1,8 @@
import XCTest
import GRDB
@TaskLocal private var localUUID = UUID()
class DatabaseReaderTests : GRDBTestCase {
func testAnyDatabaseReader() throws {
// This test passes if this code compiles.
@@ -342,6 +344,42 @@ class DatabaseReaderTests : GRDBTestCase {
#endif
}
// MARK: - Task locals
func testReadCanAccessTaskLocal() async throws {
func test(_ dbReader: some DatabaseReader) async throws {
let expectedUUID = UUID()
let dbUUID = try await $localUUID.withValue(expectedUUID) {
try await dbReader.read { db in localUUID }
}
XCTAssertEqual(dbUUID, expectedUUID)
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(makeDatabasePool().makeSnapshot())
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try await test(makeDatabasePool().makeSnapshotPool())
#endif
}
func testUnsafeReadCanAccessTaskLocal() async throws {
func test(_ dbReader: some DatabaseReader) async throws {
let expectedUUID = UUID()
let dbUUID = try await $localUUID.withValue(expectedUUID) {
try await dbReader.unsafeRead { db in localUUID }
}
XCTAssertEqual(dbUUID, expectedUUID)
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(makeDatabasePool().makeSnapshot())
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try await test(makeDatabasePool().makeSnapshotPool())
#endif
}
// MARK: - Task Cancellation
func test_read_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws {
@@ -379,7 +417,7 @@ class DatabaseReaderTests : GRDBTestCase {
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
func test_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test_successful_read_is_not_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test(_ dbReader: some DatabaseReader) async throws {
let semaphore = AsyncSemaphore(value: 0)
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
@@ -387,17 +425,14 @@ class DatabaseReaderTests : GRDBTestCase {
await semaphore.wait()
try await dbReader.read { db in
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
XCTAssertTrue(Task.isCancelled)
}
}
cancelledTaskMutex.store(task)
semaphore.signal()
do {
try await task.value
XCTFail("Expected error")
} catch {
XCTAssert(error is CancellationError)
}
// Task has completed without any error
try await task.value
// Database access is restored after cancellation (no error is thrown)
try await dbReader.read { db in
@@ -530,7 +565,7 @@ class DatabaseReaderTests : GRDBTestCase {
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
func test_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test_successful_unsafeRead_is_not_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test(_ dbReader: some DatabaseReader) async throws {
let semaphore = AsyncSemaphore(value: 0)
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
@@ -538,17 +573,14 @@ class DatabaseReaderTests : GRDBTestCase {
await semaphore.wait()
try await dbReader.unsafeRead { db in
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
XCTAssertTrue(Task.isCancelled)
}
}
cancelledTaskMutex.store(task)
semaphore.signal()
do {
try await task.value
XCTFail("Expected error")
} catch {
XCTAssert(error is CancellationError)
}
// Task has completed without any error
try await task.value
// Database access is restored after cancellation (no error is thrown)
try await dbReader.unsafeRead { db in
@@ -7,7 +7,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
var name: String
init(row: Row) throws {
name = try row.decode(forKey: "name")
name = try row.decode(forColumn: "name")
}
}
@@ -23,7 +23,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil])
@@ -44,7 +44,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil])
@@ -74,7 +74,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
@@ -94,7 +94,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
@@ -123,7 +123,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
var value: Value
init(row: Row) throws {
value = try row.decode(forKey: "value")
value = try row.decode(forColumn: "value")
}
}
@@ -139,7 +139,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["1": 1, "value": "invalid"])
@@ -160,7 +160,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["1": 1, "value": "invalid"])
@@ -190,7 +190,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
@@ -210,7 +210,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
@@ -248,7 +248,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -269,7 +269,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -299,7 +299,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
@@ -319,7 +319,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
@@ -360,7 +360,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["name": nil, "value": "invalid"])
@@ -381,7 +381,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["name": nil, "value": "invalid"])
@@ -411,7 +411,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
@@ -431,7 +431,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
@@ -484,7 +484,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -521,7 +521,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
@@ -541,7 +541,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
@@ -571,7 +571,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try String.fetchAll(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -592,10 +592,10 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(String.self, forKey: "name")
_ = try row.decode(String.self, forColumn: "name")
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -617,7 +617,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try row.decode(String.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -644,11 +644,11 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
do {
_ = try Row.fetchCursor(statement)
.map { try $0.decode(Int8.self, forKey: "missing") }
.map { try $0.decode(Int8.self, forColumn: "missing") }
.next()
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("missing"))
XCTAssertEqual(context.key, nil)
@@ -670,7 +670,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Int8.fetchAll(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["foo": 1000])
@@ -691,10 +691,10 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(Int8.self, forKey: "foo")
_ = try row.decode(Int8.self, forColumn: "foo")
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["foo": 1000])
@@ -716,7 +716,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try row.decode(Int8.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["foo": 1000])
@@ -749,7 +749,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Value.fetchAll(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -772,7 +772,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -793,10 +793,10 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(Value.self, forKey: "name")
_ = try row.decode(Value.self, forColumn: "name")
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -818,7 +818,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try row.decode(Value.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
@@ -840,7 +840,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase {
_ = try row.decode(Value.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["team": "invalid"])
+52 -14
View File
@@ -1,6 +1,8 @@
import XCTest
import GRDB
@TaskLocal private var localUUID = UUID()
class DatabaseWriterTests : GRDBTestCase {
func testDatabaseQueueUnsafeReentrantWrite() throws {
@@ -413,6 +415,48 @@ class DatabaseWriterTests : GRDBTestCase {
try await test(makeDatabasePool())
}
// MARK: - Task locals
func test_write_can_access_task_local() async throws {
func test<T: DatabaseWriter>(_ dbWriter: T) async throws {
let expectedUUID = UUID()
let dbUUID = try await $localUUID.withValue(expectedUUID) {
try await dbWriter.write { db in localUUID }
}
XCTAssertEqual(dbUUID, expectedUUID)
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
}
func test_writeWithoutTransaction_can_access_task_local() async throws {
func test<T: DatabaseWriter>(_ dbWriter: T) async throws {
let expectedUUID = UUID()
let dbUUID = try await $localUUID.withValue(expectedUUID) {
try await dbWriter.writeWithoutTransaction { db in localUUID }
}
XCTAssertEqual(dbUUID, expectedUUID)
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
}
func test_barrierWriteWithoutTransaction_can_access_task_local() async throws {
func test<T: DatabaseWriter>(_ dbWriter: T) async throws {
let expectedUUID = UUID()
let dbUUID = try await $localUUID.withValue(expectedUUID) {
try await dbWriter.barrierWriteWithoutTransaction { db in localUUID }
}
XCTAssertEqual(dbUUID, expectedUUID)
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
}
// MARK: - Task Cancellation
// Regression test for <https://github.com/groue/GRDB.swift/issues/1715>.
@@ -496,7 +540,7 @@ class DatabaseWriterTests : GRDBTestCase {
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test_successful_writeWithoutTransaction_is_not_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test(_ dbWriter: some DatabaseWriter) async throws {
let semaphore = AsyncSemaphore(value: 0)
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
@@ -504,17 +548,14 @@ class DatabaseWriterTests : GRDBTestCase {
await semaphore.wait()
try await dbWriter.writeWithoutTransaction { db in
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
XCTAssertTrue(Task.isCancelled)
}
}
cancelledTaskMutex.store(task)
semaphore.signal()
do {
try await task.value
XCTFail("Expected error")
} catch {
XCTAssert(error is CancellationError)
}
// Task has completed without any error
try await task.value
// Database access is restored after cancellation (no error is thrown)
try await dbWriter.writeWithoutTransaction { db in
@@ -758,7 +799,7 @@ class DatabaseWriterTests : GRDBTestCase {
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
func test_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test_successful_barrierWriteWithoutTransaction_is_not_cancelled_by_Task_cancellation_performed_after_database_access() async throws {
func test(_ dbWriter: some DatabaseWriter) async throws {
let semaphore = AsyncSemaphore(value: 0)
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
@@ -766,17 +807,14 @@ class DatabaseWriterTests : GRDBTestCase {
await semaphore.wait()
try await dbWriter.barrierWriteWithoutTransaction { db in
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
XCTAssertTrue(Task.isCancelled)
}
}
cancelledTaskMutex.store(task)
semaphore.signal()
do {
try await task.value
XCTFail("Expected error")
} catch {
XCTAssert(error is CancellationError)
}
// Task has completed without any error
try await task.value
// Database access is restored after cancellation (no error is thrown)
try await dbWriter.barrierWriteWithoutTransaction { db in
@@ -376,7 +376,7 @@ extension FetchableRecordDecodableTests {
_ = try StructWithData(row: ["data": nil])
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Data from database value NULL - \
@@ -395,7 +395,7 @@ extension FetchableRecordDecodableTests {
}
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Data from database value NULL - \
@@ -439,7 +439,7 @@ extension FetchableRecordDecodableTests {
_ = try StructWithDate(row: ["date": nil])
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value NULL - \
@@ -458,7 +458,7 @@ extension FetchableRecordDecodableTests {
}
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
switch error.impl {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value NULL - \
@@ -1050,9 +1050,13 @@ extension FetchableRecordDecodableTests {
"optionalDates2": "[128000]",
])
XCTFail("Expected error")
} catch let RowDecodingError.keyNotFound(.columnName(column), context) {
XCTAssertEqual(column, "requiredId")
XCTAssertEqual(context.debugDescription, "column not found: \"requiredId\"")
} catch let error as RowDecodingError {
if case let .keyNotFound(.columnName(column), context) = error.impl {
XCTAssertEqual(column, "requiredId")
XCTAssertEqual(context.debugDescription, "column not found: \"requiredId\"")
} else {
XCTFail("Unexpected error")
}
}
}
@@ -1163,12 +1167,16 @@ extension FetchableRecordDecodableTests {
"optional_dates2": "[128000]",
])
XCTFail("Expected error")
} catch let RowDecodingError.keyNotFound(.columnName(column), context) {
XCTAssertEqual(column, "requiredId")
XCTAssertEqual(context.debugDescription, """
key not found: CodingKeys(stringValue: "requiredId", intValue: nil) ("requiredId"), \
converted to required_id
""")
} catch let error as RowDecodingError {
if case let .keyNotFound(.columnName(column), context) = error.impl {
XCTAssertEqual(column, "requiredId")
XCTAssertEqual(context.debugDescription, """
key not found: CodingKeys(stringValue: "requiredId", intValue: nil) ("requiredId"), \
converted to required_id
""")
} else {
XCTFail("Unexpected error")
}
}
do {
@@ -1180,13 +1188,17 @@ extension FetchableRecordDecodableTests {
"optional_dates2": "[128000]",
])
XCTFail("Expected error")
} catch let RowDecodingError.keyNotFound(.columnName(column), context) {
XCTAssertEqual(column, "requiredID")
XCTAssertEqual(context.debugDescription, """
key not found: CodingKeys(stringValue: "requiredID", intValue: nil) ("requiredID"), \
with divergent representation requiredId, \
converted to required_id
""")
} catch let error as RowDecodingError {
if case let .keyNotFound(.columnName(column), context) = error.impl {
XCTAssertEqual(column, "requiredID")
XCTAssertEqual(context.debugDescription, """
key not found: CodingKeys(stringValue: "requiredID", intValue: nil) ("requiredID"), \
with divergent representation requiredId, \
converted to required_id
""")
} else {
XCTFail("Unexpected error")
}
}
}
@@ -1264,11 +1276,15 @@ extension FetchableRecordDecodableTests {
"_optionalDates2": "[128000]",
])
XCTFail("Expected error")
} catch let RowDecodingError.keyNotFound(.columnName(column), context) {
XCTAssertEqual(column, "requiredId")
XCTAssertEqual(context.debugDescription, """
key not found: CodingKeys(stringValue: "requiredId", intValue: nil) ("requiredId")
""")
} catch let error as RowDecodingError {
if case let .keyNotFound(.columnName(column), context) = error.impl {
XCTAssertEqual(column, "requiredId")
XCTAssertEqual(context.debugDescription, """
key not found: CodingKeys(stringValue: "requiredId", intValue: nil) ("requiredId")
""")
} else {
XCTFail("Unexpected error")
}
}
}
}
+18 -18
View File
@@ -42,14 +42,14 @@ class AdapterRowTests : RowTestCase {
assertRowRawValueEqual(row, index: 2, value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, index: 0, value: 0 as Int)
assertRowConvertedValueEqual(row, index: 1, value: 1 as Int)
assertRowConvertedValueEqual(row, index: 2, value: 2 as Int)
try assertRowConvertedValueEqual(row, index: 0, value: 0 as Int)
try assertRowConvertedValueEqual(row, index: 1, value: 1 as Int)
try assertRowConvertedValueEqual(row, index: 2, value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a)
assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b)
assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c)
try assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a)
try assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b)
try assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c)
// Expect fatal error:
//
@@ -70,14 +70,14 @@ class AdapterRowTests : RowTestCase {
assertRowRawValueEqual(row, name: "c", value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
try assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
try assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
try assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
try assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
try assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
try assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
}
}
@@ -93,14 +93,14 @@ class AdapterRowTests : RowTestCase {
assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
try assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
try assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
try assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
try assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
try assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
try assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
}
}
@@ -44,14 +44,14 @@ class RowCopiedFromStatementTests: RowTestCase {
assertRowRawValueEqual(row, index: 2, value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, index: 0, value: 0 as Int)
assertRowConvertedValueEqual(row, index: 1, value: 1 as Int)
assertRowConvertedValueEqual(row, index: 2, value: 2 as Int)
try assertRowConvertedValueEqual(row, index: 0, value: 0 as Int)
try assertRowConvertedValueEqual(row, index: 1, value: 1 as Int)
try assertRowConvertedValueEqual(row, index: 2, value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a)
assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b)
assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c)
try assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a)
try assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b)
try assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c)
// Expect fatal error:
//
@@ -73,14 +73,14 @@ class RowCopiedFromStatementTests: RowTestCase {
assertRowRawValueEqual(row, name: "c", value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
try assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
try assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
try assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
try assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
try assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
try assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
}
}
@@ -97,14 +97,14 @@ class RowCopiedFromStatementTests: RowTestCase {
assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
try assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
try assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
try assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
try assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
try assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
try assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
}
}
@@ -39,7 +39,7 @@ class RowFromDictionaryLiteralTests : RowTestCase {
XCTAssertEqual(row["a"] as Int, 0)
}
func testRowValueAtIndex() {
func testRowValueAtIndex() throws {
let row: Row = ["a": 0, "b": 1, "c": 2]
let aIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "a" })!)
@@ -52,14 +52,14 @@ class RowFromDictionaryLiteralTests : RowTestCase {
assertRowRawValueEqual(row, index: cIndex, value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, index: aIndex, value: 0 as Int)
assertRowConvertedValueEqual(row, index: bIndex, value: 1 as Int)
assertRowConvertedValueEqual(row, index: cIndex, value: 2 as Int)
try assertRowConvertedValueEqual(row, index: aIndex, value: 0 as Int)
try assertRowConvertedValueEqual(row, index: bIndex, value: 1 as Int)
try assertRowConvertedValueEqual(row, index: cIndex, value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, index: aIndex, value: CustomValue.a)
assertRowConvertedValueEqual(row, index: bIndex, value: CustomValue.b)
assertRowConvertedValueEqual(row, index: cIndex, value: CustomValue.c)
try assertRowConvertedValueEqual(row, index: aIndex, value: CustomValue.a)
try assertRowConvertedValueEqual(row, index: bIndex, value: CustomValue.b)
try assertRowConvertedValueEqual(row, index: cIndex, value: CustomValue.c)
// Expect fatal error:
//
@@ -67,7 +67,7 @@ class RowFromDictionaryLiteralTests : RowTestCase {
// row[3]
}
func testRowValueNamed() {
func testRowValueNamed() throws {
let row: Row = ["a": 0, "b": 1, "c": 2]
// Raw extraction
@@ -76,17 +76,17 @@ class RowFromDictionaryLiteralTests : RowTestCase {
assertRowRawValueEqual(row, name: "c", value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
try assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
try assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
try assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
try assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
try assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
try assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
}
func testRowValueFromColumn() {
func testRowValueFromColumn() throws {
let row: Row = ["a": 0, "b": 1, "c": 2]
// Raw extraction
@@ -95,14 +95,14 @@ class RowFromDictionaryLiteralTests : RowTestCase {
assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
try assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
try assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
try assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
try assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
try assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
try assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
}
func testWithUnsafeData() throws {
+21 -21
View File
@@ -26,7 +26,7 @@ class RowFromDictionaryTests : RowTestCase {
XCTAssertEqual(bools, [false, true, true])
}
func testRowValueAtIndex() {
func testRowValueAtIndex() throws {
let dictionary: [String: (any DatabaseValueConvertible)?] = ["a": 0, "b": 1, "c": 2]
let row = Row(dictionary)
@@ -40,14 +40,14 @@ class RowFromDictionaryTests : RowTestCase {
assertRowRawValueEqual(row, index: cIndex, value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, index: aIndex, value: 0 as Int)
assertRowConvertedValueEqual(row, index: bIndex, value: 1 as Int)
assertRowConvertedValueEqual(row, index: cIndex, value: 2 as Int)
try assertRowConvertedValueEqual(row, index: aIndex, value: 0 as Int)
try assertRowConvertedValueEqual(row, index: bIndex, value: 1 as Int)
try assertRowConvertedValueEqual(row, index: cIndex, value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, index: aIndex, value: CustomValue.a)
assertRowConvertedValueEqual(row, index: bIndex, value: CustomValue.b)
assertRowConvertedValueEqual(row, index: cIndex, value: CustomValue.c)
try assertRowConvertedValueEqual(row, index: aIndex, value: CustomValue.a)
try assertRowConvertedValueEqual(row, index: bIndex, value: CustomValue.b)
try assertRowConvertedValueEqual(row, index: cIndex, value: CustomValue.c)
// Expect fatal error:
//
@@ -55,7 +55,7 @@ class RowFromDictionaryTests : RowTestCase {
// row[3]
}
func testRowValueNamed() {
func testRowValueNamed() throws {
let row = Row(["a": 0, "b": 1, "c": 2])
// Raw extraction
@@ -64,17 +64,17 @@ class RowFromDictionaryTests : RowTestCase {
assertRowRawValueEqual(row, name: "c", value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
try assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
try assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
try assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
try assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
try assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
try assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
}
func testRowValueFromColumn() {
func testRowValueFromColumn() throws {
let row = Row(["a": 0, "b": 1, "c": 2])
// Raw extraction
@@ -83,14 +83,14 @@ class RowFromDictionaryTests : RowTestCase {
assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
try assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
try assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
try assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
try assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
try assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
try assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
}
func testWithUnsafeData() throws {
+18 -18
View File
@@ -51,14 +51,14 @@ class RowFromStatementTests : RowTestCase {
assertRowRawValueEqual(row, index: 2, value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, index: 0, value: 0 as Int)
assertRowConvertedValueEqual(row, index: 1, value: 1 as Int)
assertRowConvertedValueEqual(row, index: 2, value: 2 as Int)
try assertRowConvertedValueEqual(row, index: 0, value: 0 as Int)
try assertRowConvertedValueEqual(row, index: 1, value: 1 as Int)
try assertRowConvertedValueEqual(row, index: 2, value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a)
assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b)
assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c)
try assertRowConvertedValueEqual(row, index: 0, value: CustomValue.a)
try assertRowConvertedValueEqual(row, index: 1, value: CustomValue.b)
try assertRowConvertedValueEqual(row, index: 2, value: CustomValue.c)
// Expect fatal error:
//
@@ -85,14 +85,14 @@ class RowFromStatementTests : RowTestCase {
assertRowRawValueEqual(row, name: "c", value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
try assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
try assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
try assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
try assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
try assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
try assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
}
XCTAssertTrue(rowFetched)
}
@@ -114,14 +114,14 @@ class RowFromStatementTests : RowTestCase {
assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
try assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
try assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
try assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
try assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
try assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
try assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
}
XCTAssertTrue(rowFetched)
}
+46 -8
View File
@@ -5,8 +5,10 @@ class RowTestCase: GRDBTestCase {
func assertRowRawValueEqual<T: Equatable>(_ row: Row, index: Int, value: T) {
// form 1
let v = row[index]
XCTAssertEqual(v as! T, value)
do {
let v = row[index]
XCTAssertEqual(v as! T, value)
}
// form 2
XCTAssertEqual(row[index] as! T, value)
@@ -51,7 +53,7 @@ class RowTestCase: GRDBTestCase {
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, index: Int, value: T) {
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, index: Int, value: T) throws {
// form 1
XCTAssertEqual(row[index] as T, value)
@@ -67,9 +69,15 @@ class RowTestCase: GRDBTestCase {
} else {
XCTFail("expected successful extraction")
}
// form 5
try XCTAssertEqual(row.decode(T.self, atIndex: index), value)
// form 6
try XCTAssertEqual(row.decode(atIndex: index) as T, value)
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, name: String, value: T) {
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, name: String, value: T) throws {
// form 1
XCTAssertEqual(row[name] as T, value)
@@ -85,9 +93,15 @@ class RowTestCase: GRDBTestCase {
} else {
XCTFail("expected successful extraction")
}
// form 5
try XCTAssertEqual(row.decode(T.self, forColumn: name), value)
// form 6
try XCTAssertEqual(row.decode(forColumn: name) as T, value)
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, column: Column, value: T) {
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, column: Column, value: T) throws {
// form 1
XCTAssertEqual(row[column] as T, value)
@@ -103,9 +117,15 @@ class RowTestCase: GRDBTestCase {
} else {
XCTFail("expected successful extraction")
}
// form 5
try XCTAssertEqual(row.decode(T.self, forColumn: column), value)
// form 6
try XCTAssertEqual(row.decode(forColumn: column) as T, value)
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, index: Int, value: T) {
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, index: Int, value: T) throws {
// form 1
XCTAssertEqual(row[index] as T, value)
@@ -121,9 +141,15 @@ class RowTestCase: GRDBTestCase {
} else {
XCTFail("expected successful extraction")
}
// form 5
try XCTAssertEqual(row.decode(T.self, atIndex: index), value)
// form 6
try XCTAssertEqual(row.decode(atIndex: index) as T, value)
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, name: String, value: T) {
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, name: String, value: T) throws {
// form 1
XCTAssertEqual(row[name] as T, value)
@@ -139,9 +165,15 @@ class RowTestCase: GRDBTestCase {
} else {
XCTFail("expected successful extraction")
}
// form 5
try XCTAssertEqual(row.decode(T.self, forColumn: name), value)
// form 6
try XCTAssertEqual(row.decode(forColumn: name) as T, value)
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, column: Column, value: T) {
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, column: Column, value: T) throws {
// form 1
XCTAssertEqual(row[column] as T, value)
@@ -157,5 +189,11 @@ class RowTestCase: GRDBTestCase {
} else {
XCTFail("expected successful extraction")
}
// form 5
try XCTAssertEqual(row.decode(T.self, forColumn: column), value)
// form 6
try XCTAssertEqual(row.decode(forColumn: column) as T, value)
}
}