Compare commits

...
Author SHA1 Message Date
Gwendal Roué d97f7ab07c test 2025-09-23 08:24:03 +02:00
alephao aab2664431 fix: DispatchQueueExecutor sendable conformance on Linux 2025-09-18 08:27:14 +02:00
Gwendal Roué f3acfecc16 DatabaseCollation no longer uses a deprecated String initializer 2025-09-13 12:21:36 +02:00
Gwendal Roué aa2cdb7ec3 Merge branch 'master' into development 2025-09-10 20:53:15 +02:00
Gwendal Roué d90ba851fe Merge pull request #1803 from groue/dependabot/github_actions/actions/checkout-5
Bump actions/checkout from 4 to 5
2025-09-10 20:52:19 +02:00
Gwendal Roué 7eea8ccb91 Merge pull request #1813 from groue/dev/SendableMetaType
Support for Xcode 26
2025-09-10 18:05:39 +02:00
Gwendal Roué 6a25b3538e DocC for GRDBSendableMetatype 2025-09-10 07:41:42 +02:00
Gwendal Roué 7ec88b76e0 Start an immediate observation
In the iOS 26 simulator the demo app would show a flash of missing content.
2025-09-10 07:12:53 +02:00
Gwendal Roué 1a3842e4bc Combine and concurrency: lol 2025-09-10 07:12:53 +02:00
Gwendal Roué 32ed290a1b EncodableRecord is GRDBSendableMetatype
This allows us to apply the encoding strategies for Data, Date, UUID when we know we need it, i.e. when we know the primary key, and this happens when we access the database - in a nonisolated fashion.
2025-09-10 07:12:53 +02:00
Gwendal Roué f88c7202cd TableRecord is GRDBSendableMetatype
This is required because the value of databaseSelection is not required to be Sendable. This forces TableRecord.relationForAll to postpone the definition of the selection until we access the database - in a nonisolated fashion.
2025-09-10 07:12:53 +02:00
Gwendal Roué 79ce0ff5f3 Avoid a compiler warning 2025-09-10 07:12:53 +02:00
Gwendal Roué f435715f75 ValueReducer is SendableMetatype
ValueReducer does not support isolated conformances: it must be able to reduce observed values when needed. This can happen in a nonisolated fashion.
2025-09-10 07:12:52 +02:00
Gwendal Roué cf1702630f DatabaseAggregate is SendableMetatype
DatabaseAggregate does not support isolated conformances: it must be able to aggregate values whenever a database access is performed. This can happen in a nonisolated fashion.
2025-09-10 07:12:52 +02:00
Gwendal Roué fd7adf7fb3 SendableMetatype for compiler >= 6.2 2025-09-10 07:12:52 +02:00
Gwendal Roué be0f0c6f25 Fix a compiler error
The error was:

> use of ‘@import’ in framework header is discouraged, including this header requires -fmodules

This commit applies the fix recommended at https://developer.apple.com/documentation/xcode/identifying-and-addressing-framework-module-issues
2025-09-10 07:12:52 +02:00
Gwendal Roué cd84db3873 Xcode 26 upgrade 2025-09-10 07:12:52 +02:00
Gwendal Roué 4cfa692ddd Fix race condition regarding Task cancellation
This complements #1797 by making sure read-only transactions complete correctly, even if the task is cancelled.
2025-09-10 07:12:11 +02:00
Gwendal Roué 8dfbbb50f6 TODO 2025-09-10 06:51:14 +02:00
Gwendal Roué 3f69614405 DatabaseFunction with raw xFunc
No use right now, but I was really bugged that we could not use raw sqlite3_result_xxx methods from custom functions.
2025-09-02 08:09:16 +02:00
Gwendal Roué b4f3a83755 Remove SwiftLint warning
If we don't have warnings about explicit nil initialization, then we have a warning about the name of a disabled rule which is now deprecated. In all cases, we have a warning.

