Compare commits

...
Author SHA1 Message Date
Gwendal Roué dffc4bbe5d More Swift 6 paranoid tests 2025-12-31 12:29:59 +01:00
Gwendal Roué aa28797f67 Swift 6 record tests 2025-12-30 16:52:04 +01:00
Gwendal Roué fe59d44499 Swift 6 test targets 2025-12-30 13:01:09 +01:00
Gwendal Roué 064eb9dea2 DatabaseWriter.write accepts a sending closure 2025-12-30 13:01:09 +01:00
Gwendal Roué 7bb5c636e7 DatabaseWriter.barrierWriteWithoutTransaction accepts a sending closure 2025-12-30 13:01:09 +01:00
Gwendal Roué 080f9275cc DatabaseWriter.writeWithoutTransaction accepts a sending closure 2025-12-30 13:01:09 +01:00
Gwendal Roué aadc73cc11 DatabaseReader.unsafeRead accepts a sending closure 2025-12-30 13:01:09 +01:00
Gwendal Roué 2024f857a0 DatabaseReader.read accepts a sending closure 2025-12-30 13:01:09 +01:00
Gwendal Roué 129e53d54e Remove obsolete TODOs 2025-12-30 13:00:56 +01:00
Gwendal Roué bc5dd31366 Fix Swiftlint warnings 2025-12-30 10:31:13 +01:00
Gwendal Roué aa0079aeb8 Merge branch 'development' 2025-12-13 12:11:32 +01:00
Gwendal Roué 74ef238376 v7.9.0 2025-12-13 12:05:31 +01:00
Gwendal Roué 9d7a487971 Merge pull request #1839 from groue/dev/issue-1838
Fix cancellation of async tasks that use the FTS5 full-text engine.
2025-12-10 16:11:32 +01:00
Gwendal Roué ac2f2e8643 Test that we recover from the FTS5 bug 2025-12-10 13:38:25 +01:00
Gwendal Roué e281149a2d Simplify Issue1838Tests
... and add it to test targets
2025-12-10 13:28:04 +01:00
Gwendal Roué 3ee256e7e8 Common API for statements that must ignore interruption errors 2025-12-09 21:39:20 +01:00
Gwendal Roué 361599aacd Task cancellation should turn all SQLITE_INTERRUPT errors into CancellationError, including errors thrown by statement compilation
I did not know statement compilation could fail when database is interrupted until #1838. A ROLLBACK statement would not even compile due to the FTS5 statement leak reported in https://sqlite.org/forum/forumpost/137c7662b389fa18
2025-12-09 21:38:15 +01:00
Gwendal Roué 64a024097d Fix failing test for #1838 by reseting all prepared statements before retrying 2025-12-08 21:40:48 +01:00
Gwendal Roué 60ea10948b Protect PRAGMA query_only = 0 against SQLITE_INTERRUPT
This should fix a race condition about cancellation that happens during a read-only access.
2025-12-08 21:22:43 +01:00
Gwendal Roué 5dba64d545 Retry a rollback in case of SQLITE_INTERRUPT error
This should fix a race condition about cancellation that happens during a rollback
2025-12-08 21:11:26 +01:00
Gwendal Roué 2212a17950 Failing test for #1838 2025-12-08 15:13:28 +01:00
Gwendal Roué 24fa06d646 Merge branch 'master' into development 2025-12-08 09:51:07 +01:00
Gwendal Roué fd788900b6 Revert "Add link to our beloved sponsor Base"
This reverts commit 827ab62bb6.
2025-12-08 09:50:02 +01:00
Gwendal Roué b31be05ee3 Do not use traits, since they are not supported by Xcode
This pull request fixes #1826, which broke `make test_GRDBDemo` with Xcode 26.0.1.

To reproduce the failure:

- Remove from ~/Library/Developer/Xcode/DerivedData all previous builds of GRDB and related stuff
- Run `make distclean test_GRDBDemo`

We expect a success, but it fails with error "Unable to find module dependency: 'GRDBSQLite'".
2025-10-27 13:37:21 +01:00
35 changed files with 1025 additions and 107 deletions

No files matched your search

