Compare commits

..
Author SHA1 Message Date
Tim De Jong 3dd3bbf0c5 vscode config 2025-10-12 18:03:57 +02:00
Tim De Jong d7cf0f9e59 NSError bridging is not available, or doesn't work the same on non-Darwin platforms. Skip testNSErrorBridging on these platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 389c3e0d4a Use #if !canImport(Combine) per test case (as done by @marcprux) and throw an XCTSkip for these test cases. This gives a better impression how many tests are skipped on Linux/non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong a212bf9e89 It should be canImport(Darwin) not os(Darwin) 2025-10-12 18:03:57 +02:00
Tim De Jong 65186104cc Integrated upstream changes.
Some tests depend on Combine which is not available on non-Darwin platforms. Fix this.
2025-10-12 18:03:57 +02:00
Tim De Jong 2f108508fa Fixed DatabaseSnapshotTests on non-darwin platforms 2025-10-12 18:03:57 +02:00
Tim De Jong 5513eab099 Fixed the tests in DatabaseQueueTests.swift 2025-10-12 18:03:57 +02:00
Tim De Jong 2ad2d20a89 Fixed the unit tests in DatabasePoolConcurrencyTests. 2025-10-12 18:03:57 +02:00
Tim De Jong dd90fe6e62 Ignore ValueObservationRecorderTests.swift on non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 691207567a Ignore FailureTestCase.swift entirely on non-Darwin platforms for now. 2025-10-12 18:03:57 +02:00
Tim De Jong c7f1dd7470 Fixed import in CGFloatTests.swift to work under non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 8e5b9ca9bd Fixed UUID fromDatabaseValue for non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong dc7d47c066 Fixed databaseValue build for non-Darwin platforms. 2025-10-12 18:03:56 +02:00
Tim De Jong 14f60ad48f Fixed fromDatabaseValue build under non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong e758fde941 Removed #if !os(Linux) in NSString.swift, NSData.swift and Date.swift. 2025-10-12 17:43:25 +02:00
Tim De Jong 7477e1cff8 Removed the #if !os(Linux) compiler directive in the Decimal extension, as it compiles fine under swift 6 2025-10-12 17:43:15 +02:00
Tim De Jong 2d6fe172c3 Import Foundation for CGFloat on non-Darwin platforms 2025-10-12 17:43:02 +02:00
Tim De Jong 0526853dde Fixed some linker errors caused by WAL absence on Linux. 2025-10-12 17:42:49 +02:00
55 changed files with 258 additions and 1045 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"editor.formatOnSave": false,
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"editor.trimAutoWhitespace": false
}
+1 -33
View File
@@ -7,7 +7,6 @@ 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)
@@ -141,37 +140,6 @@ 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
@@ -4402,7 +4370,7 @@ Released April 3, 2017
**Breaking Changes**
- 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)).
- 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)).
- 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.9.0'
s.version = '7.8.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
-4
View File
@@ -292,7 +292,6 @@
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 */; };
@@ -803,7 +802,6 @@
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>"; };
@@ -1450,7 +1448,6 @@
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */,
5698ACCA1DA62A2D0056AF8C /* FTS5TokenizerTests.swift */,
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */,
56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */,
);
name = FTS;
sourceTree = "<group>";
@@ -2133,7 +2130,6 @@
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,27 +513,6 @@ 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 {
+2 -58
View File
@@ -863,16 +863,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
readOnlyDepth -= 1
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
if readOnlyDepth == 0 {
// 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()
}
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
}
}
@@ -1309,31 +1300,6 @@ 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 {
@@ -1798,16 +1764,7 @@ 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 {
// 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")
}
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(!isInsideTransaction)
}
@@ -1822,19 +1779,6 @@ 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.
+41 -59
View File
@@ -352,35 +352,29 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: sending (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// 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)
}
}
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)
}
}
}
@@ -438,22 +432,16 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: sending (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// 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)
}
return try await readerPool.get { reader in
try await reader.execute { db in
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -798,7 +786,7 @@ extension DatabasePool: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: sending (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -814,38 +802,32 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: sending (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// 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 {
// 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 await readerPool.barrier {
try Task.checkCancellation()
return try writer.sync { db in
defer {
cancelMutex.store(nil)
db.uncancel()
}
cancelMutex.store(db.cancel)
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: sending (Database) throws -> T
_ value: @Sendable (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: sending (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
@@ -397,7 +397,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: sending (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -408,7 +408,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: sending (Database) throws -> T
_ updates: @Sendable (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: sending (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: sending (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: sending (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: sending (Database) throws -> T
_ value: @Sendable (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: sending (Database) throws -> T
_ value: @Sendable (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: sending (Database) throws -> T
_ value: @Sendable (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: sending (Database) throws -> T
_ value: @Sendable (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: sending (Database) throws -> T
_ value: @Sendable (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: sending (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: sending (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: sending (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: sending (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: sending (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: sending (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: sending (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
+4
View File
@@ -1,4 +1,8 @@
#if os(Linux)
@preconcurrency import Dispatch
#else
import Dispatch
#endif
/// An actor that runs in a DispatchQueue.
///
+12 -19
View File
@@ -250,29 +250,22 @@ final class SerializedDatabase {
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: sending (Database) throws -> T
_ block: @Sendable (Database) throws -> T
) async throws -> T {
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
// 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)
return try await withTaskCancellationHandler {
try await actor.execute {
defer {
cancelMutex.store(nil)
db.uncancel()
preconditionNoUnsafeTransactionLeft(db)
}
} onCancel: {
cancelMutex.withLock { $0?() }
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try block(db)
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
+4 -1
View File
@@ -150,7 +150,10 @@ public final class Statement {
&sqliteStatement, statementEnd)
guard code == SQLITE_OK else {
try database.statementCompilationDidFail(at: statementStart, withResultCode: code)
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: String(cString: statementStart))
}
guard let sqliteStatement else {
+3 -1
View File
@@ -1,5 +1,8 @@
#if canImport(CoreGraphics)
import CoreGraphics
#elseif !canImport(Darwin)
import Foundation
#endif
/// CGFloat adopts DatabaseValueConvertible
extension CGFloat: DatabaseValueConvertible {
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
return CGFloat(double)
}
}
#endif
-2
View File
@@ -12,7 +12,6 @@ import GRDBSQLite
import Foundation
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate: DatabaseValueConvertible {
@@ -41,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
return cast(date)
}
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -1,4 +1,3 @@
#if !os(Linux)
// Import C SQLite functions
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
@@ -68,4 +67,3 @@ extension Decimal: StatementColumnConvertible {
@usableFromInline
let _posixLocale = Locale(identifier: "en_US_POSIX")
#endif
@@ -1,4 +1,3 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
return cast(data)
}
}
#endif
+11 -3
View File
@@ -1,4 +1,4 @@
#if !os(Linux) && !os(Windows)
#if !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
@@ -81,10 +81,18 @@ extension NSNumber: DatabaseValueConvertible {
/// Otherwise, returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .int64(let int64) where self is NSDecimalNumber.Type:
let number = NSDecimalNumber(value: int64)
return number as? Self
case .int64(let int64):
return self.init(value: int64)
let number = NSNumber(value: int64)
return number as? Self
case .double(let double) where self is NSDecimalNumber.Type:
let number = NSDecimalNumber(value: double)
return number as? Self
case .double(let double):
return self.init(value: double)
let number = NSNumber(value: double)
return number as? Self
case let .string(string):
// Must match Decimal.fromDatabaseValue(_:)
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
@@ -1,4 +1,3 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
return self.init(string: string)
}
}
#endif
+6 -2
View File
@@ -1,12 +1,16 @@
import Foundation
#if !os(Linux) && !os(Windows)
#if !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
/// Returns a TEXT database value containing the absolute URL.
public var databaseValue: DatabaseValue {
absoluteString?.databaseValue ?? .null
#if !canImport(Darwin)
absoluteString.databaseValue
#else
absoluteString?.databaseValue ?? .null
#endif
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
+12 -5
View File
@@ -12,7 +12,7 @@ import GRDBSQLite
import Foundation
#if !os(Linux) && !os(Windows)
#if !os(Windows)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
@@ -36,10 +36,17 @@ extension NSUUID: DatabaseValueConvertible {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
return data.withUnsafeBytes {
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
#if canImport(Darwin)
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
#else
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
return nil as Self?
}
return NSUUID(uuidBytes: uuidBytes) as? Self
#endif
}
case .string(let string):
return self.init(uuidString: string)
return NSUUID(uuidString: string) as? Self
default:
return nil
}
@@ -91,8 +98,8 @@ extension UUID: StatementColumnConvertible {
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
let blob = sqlite3_column_blob(sqliteStatement, index)
else {
return nil
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
-4
View File
@@ -287,7 +287,6 @@
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 */; };
@@ -815,7 +814,6 @@
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>"; };
@@ -1443,7 +1441,6 @@
5698AC3E1DA2BEBB0056AF8C /* FTS */ = {
isa = PBXGroup;
children = (
56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */,
5698AC3F1DA2BED90056AF8C /* FTS3PatternTests.swift */,
5698AC481DA2D48A0056AF8C /* FTS3RecordTests.swift */,
5698AC881DA389380056AF8C /* FTS3TableBuilderTests.swift */,
@@ -2377,7 +2374,6 @@
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 */,
+15 -27
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.2
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import Foundation
@@ -14,7 +14,15 @@ 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"),
// Not all Linux distributions have support for WAL snapshots.
.define("SQLITE_DISABLE_SNAPSHOT", .when(platforms: [.linux])),
]
var cSettings: [CSetting] = []
var dependencies: [PackageDescription.Package.Dependency] = []
@@ -50,6 +58,10 @@ 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(
@@ -58,7 +70,7 @@ let package = Package(
.target(
name: "GRDB",
dependencies: [
.target(name: "GRDBSQLite"),
.target(name: "GRDBSQLite", condition: .when(traits: ["GRDBSQLite"])),
],
path: "GRDB",
resources: [.copy("PrivacyInfo.xcprivacy")],
@@ -80,9 +92,6 @@ let package = Package(
"Swift6Migration",
"generatePerformanceReport.rb",
"parsePerformanceTests.rb",
"Swift6ApprochableConcurrencyGRDBTests",
"Swift6DefaultGRDBTests",
"Swift6MainActorIsolationGRDBTests",
],
resources: [
.copy("GRDBTests/Betty.jpeg"),
@@ -95,28 +104,7 @@ 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
@@ -1,105 +0,0 @@
// 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]
)
+11 -1
View File
@@ -15,7 +15,17 @@
<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**: 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)
---
<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)
**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.

After

Width:  |  Height:  |  Size: 78 KiB

+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.9.0</string>
<string>7.8.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+6 -1
View File
@@ -1,7 +1,12 @@
import XCTest
import CoreGraphics
import GRDB
#if canImport(CoreGraphics)
import CoreGraphics
#elseif !canImport(Darwin)
import Foundation
#endif
class CGFloatTests: GRDBTestCase {
func testCGFLoat() throws {
+4
View File
@@ -216,6 +216,9 @@ class DatabaseErrorTests: GRDBTestCase {
}
func testNSErrorBridging() throws {
#if !canImport(Darwin)
throw XCTSkip("NSError bridging not available on non-Darwin platforms")
#else
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { $0.column("id", .integer).primaryKey() }
@@ -229,5 +232,6 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertNotNil(error.localizedFailureReason)
}
}
#endif
}
}
@@ -10,6 +10,9 @@ class DatabaseMigratorTests : GRDBTestCase {
}
func testEmptyMigratorSync() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
let migrator = DatabaseMigrator()
try migrator.migrate(writer)
@@ -18,9 +21,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testEmptyMigratorAsync() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
let expectation = self.expectation(description: "")
let migrator = DatabaseMigrator()
@@ -38,9 +45,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testEmptyMigratorPublisher() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
let migrator = DatabaseMigrator()
let publisher = migrator.migratePublisher(writer)
@@ -51,9 +62,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testNonEmptyMigratorSync() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
@@ -95,9 +110,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testNonEmptyMigratorAsync() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
@@ -146,9 +165,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testNonEmptyMigratorPublisher() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
@@ -198,9 +221,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testEmptyMigratorPublisherIsAsynchronous() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
let migrator = DatabaseMigrator()
let expectation = self.expectation(description: "")
@@ -220,9 +247,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testNonEmptyMigratorPublisherIsAsynchronous() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("first", migrate: { _ in })
@@ -243,9 +274,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testMigratorPublisherDefaultScheduler() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test<Writer: DatabaseWriter>(writer: Writer) {
var migrator = DatabaseMigrator()
migrator.registerMigration("first", migrate: { _ in })
@@ -268,9 +303,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testMigratorPublisherCustomScheduler() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test<Writer: DatabaseWriter>(writer: Writer) {
var migrator = DatabaseMigrator()
migrator.registerMigration("first", migrate: { _ in })
@@ -294,9 +333,13 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testMigrateUpTo() throws {
#if !canImport(Combine)
throw XCTSkip("Combine not supported on this platform")
#else
func test(writer: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("a") { db in
@@ -345,6 +388,7 @@ class DatabaseMigratorTests : GRDBTestCase {
try Test(test).run { try DatabaseQueue() }
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
#endif
}
func testMigrationFailureTriggersRollback() throws {
@@ -877,10 +877,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, nil)
XCTAssertEqual(db.description, "GRDB.DatabasePool.writer")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "GRDB.DatabasePool.writer")
#endif
}
let s1 = DispatchSemaphore(value: 0)
@@ -890,10 +892,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, nil)
XCTAssertEqual(db.description, "GRDB.DatabasePool.reader.1")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "GRDB.DatabasePool.reader.1")
#endif
_ = s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -906,10 +910,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, nil)
XCTAssertEqual(db.description, "GRDB.DatabasePool.reader.2")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "GRDB.DatabasePool.reader.2")
#endif
}
}
let blocks = [block1, block2]
@@ -925,10 +931,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, "Toreador")
XCTAssertEqual(db.description, "Toreador.writer")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "Toreador.writer")
#endif
}
let s1 = DispatchSemaphore(value: 0)
@@ -938,10 +946,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, "Toreador")
XCTAssertEqual(db.description, "Toreador.reader.1")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "Toreador.reader.1")
#endif
_ = s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -954,10 +964,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, "Toreador")
XCTAssertEqual(db.description, "Toreador.reader.2")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "Toreador.reader.2")
#endif
}
}
let blocks = [block1, block2]
@@ -1037,6 +1049,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
func testQoS() throws {
#if !canImport(Darwin)
throw XCTSkip("__dispatch_get_global_queue unavailable")
#else
func test(qos: DispatchQoS) throws {
// https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5
//
@@ -1072,6 +1087,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
try test(qos: .background)
try test(qos: .userInitiated)
#endif
}
// MARK: - AsyncConcurrentRead
@@ -1254,6 +1270,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// MARK: - Concurrent opening
func testConcurrentOpening() throws {
#if !canImport(Darwin)
throw XCTSkip("NSFileCoordinator unavailable")
#else
for _ in 0..<50 {
let dbDirectoryName = "DatabasePoolConcurrencyTests-\(ProcessInfo.processInfo.globallyUniqueString)"
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
@@ -1277,6 +1296,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTAssert(poolError ?? coordinatorError == nil)
}
}
#endif
}
// MARK: - NSFileCoordinator sample code tests
@@ -1284,6 +1304,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// Test for sample code in Documentation.docc/DatabaseSharing.md.
// This test passes if this method compiles
private func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
#if !canImport(Darwin)
throw XCTSkip("NSFileCoordinator unavailable")
#else
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
@@ -1299,6 +1322,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
throw error
}
return dbPool!
#endif
}
// Test for sample code in Documentation.docc/DatabaseSharing.md.
@@ -1313,6 +1337,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// Test for sample code in Documentation.docc/DatabaseSharing.md.
// This test passes if this method compiles
private func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
#if !canImport(Darwin)
throw XCTSkip("NSFileCoordinator unavailable")
#else
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
@@ -1328,6 +1355,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
throw error
}
return dbPool
#endif
}
// Test for sample code in Documentation.docc/DatabaseSharing.md.
+8
View File
@@ -129,10 +129,12 @@ class DatabaseQueueTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, nil)
XCTAssertEqual(db.description, "GRDB.DatabaseQueue")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "GRDB.DatabaseQueue")
#endif
}
}
@@ -144,10 +146,12 @@ class DatabaseQueueTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, "Toreador")
XCTAssertEqual(db.description, "Toreador")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "Toreador")
#endif
}
}
@@ -221,6 +225,9 @@ class DatabaseQueueTests: GRDBTestCase {
}
func testQoS() throws {
#if !canImport(Darwin)
throw XCTSkip("__dispatch_get_global_queue not available on non-Darwin platforms")
#else
func test(qos: DispatchQoS) throws {
// https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5
//
@@ -256,6 +263,7 @@ class DatabaseQueueTests: GRDBTestCase {
try test(qos: .background)
try test(qos: .userInitiated)
#endif
}
// MARK: - SQLITE_BUSY prevention
@@ -4,12 +4,14 @@ import GRDB
class DatabaseRegionObservationTests: GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
#if canImport(Combine)
func testAnyDatabaseWriter(writer: any DatabaseWriter) throws {
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
_ = observation.start(in: writer, onError: { _ in }, onChange: { _ in })
_ = observation.publisher(in: writer)
}
#endif
func testDatabaseRegionObservation_FullDatabase() throws {
let dbQueue = try makeDatabaseQueue()
@@ -230,10 +230,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, nil)
XCTAssertEqual(db.description, "GRDB.DatabasePool.snapshot.1")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "GRDB.DatabasePool.snapshot.1")
#endif
}
let snapshot2 = try dbPool.makeSnapshot()
@@ -241,10 +243,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, nil)
XCTAssertEqual(db.description, "GRDB.DatabasePool.snapshot.2")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "GRDB.DatabasePool.snapshot.2")
#endif
}
}
@@ -257,10 +261,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, "Toreador")
XCTAssertEqual(db.description, "Toreador.snapshot.1")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "Toreador.snapshot.1")
#endif
}
let snapshot2 = try dbPool.makeSnapshot()
@@ -268,10 +274,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
XCTAssertEqual(db.configuration.label, "Toreador")
XCTAssertEqual(db.description, "Toreador.snapshot.2")
#if canImport(Darwin)
// This test CAN break in future releases: the dispatch queue labels
// are documented to be a debug-only tool.
let label = String(utf8String: __dispatch_queue_get_label(nil))
XCTAssertEqual(label, "Toreador.snapshot.2")
#endif
}
}
-37
View File
@@ -896,41 +896,4 @@ 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()))
}
}
+2
View File
@@ -1,3 +1,4 @@
#if canImport(Darwin)
// Inspired by https://github.com/groue/CombineExpectations
import XCTest
@@ -207,3 +208,4 @@ class FailureTestCaseTests: FailureTestCase {
}
}
}
#endif
-53
View File
@@ -1,53 +0,0 @@
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,6 +1,7 @@
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,6 +598,7 @@ 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.
@@ -1,3 +1,4 @@
#if canImport(Darwin)
import Dispatch
import XCTest
@@ -781,3 +782,4 @@ class ValueObservationRecorderTests: FailureTestCase {
}
}
}
#endif
@@ -926,6 +926,7 @@ class ValueObservationTests: GRDBTestCase {
}
// MARK: - Async Await
#if canImport(Combine)
func testAsyncAwait_values_prefix() async throws {
func test(_ writer: some DatabaseWriter) async throws {
@@ -1238,6 +1239,7 @@ class ValueObservationTests: GRDBTestCase {
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
}
#endif
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
func testIssue1383() throws {
@@ -1,69 +0,0 @@
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)
}
}
@@ -1,33 +0,0 @@
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)
}
}
}
@@ -1,66 +0,0 @@
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)
}
}
@@ -1,26 +0,0 @@
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)
}
}
}
@@ -1,69 +0,0 @@
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)
}
}
@@ -1,33 +0,0 @@
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)
}
}
}
@@ -1,66 +0,0 @@
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)
}
}
@@ -1,26 +0,0 @@
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)
}
}
}
@@ -1,69 +0,0 @@
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)
}
}
@@ -1,33 +0,0 @@
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)
}
}
}
@@ -1,66 +0,0 @@
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)
}
}
@@ -1,26 +0,0 @@
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)
}
}
}