So let's just write 2025 Swift, ignore that rule, and call it a day.
2025-09-02 08:07:16 +02:00
Gwendal Roué 7cd2a4563c Merge pull request #1807 from emmanuel-ferdman/development
Update `GRDB7MigrationGuide.md` reference
2025-08-31 13:52:09 +02:00
Emmanuel Ferdman 2698c55654 Update GRDB7MigrationGuide.md reference
Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
2025-08-30 09:58:59 -07:00
Gwendal Roué 37065fb503 Regression test for #1797 2025-08-19 08:05:07 +02:00
Gwendal Roué 3801ab9ac6 Fix Base image link 2025-08-19 08:04:41 +02:00
Gwendal Roué 26abd8ad79 Merge branch 'dev/sponsor-base' 2025-08-18 17:52:58 +02:00
Gwendal Roué 827ab62bb6 Add link to our beloved sponsor Base 2025-08-18 17:39:03 +02:00
dependabot[bot] fdeb88a6bd Bump actions/checkout from 4 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-18 09:08:53 +00:00
43 changed files with 358 additions and 127 deletions

No files matched your search

+6 -6
View File
@@ -53,7 +53,7 @@ jobs:
destination: "OS=18.1,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -70,7 +70,7 @@ jobs:
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -87,7 +87,7 @@ jobs:
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -104,7 +104,7 @@ jobs:
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -121,7 +121,7 @@ jobs:
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -138,7 +138,7 @@ jobs:
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_universal_xcframework
@@ -158,7 +158,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
LastUpgradeCheck = 2600;
TargetAttributes = {
56CFC6432C9F1DC9000B5023 = {
CreatedOnToolsVersion = 16.0;
@@ -293,6 +293,7 @@
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -350,6 +351,7 @@
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
VALIDATE_PRODUCT = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1600"
LastUpgradeVersion = "2600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -56,7 +56,7 @@ import GRDB
// Start observing the database.
// Previous observation, if any, is cancelled.
cancellable = observation.start(in: appDatabase.reader) { error in
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
// Handle error
} onChange: { [unowned self] players in
self.players = players
+6 -1
View File
@@ -1842,8 +1842,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2539,6 +2540,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2546,6 +2548,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -2570,6 +2573,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2577,6 +2581,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+4 -4
View File
@@ -87,7 +87,7 @@ public struct Configuration: Sendable {
/// with the number of snapshots.
///
/// The default configuration label is nil.
public var label: String? = nil
public var label: String?
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they does not match any
@@ -329,7 +329,7 @@ public struct Configuration: Sendable {
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
/// If nil, GRDB picks a default one.
var readonlyBusyMode: Database.BusyMode? = nil
var readonlyBusyMode: Database.BusyMode?
/// The maximum number of concurrent reader connections.
///
@@ -387,7 +387,7 @@ public struct Configuration: Sendable {
/// ``qos`` property.
///
/// The default is nil.
public var targetQueue: DispatchQueue? = nil
public var targetQueue: DispatchQueue?
/// The target dispatch queue for write database accesses.
///
@@ -395,7 +395,7 @@ public struct Configuration: Sendable {
/// by ``targetQueue``.
///
/// The default is nil.
public var writeTargetQueue: DispatchQueue? = nil
public var writeTargetQueue: DispatchQueue?
#if os(iOS)
/// A boolean value indicating whether the database connection releases
+2 -2
View File
@@ -571,7 +571,7 @@ extension Database {
// We don't use `try makeStatement(sql:)` in order to avoid throwing an
// error (this annoys users who set a breakpoint on Swift errors).
let sql = "SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)"
var statement: SQLiteStatement? = nil
var statement: SQLiteStatement?
let code = sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
return code == SQLITE_OK
@@ -743,7 +743,7 @@ extension Database {
id: Int,
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
var previousId: Int?
for row in try Row.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier))
""")
+1 -1
View File
@@ -387,7 +387,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>? = nil
var statementEnd: UnsafePointer<CChar>?
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
+7 -7
View File
@@ -169,7 +169,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -459,7 +459,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
// See <https://www.sqlite.org/c3ref/open.html>
var sqliteConnection: SQLiteConnection? = nil
var sqliteConnection: SQLiteConnection?
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
// https://www.sqlite.org/c3ref/open.html
@@ -806,7 +806,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) in
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
@@ -1286,7 +1286,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
var statement: SQLiteStatement? = nil
var statement: SQLiteStatement?
let sql = "PRAGMA journal_mode"
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
@@ -1483,7 +1483,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1626,7 +1626,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1744,7 +1744,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
assert(!isInsideTransaction)
}
/// Commits a database transaction.
+20 -16
View File
@@ -53,12 +53,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
}
}
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
/// <https://www.sqlite.org/c3ref/create_collation.html>
typealias XCompare = @Sendable (
_ length1: CInt,
_ buffer1: UnsafeRawPointer,
_ length2: CInt,
_ buffer2: UnsafeRawPointer
) -> CInt
/// The identifier of the collation.
public var id: ID { ID(name: name) }
/// The name of the collation.
public let name: String
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let xCompare: XCompare
/// Creates a collation.
///
@@ -75,21 +84,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
return CInt(function(string1, string2).rawValue)
})
}
init(_ name: String, xCompare: @escaping XCompare) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
self.xCompare = xCompare
}
}
+46 -18
View File
@@ -82,20 +82,43 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
/// have exactly `argumentCount` elements, provided `argumentCount` is
/// not nil.
public init(
public convenience init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv[index]!)
}
let result = try function(arguments)
switch result?.databaseValue.storage ?? .null {
case .null:
sqlite3_result_null(context)
case .int64(let int64):
sqlite3_result_int64(context, int64)
case .double(let double):
sqlite3_result_double(context, double)
case .string(let string):
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
}
}
}
init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
xFunc: @escaping XFunc)
{
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
self.kind = .function(xFunc)
}
/// Creates an SQL aggregate function.
@@ -256,11 +279,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private class FunctionDefinition {
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
throws -> (any DatabaseValueConvertible)?)
let xFunc: XFunc
init(xFunc: @escaping XFunc)
{
self.compute = compute
self.xFunc = xFunc
}
}
@@ -283,11 +305,19 @@ public final class DatabaseFunction: Identifiable, Sendable {
}
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
typealias XFunc = @Sendable (
_ argc: CInt,
_ argv: UnsafeMutablePointer<OpaquePointer?>,
_ context: OpaquePointer?
) throws -> Void
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(XFunc)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
@@ -296,8 +326,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
var definition: AnyObject {
switch self {
case .function(let compute):
return FunctionDefinition(compute: compute)
case .function(let xFunc):
return FunctionDefinition(xFunc: xFunc)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
@@ -312,9 +342,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
@@ -464,7 +492,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate {
public protocol DatabaseAggregate: GRDBSendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+21 -6
View File
@@ -361,8 +361,13 @@ extension DatabasePool: DatabaseReader {
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// 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.
@@ -387,8 +392,13 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// 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)
releaseReader(.reuse)
}
@@ -551,8 +561,13 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// 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)
releaseReader(.reuse)
}
+14 -4
View File
@@ -248,8 +248,13 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { db in
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// 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)
try? db.endReadOnly()
}
@@ -297,8 +302,13 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// 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)
try? db.endReadOnly()
}
+6 -2
View File
@@ -201,7 +201,11 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -212,7 +216,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+7 -2
View File
@@ -113,8 +113,13 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// 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)
}
}
+4
View File
@@ -43,3 +43,7 @@ private final class DispatchQueueExecutor: SerialExecutor {
dispatchPrecondition(condition: .onQueue(queue))
}
}
#if os(Linux)
extension DispatchQueueExecutor: @unchecked Sendable {}
#endif
+1 -1
View File
@@ -141,7 +141,7 @@ public final class Statement {
let authorizer = database.authorizer
authorizer.reset()
var sqliteStatement: SQLiteStatement? = nil
var sqliteStatement: SQLiteStatement?
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
+1 -1
View File
@@ -1494,7 +1494,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
var value: SQLiteValue?
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+7 -1
View File
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
// Commit or rollback, but try hard to leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -229,5 +229,11 @@ Task {
}
```
## Topics
### Supporting Types
- ``GRDBSendableMetatype``
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
+2 -2
View File
@@ -117,8 +117,8 @@ public struct FTS5 {
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
var statement: SQLiteStatement?
var api: UnsafePointer<fts5_api>?
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
+1 -1
View File
@@ -208,7 +208,7 @@ extension Database {
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer? = nil
var tokenizerPointer: OpaquePointer?
let code: CInt
if arguments.isEmpty {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
@@ -636,7 +636,7 @@ public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
var key: String?
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
@@ -362,11 +362,13 @@ extension QueryInterfaceRequest: SelectionRequest {
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
let databaseTableName = self.databaseTableName
return selectWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
"selectID requires a single-column primary key in the table \(databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
+3 -3
View File
@@ -1592,7 +1592,7 @@ extension SQLExpression {
case let .associativeBinary(op, expressions):
assert(expressions.count > 1)
if op == .and {
var result: Set<Int64>? = nil
var result: Set<Int64>?
for expression in expressions {
if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) {
if var rowIDs = result {
@@ -2020,8 +2020,8 @@ struct SQLAggregateFunctionInvocation {
var name: String
var arguments: [SQLExpression]
var isDistinct = false
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
var ordering: SQLOrdering? // SQLite 3.44.0+
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord {
public protocol EncodableRecord: GRDBSendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
+1 -1
View File
@@ -134,7 +134,7 @@ import Foundation
/// - ``select(_:as:)-tjh0``
/// - ``updateAll(_:onConflict:_:)-7vv9x``
/// - ``updateAll(_:onConflict:_:)-7atfw``
public protocol TableRecord {
public protocol TableRecord: GRDBSendableMetatype {
/// A type that defines columns.
///
/// For example:
+4 -2
View File
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
self.attemptToFulfill = attemptToFulfill
}
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
func receive<S>(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
@@ -35,7 +35,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
private class OnDemandFutureSubscription<Downstream>: Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype
{
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
+10
View File
@@ -23,6 +23,16 @@ public func databaseQuestionMarks(count: Int) -> String {
repeatElement("?", count: count).joined(separator: ",")
}
#if compiler(>=6.2)
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
/// and `Any` in previous compiler versions.
public typealias GRDBSendableMetatype = SendableMetatype
#else
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
/// and `Any` in previous compiler versions.
public typealias GRDBSendableMetatype = Any
#endif
// MARK: - Internal
/// Reserved for GRDB: do not use.
@@ -11,7 +11,7 @@
// which is its `Fetcher`.
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer {
public protocol _ValueReducer: GRDBSendableMetatype {
/// The Sendable type that fetches database values
associatedtype Fetcher: _ValueReducerFetcher
+6 -2
View File
@@ -511,7 +511,11 @@ extension DatabasePublishers {
self.start = start
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
let subscription = ValueSubscription(
start: start,
downstream: subscriber)
@@ -521,7 +525,7 @@ extension DatabasePublishers {
private class ValueSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error
{
// @unchecked Sendable because `cancellable` and `state` are
+6 -1
View File
@@ -1880,8 +1880,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
F3BA80591CFB2BB2003DC1BA = {
@@ -2555,6 +2556,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2562,6 +2564,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "appletvos appletvsimulator driverkit iphoneos iphonesimulator macosx watchos watchsimulator";
SUPPORTS_MACCATALYST = YES;
@@ -2588,6 +2591,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2595,6 +2599,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "appletvos appletvsimulator driverkit iphoneos iphonesimulator macosx watchos watchsimulator";
SUPPORTS_MACCATALYST = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+13 -3
View File
@@ -15,6 +15,16 @@
<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**: July 23, 2025 • [version 7.6.1](https://github.com/groue/GRDB.swift/tree/v7.6.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
@@ -325,7 +335,7 @@ Documentation
- [Unicode](#unicode)
- [Memory Management](#memory-management)
- [Data Protection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)
- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/Documentation/GRDB7MigrationGuide.md)
- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
- :bulb: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md)
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
@@ -2184,7 +2194,7 @@ For more information about batch updates, see [Update Requests](#update-requests
> **Note**: Upsert apis are available from SQLite 3.35.0+: iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build] or [SQLCipher](#encryption).
>
> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks reports the rowid of the inserted or updated row; `willUpdate`, `aroundUdate`, `didUdate` are not called.
> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks reports the rowid of the inserted or updated row; `willUpdate`, `aroundUpdate`, `didUpdate` are not called.
[PersistableRecord] provides three upsert methods:
@@ -2998,7 +3008,7 @@ try player.insert(db)
> // INSERT OR IGNORE INTO player ... RETURNING *
> do {
> let insertedPlayer = try player.insertAndFetch(db) {
> // Succesful insertion
> // Successful insertion
> catch RecordError.recordNotFound {
> // Failed insertion due to IGNORE policy
> }
+2 -2
View File
@@ -1,4 +1,4 @@
@import Foundation;
#import <Foundation/Foundation.h>
//! Project version number for GRDB.
FOUNDATION_EXPORT double GRDB_VersionNumber;
@@ -8,4 +8,4 @@ FOUNDATION_EXPORT const unsigned char GRDB_VersionString[];
#import <GRDB/GRDBCustomSQLite-USER.h>
#import <GRDB/sqlite3.h>
#import "GRDB-Bridging.h"
#import <GRDB/GRDB-Bridging.h>
-1
View File
@@ -18,7 +18,6 @@ disabled_rules:
- non_optional_string_data_conversion
- opening_brace
- optional_data_string_conversion
- redundant_optional_initialization
- syntactic_sugar
- todo
- trailing_comma
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

+1 -2
View File
@@ -1,4 +1,4 @@
@import Foundation;
#import <Foundation/Foundation.h>
//! Project version number for GRDB.
FOUNDATION_EXPORT double GRDB_VersionNumber;
@@ -7,4 +7,3 @@ FOUNDATION_EXPORT double GRDB_VersionNumber;
FOUNDATION_EXPORT const unsigned char GRDB_VersionString[];
#import <GRDB/GRDB-Bridging.h>
+23 -23
View File
@@ -6,38 +6,38 @@ class DatabaseCollationTests: GRDBTestCase {
func testDefaultCollations() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "INSERT INTO strings VALUES (1, '1')")
try db.execute(sql: "INSERT INTO strings VALUES (2, '2')")
try db.execute(sql: "INSERT INTO strings VALUES (3, '10')")
try db.execute(sql: "INSERT INTO strings VALUES (4, 'a')")
try db.execute(sql: "INSERT INTO strings VALUES (5, 'à')")
try db.execute(sql: "INSERT INTO strings VALUES (6, 'A')")
try db.execute(sql: "INSERT INTO strings VALUES (7, 'Z')")
try db.execute(sql: "INSERT INTO strings VALUES (8, 'z')")
try db.execute(sql: """
CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO strings VALUES (1, '1');
INSERT INTO strings VALUES (2, '2');
INSERT INTO strings VALUES (3, '10');
INSERT INTO strings VALUES (4, 'a');
INSERT INTO strings VALUES (5, 'à');
INSERT INTO strings VALUES (6, 'A');
INSERT INTO strings VALUES (7, 'Z');
INSERT INTO strings VALUES (8, 'z');
INSERT INTO strings VALUES (9, '');
INSERT INTO strings VALUES (10, NULL);
INSERT INTO strings VALUES (11, x'42FF'); -- Invalid UTF8 "B�"
""")
// Swift 4.2 and Swift 4.1 don't sort strings in the same way
if "z" < "à" {
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[1,3,2,6,7,4,8,5])
} else {
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[1,3,2,6,7,4,5,8])
}
// Note that "B�" is always last. We can observe that SQLite
// does not invoke the collation for invalid UTF8 strings.
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[10,9,1,3,2,6,7,4,8,5,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"),
[1,3,2,4,6,5,7,8])
[10,9,1,3,2,4,6,5,7,8,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCaseInsensitiveCompare.name), id"),
[1,3,2,4,6,5,7,8])
[10,9,1,3,2,4,6,5,7,8,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCompare.name), id"),
[1,3,2,4,6,5,8,7])
[10,9,1,3,2,4,6,5,8,7,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedStandardCompare.name), id"),
[1,2,3,4,6,5,8,7])
[10,9,1,2,3,4,6,5,8,7,11])
}
}
@@ -1109,4 +1109,67 @@ class DatabaseMigratorTests : GRDBTestCase {
XCTFail("Expected error")
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { }
}
// https://github.com/groue/GRDB.swift/discussions/1817
func test_discussion_1817() throws {
var oldMigrator = DatabaseMigrator()
oldMigrator.registerMigration("team") { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
}
oldMigrator.registerMigration("player") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("name", .text).defaults(to: "Anonymous").notNull()
}
}
var newMigrator = DatabaseMigrator()
let collapsedMigrationIdentifier = "player"
let collapsedSQL = try oldMigrator.schemaSQL(upTo: collapsedMigrationIdentifier)
newMigrator.registerMigration(collapsedMigrationIdentifier) { db in
try db.execute(sql: collapsedSQL)
}
do {
let dbQueue = try DatabaseQueue()
try oldMigrator.migrate(dbQueue)
try newMigrator.migrate(dbQueue)
try dbQueue.read { db in
try XCTAssertTrue(newMigrator.hasCompletedMigrations(db))
try XCTAssertFalse(newMigrator.hasBeenSuperseded(db))
}
}
do {
let dbQueue = try DatabaseQueue()
try newMigrator.migrate(dbQueue)
try dbQueue.read { db in
try XCTAssertTrue(newMigrator.hasCompletedMigrations(db))
try XCTAssertFalse(newMigrator.hasBeenSuperseded(db))
}
}
}
}
extension DatabaseMigrator {
func schemaSQL(upTo migrationIdentifier: String) throws -> String {
let dbQueue = try DatabaseQueue()
try migrate(dbQueue, upTo: migrationIdentifier)
class OutputStream: TextOutputStream {
var buffer = ""
func write(_ string: String) {
buffer += string
}
}
let stream = OutputStream()
try dbQueue.dumpSchema(to: stream)
return stream.buffer
.components(separatedBy: "\n")
.dropFirst() // Remove "sqlite_master" line
.joined(separator: "\n")
}
}
+48
View File
@@ -677,4 +677,52 @@ class DatabaseReaderTests : GRDBTestCase {
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
// Regression test for https://github.com/groue/GRDB.swift/pull/1797
func test_cancellation_does_not_impact_other_tasks() async throws {
func test(_ dbReader: some DatabaseReader) async throws {
// Numbers that have the test fail more or less reliably
// (on my machine) unless the #1797 patch is applied.
let repeatCount = 30
let taskCount = 400
for _ in 0..<repeatCount {
try await withThrowingTaskGroup(of: Void.self) { group in
for i in 0..<taskCount{
let task = Task {
try await dbReader.read { db in
try db.execute(sql: "SELECT 1")
}
}
group.addTask {
if i.isMultiple(of: 2) {
Task {
// For the test to fail, we need to be lucky, here:
// Cancellation must occur after the database access
// has completed, but before `read` has returned. This
// triggers the failure of unrelated tasks because
// the database enters the cancelled state
// (fixed by #1797).
task.cancel()
}
// Ignore expected CancellationError
try? await task.value
} else {
// Unexpected CancellationError fails the test
try await task.value
}
}
}
try await group.waitForAll()
}
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(makeDatabasePool().makeSnapshot())
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try await test(makeDatabasePool().makeSnapshotPool())
#endif
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"