+33 -1
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.9.x` Releases - [7.9.0](#790)
- `7.8.x` Releases - [7.8.0](#780)
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
@@ -140,6 +141,37 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.9.0
Released December 13, 2025
- **Breaking Change**: Simplify the compiler checks for the availability of SQLite snapshots by [@groue](https://github.com/groue) in [#1826](https://github.com/groue/GRDB.swift/pull/1826)
This change aims at easing Linux and Android compatibility.
**The library requirements are raised to Swift 6.1+, Xcode 16.3+.**
- **Breaking Change**: Accept multiple SQLCipher libraries by [@groue](https://github.com/groue) in [#1819](https://github.com/groue/GRDB.swift/pull/1819)
This change aims at easing building GRDB against various SQLCipher flavors.
**The compiler flag that enables new GRDB APIs for SQLCipher is now `SQLITE_HAS_CODEC`.**
- **Fixed**: Fix cancellation of async tasks that use the FTS5 full-text engine by [@groue](https://github.com/groue) in [#1839](https://github.com/groue/GRDB.swift/pull/1839)
This workarounds an [SQLite bug](https://sqlite.org/forum/forumpost/95413eb410) that would trigger a GRDB crash, and improves the robustness of the library regarding database accesses cancellation and database interruption.
- **New**: Improve the ergonomics of `DatabaseMigrator.registerMigration(_:foreignKeyChecks:merging:migrate)`, introduced in [#1818](https://github.com/groue/GRDB.swift/pull/1818), by accepting that the name of the merged migration is included in the set of merged migrations:
```swift
// Used to fail, now OK:
migrator.registerMigration("v3", merging: ["v1", "v2", "v3"]) { ... }
// ~~~~ ~~~~
// The above code is equivalent to:
migrator.registerMigration("v3", merging: ["v1", "v2"]) { ... }
```
## 7.8.0
Released October 2, 2025
@@ -4370,7 +4402,7 @@ Released April 3, 2017
**Breaking Changes**
- SQLite C API is now available right from the GRBD module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
- SQLite C API is now available right from the GRDB module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
- The [manual installation procedure for WatchOS extensions](https://github.com/groue/GRDB.swift#installation) has changed.
- [Carthage](https://github.com/Carthage/Carthage) is no longer supported. At the present time it is unable to support the various frameworks built by GRDB (system SQLite, SQLCipher, custom SQLite builds, etc.)
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.8.0'
s.version = '7.9.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+4
View File
@@ -292,6 +292,7 @@
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
56C7979B2EE99BD000AA265D /* Issue1838Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; };
@@ -802,6 +803,7 @@
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Issue1838Tests.swift; sourceTree = "<group>"; };
56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
@@ -1448,6 +1450,7 @@
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */,
5698ACCA1DA62A2D0056AF8C /* FTS5TokenizerTests.swift */,
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */,
56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */,
);
name = FTS;
sourceTree = "<group>";
@@ -2130,6 +2133,7 @@
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
56C7979B2EE99BD000AA265D /* Issue1838Tests.swift in Sources */,
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
+21
View File
@@ -513,6 +513,27 @@ extension Database {
publicStatementArguments: configuration.publicStatementArguments)
}
/// Always throws an error
func statementCompilationDidFail(
at statementStart: UnsafePointer<CChar>,
withResultCode resultCode: CInt
) throws -> Never {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
// The only error that a user sees when a Task is cancelled
// is CancellationError.
try suspensionMutex.load().checkCancellation()
default:
break
}
// Throw compilation failure
throw DatabaseError(
resultCode: resultCode,
message: lastErrorMessage,
sql: String(cString: statementStart))
}
private func checkForAutocommitTransition() {
if sqlite3_get_autocommit(sqliteConnection) == 0 {
if autocommitState == .on {
+58 -2
View File
@@ -863,7 +863,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
readOnlyDepth -= 1
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
if readOnlyDepth == 0 {
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
// We MUST ignore interruptions when we leave the read-only mode,
// otherwise user could not write with this database
// connection again.
//
// It's OK to ignore interruption, since interruption is
// concurrent and we can pretend it occurred before or after
// the PRAGMA.
try ignoringInterruption {
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
}
}
}
@@ -1300,6 +1309,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return try value()
}
/// Returns the result of `value`. If `value` throws an interruption
/// error, it is retried a second time.
func ignoringInterruption<T>(_ value: () throws -> T) rethrows -> T {
do {
return try value() // swiftlint:disable:next statement_position
}
catch is CancellationError,
DatabaseError.SQLITE_INTERRUPT,
DatabaseError.SQLITE_ABORT
{
// Maybe we were unlucky, and user has interrupted the database
// during `value` execution.
//
// Another possible cause for this error is the FTS5 bug
// described at <https://sqlite.org/forum/forumpost/137c7662b3>,
// which leaves the database in a sticky interrupted state.
// To workaround this bug, we must leave the interrupted state
// before retrying:
resetAllPreparedStatements()
// Retry
return try value()
}
}
/// Support for `checkForSuspensionViolation(from:)`
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
@@ -1764,7 +1798,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// which rollback errors should be ignored, and which rollback errors
// should be exposed to the library user.
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
// We MUST ignore interruptions during the rollback, otherwise
// we could leave a transaction open, and trigger a fatal error in
// `SerializedDatabase.preconditionNoUnsafeTransactionLeft`.
//
// It's OK to ignore interruption, since interruption is
// concurrent and we can pretend it occurred before or after
// the rollback.
try ignoringInterruption {
try execute(sql: "ROLLBACK TRANSACTION")
}
}
assert(!isInsideTransaction)
}
@@ -1779,6 +1822,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
}
/// Resets all prepared statements.
///
/// This method helps clearing the interrupted state, as a workaround
/// for https://sqlite.org/forum/forumpost/137c7662b3, discovered
/// in https://github.com/groue/GRDB.swift/issues/1838.
func resetAllPreparedStatements() {
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
sqlite3_reset(stmt)
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
// MARK: - Memory Management
/// Frees as much memory as possible.
+59 -41
View File
@@ -352,29 +352,35 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
// Compiler does not see that value can be sent.
return try await withoutActuallyEscaping(value) { value in
typealias SendableClosure = @Sendable (Database) throws -> T
let value = unsafeBitCast(value, to: SendableClosure.self)
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
}
@@ -432,16 +438,22 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
return try await readerPool.get { reader in
try await reader.execute { db in
try db.clearSchemaCacheIfNeeded()
return try value(db)
// Compiler does not see that value can be sent.
return try await withoutActuallyEscaping(value) { value in
typealias SendableClosure = @Sendable (Database) throws -> T
let value = unsafeBitCast(value, to: SendableClosure.self)
return try await readerPool.get { reader in
try await reader.execute { db in
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
}
@@ -786,7 +798,7 @@ extension DatabasePool: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: sending (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -802,32 +814,38 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: sending (Database) throws -> T
) async throws -> T {
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 {
// Compiler does not see that updates can be sent.
return try await withoutActuallyEscaping(updates) { updates in
typealias SendableClosure = @Sendable (Database) throws -> T
let updates = unsafeBitCast(updates, to: SendableClosure.self)
// 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 writer.sync { db in
defer {
cancelMutex.store(nil)
db.uncancel()
}
cancelMutex.store(db.cancel)
return try await readerPool.barrier {
try Task.checkCancellation()
return try updates(db)
return try writer.sync { db in
defer {
cancelMutex.store(nil)
db.uncancel()
}
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try updates(db)
}
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
+4 -4
View File
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -278,7 +278,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
@@ -397,7 +397,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: sending (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -408,7 +408,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: sending (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
+4 -4
View File
@@ -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: @Sendable (Database) throws -> T
_ value: sending (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: @Sendable (Database) throws -> T
_ value: sending (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: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -669,7 +669,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
+2 -2
View File
@@ -159,7 +159,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
@@ -180,7 +180,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await read(value)
}
+2 -2
View File
@@ -297,7 +297,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -345,7 +345,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await read(value)
}
+7 -7
View File
@@ -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: @Sendable (Database) throws -> T
_ updates: sending (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: @Sendable (Database) throws -> T
_ updates: sending (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: @Sendable (Database) throws -> T
_ updates: sending (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: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -902,7 +902,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: sending (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
@@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: sending (Database) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@@ -947,7 +947,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: sending (Database) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
+19 -12
View File
@@ -250,22 +250,29 @@ final class SerializedDatabase {
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @Sendable (Database) throws -> T
_ block: sending (Database) throws -> T
) async throws -> T {
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try await actor.execute {
defer {
cancelMutex.store(nil)
db.uncancel()
preconditionNoUnsafeTransactionLeft(db)
// Compiler does not see that block can be sent.
return try await withoutActuallyEscaping(block) { block in
typealias SendableClosure = @Sendable (Database) throws -> T
let block = unsafeBitCast(block, to: SendableClosure.self)
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)
}
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try block(db)
} onCancel: {
cancelMutex.withLock { $0?() }
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
+1 -4
View File
@@ -150,10 +150,7 @@ public final class Statement {
&sqliteStatement, statementEnd)
guard code == SQLITE_OK else {
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: String(cString: statementStart))
try database.statementCompilationDidFail(at: statementStart, withResultCode: code)
}
guard let sqliteStatement else {
+4
View File
@@ -287,6 +287,7 @@
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; };
56C0539B22ACEECD0029D27D /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538E22ACEECD0029D27D /* Map.swift */; };
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
56C7979D2EE99BE900AA265D /* Issue1838Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */; };
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
@@ -814,6 +815,7 @@
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Issue1838Tests.swift; sourceTree = "<group>"; };
56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = "<group>"; };
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
@@ -1441,6 +1443,7 @@
5698AC3E1DA2BEBB0056AF8C /* FTS */ = {
isa = PBXGroup;
children = (
56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */,
5698AC3F1DA2BED90056AF8C /* FTS3PatternTests.swift */,
5698AC481DA2D48A0056AF8C /* FTS3RecordTests.swift */,
5698AC881DA389380056AF8C /* FTS3TableBuilderTests.swift */,
@@ -2374,6 +2377,7 @@
562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */,
565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */,
56C7979D2EE99BE900AA265D /* Issue1838Tests.swift in Sources */,
F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */,
F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */,
5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
+27 -13
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.1
// swift-tools-version:6.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import Foundation
@@ -14,12 +14,6 @@ let darwinPlatforms: [Platform] = [
]
var swiftSettings: [SwiftSetting] = [
.define("SQLITE_ENABLE_FTS5"),
// Until Xcode has proper support for package traits, we must enable
// SQLITE_ENABLE_SNAPSHOT by default so that Xcode projects that build
// a Darwin app can depend on GRDB and profit from WAL snapshots.
// Package traits who want to disable snapshots must set SQLITE_DISABLE_SNAPSHOT.
// TODO: when Xcode support traits, remove all mentions of SQLITE_DISABLE_SNAPSHOT and update as below:
// .define("SQLITE_ENABLE_SNAPSHOT", .when(platforms: darwinPlatforms, traits: ["GRDBSQLite"])),
.define("SQLITE_ENABLE_SNAPSHOT"),
]
var cSettings: [CSetting] = []
@@ -56,10 +50,6 @@ let package = Package(
.library(name: "GRDB", targets: ["GRDB"]),
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
],
traits: [
"GRDBSQLite",
.default(enabledTraits: ["GRDBSQLite"]),
],
dependencies: dependencies,
targets: [
.systemLibrary(
@@ -68,7 +58,7 @@ let package = Package(
.target(
name: "GRDB",
dependencies: [
.target(name: "GRDBSQLite", condition: .when(traits: ["GRDBSQLite"])),
.target(name: "GRDBSQLite"),
],
path: "GRDB",
resources: [.copy("PrivacyInfo.xcprivacy")],
@@ -90,6 +80,9 @@ let package = Package(
"Swift6Migration",
"generatePerformanceReport.rb",
"parsePerformanceTests.rb",
"Swift6ApprochableConcurrencyGRDBTests",
"Swift6DefaultGRDBTests",
"Swift6MainActorIsolationGRDBTests",
],
resources: [
.copy("GRDBTests/Betty.jpeg"),
@@ -102,7 +95,28 @@ let package = Package(
.swiftLanguageMode(.v5),
.enableUpcomingFeature("InferSendableFromCaptures"),
.enableUpcomingFeature("GlobalActorIsolatedTypesUsability"),
])
]),
.testTarget(
name: "Swift6ApprochableConcurrencyGRDBTests",
dependencies: ["GRDB"],
swiftSettings: [
.enableUpcomingFeature("NonisolatedNonsendingByDefault"),
.enableUpcomingFeature("InferIsolatedConformances")
]
),
.testTarget(
name: "Swift6DefaultGRDBTests",
dependencies: ["GRDB"]
),
.testTarget(
name: "Swift6MainActorIsolationGRDBTests",
dependencies: ["GRDB"],
swiftSettings: [
.defaultIsolation(MainActor.self),
.enableUpcomingFeature("NonisolatedNonsendingByDefault"),
.enableUpcomingFeature("InferIsolatedConformances")
]
),
],
swiftLanguageModes: [.v6]
)
+105
View File
@@ -0,0 +1,105 @@
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import Foundation
import PackageDescription
let darwinPlatforms: [Platform] = [
.iOS,
.macOS,
.macCatalyst,
.tvOS,
.visionOS,
.watchOS,
]
var swiftSettings: [SwiftSetting] = [
.define("SQLITE_ENABLE_FTS5"),
.define("SQLITE_ENABLE_SNAPSHOT"),
]
var cSettings: [CSetting] = []
var dependencies: [PackageDescription.Package.Dependency] = []
// Don't rely on those environment variables. They are ONLY testing conveniences:
// $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM
if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" {
swiftSettings.append(.define("SQLITE_ENABLE_PREUPDATE_HOOK"))
cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK"))
}
// The SPI_BUILDER environment variable enables documentation building
// on <https://swiftpackageindex.com/groue/GRDB.swift>. See
// <https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/2122>
// for more information.
//
// SPI_BUILDER also enables the `make docs-localhost` command.
if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" {
dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"))
}
let package = Package(
name: "GRDB",
defaultLocalization: "en", // for tests
platforms: [
.iOS(.v13),
.macOS(.v10_15),
.tvOS(.v13),
.watchOS(.v7),
],
products: [
.library(name: "GRDBSQLite", targets: ["GRDBSQLite"]),
.library(name: "GRDB", targets: ["GRDB"]),
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
],
dependencies: dependencies,
targets: [
.systemLibrary(
name: "GRDBSQLite",
providers: [.apt(["libsqlite3-dev"])]),
.target(
name: "GRDB",
dependencies: [
.target(name: "GRDBSQLite"),
],
path: "GRDB",
resources: [.copy("PrivacyInfo.xcprivacy")],
cSettings: cSettings,
swiftSettings: swiftSettings),
.testTarget(
name: "GRDBTests",
dependencies: ["GRDB"],
path: "Tests",
exclude: [
"CocoaPods",
"Crash",
"CustomSQLite",
"GRDBManualInstall",
"GRDBTests/getThreadsCount.c",
"Info.plist",
"Performance",
"SPM",
"Swift6Migration",
"generatePerformanceReport.rb",
"parsePerformanceTests.rb",
"Swift6ApprochableConcurrencyGRDBTests",
"Swift6DefaultGRDBTests",
"Swift6MainActorIsolationGRDBTests",
],
resources: [
.copy("GRDBTests/Betty.jpeg"),
.copy("GRDBTests/InflectionsTests.json"),
.copy("GRDBTests/Issue1383.sqlite"),
],
cSettings: cSettings,
swiftSettings: swiftSettings + [
// Tests still use the Swift 5 language mode.
.swiftLanguageMode(.v5),
.enableUpcomingFeature("InferSendableFromCaptures"),
.enableUpcomingFeature("GlobalActorIsolatedTypesUsability"),
]),
.testTarget(
name: "Swift6DefaultGRDBTests",
dependencies: ["GRDB"]
),
],
swiftLanguageModes: [.v6]
)
+1 -11
View File
@@ -15,17 +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>
---
<a href="https://menial.co.uk/base/"><img alt="Base: The best SQLite database editor for macOS" src="https://raw.githubusercontent.com/groue/GRDB.swift/master/Sponsors/base.png"></a>
<p align="center">
<strong>Thank you to <a href="https://menial.co.uk/base/">Base</a> for sponsoring GRDB</strong><br />Base is a small, powerful, comfortable SQLite editor for everyone on macOS.
</p>
---
**Latest release**: October 2, 2025 • [version 7.8.0](https://github.com/groue/GRDB.swift/tree/v7.8.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: December 13, 2025 • [version 7.9.0](https://github.com/groue/GRDB.swift/tree/v7.9.0) • [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.1+ / Xcode 16.3+
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.8.0</string>
<string>7.9.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+37
View File
@@ -896,4 +896,41 @@ class DatabaseWriterTests : GRDBTestCase {
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
// Regression test for https://github.com/groue/GRDB.swift/pull/1838
func test_cancellation_does_not_prevent_rollback() async throws {
func test(_ dbWriter: some DatabaseWriter) async throws {
// Numbers that have the test fail more or less reliably
// (on my machine) unless the #1838 patch is applied.
// When the test fails, we have a fatal error: A transaction has been left opened at the end of a database access.
let repeatCount = 400
let taskCount = 50
for _ in 0..<repeatCount {
try await withThrowingTaskGroup(of: Void.self) { group in
for _ in 0..<taskCount{
let task = Task {
try await dbWriter.writeWithoutTransaction { db in
try db.beginTransaction()
try db.rollback()
}
}
group.addTask {
Task {
// For the test to fail, we need to be lucky, here:
// Cancellation must occur during the compilation
// or the execution of the rollback statement.
task.cancel()
}
// Ignore expected CancellationError
try? await task.value
}
}
try await group.waitForAll()
}
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
}
+53
View File
@@ -0,0 +1,53 @@
import GRDB
import XCTest
class Issue1838Tests: GRDBTestCase {
/// Regression test for <https://github.com/groue/GRDB.swift/issues/1838>.
///
/// This test passes since <https://github.com/groue/GRDB.swift/pull/1839>
/// which workarounds the SQLite bug described at
/// <https://sqlite.org/forum/forumpost/95413eb410>.
func test_interrupted_rollback() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING FTS5(content)")
try db.inTransaction {
try db.execute(sql: "INSERT INTO documents(content) VALUES ('Document')")
dbQueue.interrupt()
return .rollback
}
}
let documentCount = try dbQueue.read { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents")!
}
XCTAssertEqual(documentCount, 0)
}
/// Tests about how we handle the FTS5 bug <https://sqlite.org/forum/forumpost/95413eb410>
func test_interrupted_commit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING FTS5(content)")
}
do {
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO documents(content) VALUES ('Document')")
dbQueue.interrupt()
}
// Do not assert that the above code throws, because the
// FTS5 bug might be fixed in the tested SQLite version.
} catch DatabaseError.SQLITE_INTERRUPT {
// Fine: That's the FTS5 bug.
}
// Make sure the interrupted state created by the FTS5 bug is no longer active.
let documentCount = try dbQueue.read { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents")!
}
XCTAssertEqual(documentCount, 0)
}
}
@@ -1,7 +1,6 @@
import XCTest
import GRDB
#warning("TODO: document the caveat that didInsert(with:) is unreliable due to last insert rowid not set by triggers: https://sqlite.org/c3ref/last_insert_rowid.html. See also https://sqlite.org/forum/forumpost/fb1c3b4a13")
private struct Player: Codable,
Equatable,
Identifiable,
@@ -598,7 +598,6 @@ class TableRecordUpdateTests: GRDBTestCase {
}
func testRequestUpdateAndFetchCursor_view() throws {
#warning("TODO: document this caveat")
// Mixing INSTEAD OF triggers and RETURNING used to trigger a bug
// that was fixed in SQLite 3.42. The SQLite test linked below
// landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16.
@@ -0,0 +1,69 @@
import GRDB
import Testing
private struct Player {
var id: Int64?
var name: String
}
extension Player: Codable, Identifiable { }
extension Player: FetchableRecord, TableRecord {
enum Columns {
static let name = Column(CodingKeys.name)
}
}
@Suite struct FetchableRecordTests {
@Test func fetch_record() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(name) VALUES ('Arthur')
""")
return try Player.fetchOne(db)
}
#expect(player?.name == "Arthur")
}
@Test func fetch_record_by_id() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(id, name) VALUES (42, 'Arthur')
""")
return try Player.find(db, id: 42)
}
#expect(player.name == "Arthur")
}
@Test func fetch_record_by_column() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(id, name) VALUES (42, 'Arthur')
""")
return try Player
.filter { $0.name == "Arthur" }
.fetchOne(db)
}
#expect(player?.id == 42)
}
}
@@ -0,0 +1,33 @@
import GRDB
import Testing
private struct Player {
var id: Int64?
var name: String
}
extension Player: Codable, Identifiable { }
extension Player: MutablePersistableRecord {
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@Suite struct MutablePersistableRecordTests {
@Test func insert_record() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
var player = Player(name: "Arthur")
try player.insert(db)
#expect(player.id == 1)
let playerCount = try Player.fetchCount(db)
#expect(playerCount == 1)
}
}
}
@@ -0,0 +1,66 @@
import GRDB
import Testing
private class NonSendable {
var value: Int
init(value: Int) {
self.value = value
}
}
@Suite struct NonSendableTests {
@Test func non_sendable_type_in_synchronous_database_access() throws {
let dbQueue = try DatabaseQueue()
let input = NonSendable(value: 0)
let output = try dbQueue.read { _ in
input
}
#expect(input === output)
}
@Test func non_sendable_type_sent_to_databaseReader_read() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.read { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseReader_unsafeRead() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.unsafeRead { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_barrierWriteWithoutTransaction() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.barrierWriteWithoutTransaction { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_write() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.write { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_writeWithoutTransaction() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.writeWithoutTransaction { _ in
nonSendable.value
}
#expect(value == 0)
}
}
@@ -0,0 +1,26 @@
import GRDB
import Testing
private struct Player {
var id: Int64
var name: String
}
extension Player: Codable, Identifiable { }
extension Player: PersistableRecord { }
@Suite struct PersistableRecordTests {
@Test func insert_record() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try Player(id: 1, name: "Arthur").insert(db)
let playerCount = try Player.fetchCount(db)
#expect(playerCount == 1)
}
}
}
@@ -0,0 +1,69 @@
import GRDB
import Testing
private struct Player {
var id: Int64?
var name: String
}
extension Player: Codable, Identifiable { }
extension Player: FetchableRecord, TableRecord {
enum Columns {
static let name = Column(CodingKeys.name)
}
}
@Suite struct FetchableRecordTests {
@Test func fetch_record() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(name) VALUES ('Arthur')
""")
return try Player.fetchOne(db)
}
#expect(player?.name == "Arthur")
}
@Test func fetch_record_by_id() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(id, name) VALUES (42, 'Arthur')
""")
return try Player.find(db, id: 42)
}
#expect(player.name == "Arthur")
}
@Test func fetch_record_by_column() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(id, name) VALUES (42, 'Arthur')
""")
return try Player
.filter { $0.name == "Arthur" }
.fetchOne(db)
}
#expect(player?.id == 42)
}
}
@@ -0,0 +1,33 @@
import GRDB
import Testing
private struct Player {
var id: Int64?
var name: String
}
extension Player: Codable, Identifiable { }
extension Player: MutablePersistableRecord {
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@Suite struct MutablePersistableRecordTests {
@Test func insert_record() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
var player = Player(name: "Arthur")
try player.insert(db)
#expect(player.id == 1)
let playerCount = try Player.fetchCount(db)
#expect(playerCount == 1)
}
}
}
@@ -0,0 +1,66 @@
import GRDB
import Testing
private class NonSendable {
var value: Int
init(value: Int) {
self.value = value
}
}
@Suite struct NonSendableTests {
@Test func non_sendable_type_in_synchronous_database_access() throws {
let dbQueue = try DatabaseQueue()
let input = NonSendable(value: 0)
let output = try dbQueue.read { _ in
input
}
#expect(input === output)
}
@Test func non_sendable_type_sent_to_databaseReader_read() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.read { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseReader_unsafeRead() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.unsafeRead { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_barrierWriteWithoutTransaction() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.barrierWriteWithoutTransaction { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_write() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.write { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_writeWithoutTransaction() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.writeWithoutTransaction { _ in
nonSendable.value
}
#expect(value == 0)
}
}
@@ -0,0 +1,26 @@
import GRDB
import Testing
private struct Player {
var id: Int64
var name: String
}
extension Player: Codable, Identifiable { }
extension Player: PersistableRecord { }
@Suite struct PersistableRecordTests {
@Test func insert_record() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try Player(id: 1, name: "Arthur").insert(db)
let playerCount = try Player.fetchCount(db)
#expect(playerCount == 1)
}
}
}
@@ -0,0 +1,69 @@
import GRDB
import Testing
nonisolated private struct Player: Codable {
var id: Int64?
var name: String
}
extension Player: nonisolated Identifiable { }
extension Player: nonisolated FetchableRecord, TableRecord {
nonisolated enum Columns {
static let name = Column(CodingKeys.name)
}
}
@Suite struct FetchableRecordTests {
@Test func fetch_record() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(name) VALUES ('Arthur')
""")
return try Player.fetchOne(db)
}
#expect(player?.name == "Arthur")
}
@Test func fetch_record_by_id() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(id, name) VALUES (42, 'Arthur')
""")
return try Player.find(db, id: 42)
}
#expect(player.name == "Arthur")
}
@Test func fetch_record_by_column() async throws {
let dbQueue = try DatabaseQueue()
let player = try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: """
INSERT INTO player(id, name) VALUES (42, 'Arthur')
""")
return try Player
.filter { $0.name == "Arthur" }
.fetchOne(db)
}
#expect(player?.id == 42)
}
}
@@ -0,0 +1,33 @@
import GRDB
import Testing
nonisolated private struct Player: Codable {
var id: Int64?
var name: String
}
extension Player: nonisolated Identifiable { }
extension Player: MutablePersistableRecord {
nonisolated mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@Suite struct MutablePersistableRecordTests {
@Test func insert_record() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
var player = Player(name: "Arthur")
try player.insert(db)
#expect(player.id == 1)
let playerCount = try Player.fetchCount(db)
#expect(playerCount == 1)
}
}
}
@@ -0,0 +1,66 @@
import GRDB
import Testing
nonisolated private class NonSendable {
var value: Int
init(value: Int) {
self.value = value
}
}
@Suite struct NonSendableTests {
@Test func non_sendable_type_in_synchronous_database_access() throws {
let dbQueue = try DatabaseQueue()
let input = NonSendable(value: 0)
let output = try dbQueue.read { _ in
input
}
#expect(input === output)
}
@Test func non_sendable_type_sent_to_databaseReader_read() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.read { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseReader_unsafeRead() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.unsafeRead { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_barrierWriteWithoutTransaction() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.barrierWriteWithoutTransaction { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_write() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.write { _ in
nonSendable.value
}
#expect(value == 0)
}
@Test func non_sendable_type_sent_to_databaseWriter_writeWithoutTransaction() async throws {
let dbQueue = try DatabaseQueue()
let nonSendable = NonSendable(value: 0)
let value = try await dbQueue.writeWithoutTransaction { _ in
nonSendable.value
}
#expect(value == 0)
}
}
@@ -0,0 +1,26 @@
import GRDB
import Testing
nonisolated private struct Player: Codable {
var id: Int64
var name: String
}
extension Player: nonisolated Identifiable { }
extension Player: PersistableRecord { }
@Suite struct PersistableRecordTests {
@Test func insert_record() async throws {
let dbQueue = try DatabaseQueue()
try await dbQueue.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try Player(id: 1, name: "Arthur").insert(db)
let playerCount = try Player.fetchCount(db)
#expect(playerCount == 1)
}
}
}