Compare commits

..
Author SHA1 Message Date
Gwendal Roué b44628b9cd Add missing SendableMetatype requirements 2025-07-25 07:27:28 +02:00
44 changed files with 130 additions and 361 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@v5
- uses: actions/checkout@v4
- 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@v5
- uses: actions/checkout@v4
- 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@v5
- uses: actions/checkout@v4
- 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@v5
- uses: actions/checkout@v4
- 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@v5
- uses: actions/checkout@v4
- 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@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_universal_xcframework
@@ -158,7 +158,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2600;
LastUpgradeCheck = 1600;
TargetAttributes = {
56CFC6432C9F1DC9000B5023 = {
CreatedOnToolsVersion = 16.0;
@@ -293,7 +293,6 @@
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";
@@ -351,7 +350,6 @@
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 = "2600"
LastUpgradeVersion = "1600"
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, scheduling: .immediate) { error in
cancellable = observation.start(in: appDatabase.reader) { error in
// Handle error
} onChange: { [unowned self] players in
self.players = players
+1 -6
View File
@@ -1842,9 +1842,8 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 2600;
LastUpgradeCheck = 1400;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2540,7 +2539,6 @@
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 = (
@@ -2548,7 +2546,6 @@
"@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;
@@ -2573,7 +2570,6 @@
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 = (
@@ -2581,7 +2577,6 @@
"@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 = "2600"
LastUpgradeVersion = "1400"
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?
public var label: String? = nil
/// 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?
var readonlyBusyMode: Database.BusyMode? = nil
/// 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?
public var targetQueue: DispatchQueue? = nil
/// 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?
public var writeTargetQueue: DispatchQueue? = nil
#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?
var statement: SQLiteStatement? = nil
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?
var previousId: Int? = nil
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>?
var statementEnd: UnsafePointer<CChar>? = nil
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? {
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
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?
var sqliteConnection: SQLiteConnection? = nil
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 collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
}, 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?
var statement: SQLiteStatement? = nil
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?
var firstError: Error? = nil
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?
var firstError: Error? = nil
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(!isInsideTransaction)
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
}
/// Commits a database transaction.
+16 -20
View File
@@ -53,21 +53,12 @@ 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 xCompare: XCompare
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -84,16 +75,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
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) {
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.name = name
self.xCompare = xCompare
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)
}
}
}
+18 -46
View File
@@ -82,43 +82,20 @@ 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 convenience init(
public 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(xFunc)
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
}
/// Creates an SQL aggregate function.
@@ -279,10 +256,11 @@ 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 xFunc: XFunc
init(xFunc: @escaping XFunc)
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
throws -> (any DatabaseValueConvertible)?)
{
self.xFunc = xFunc
self.compute = compute
}
}
@@ -305,19 +283,11 @@ 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(XFunc)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
@@ -326,8 +296,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
var definition: AnyObject {
switch self {
case .function(let xFunc):
return FunctionDefinition(xFunc: xFunc)
case .function(let compute):
return FunctionDefinition(compute: compute)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
@@ -342,7 +312,9 @@ public final class DatabaseFunction: Identifiable, Sendable {
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
@@ -492,7 +464,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate: GRDBSendableMetatype {
public protocol DatabaseAggregate: SendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+6 -21
View File
@@ -361,13 +361,8 @@ extension DatabasePool: DatabaseReader {
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()
}
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
@@ -392,13 +387,8 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { 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()
}
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -561,13 +551,8 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { 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()
}
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
+4 -14
View File
@@ -248,13 +248,8 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { 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()
}
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -302,13 +297,8 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
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()
}
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
+2 -6
View File
@@ -201,11 +201,7 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -216,7 +212,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype,
where Downstream: Subscriber & SendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+2 -7
View File
@@ -113,13 +113,8 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// 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()
}
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
}
-4
View File
@@ -43,7 +43,3 @@ 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?
var sqliteStatement: SQLiteStatement? = nil
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?
var value: SQLiteValue? = nil
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+1 -7
View File
@@ -15,13 +15,7 @@ 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
// 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()
}
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -229,11 +229,5 @@ 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?
var api: UnsafePointer<fts5_api>?
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
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?
var tokenizerPointer: OpaquePointer? = nil
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?
var key: String? = nil
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
@@ -360,15 +360,13 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
where RowDecoder: Identifiable & SendableMetatype
{
let databaseTableName = self.databaseTableName
return selectWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(databaseTableName)")
"selectID requires a single-column primary key in the table \(self.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>?
var result: Set<Int64>? = nil
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? // SQLite 3.44.0+
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @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
@@ -457,7 +457,7 @@ extension Table {
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
where RowDecoder: Identifiable & SendableMetatype
{
all().selectID()
}
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord: GRDBSendableMetatype {
public protocol EncodableRecord: SendableMetatype {
/// 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: GRDBSendableMetatype {
public protocol TableRecord: SendableMetatype {
/// A type that defines columns.
///
/// For example:
+2 -4
View File
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
self.attemptToFulfill = attemptToFulfill
}
func receive<S>(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input {
func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
@@ -35,9 +35,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
private class OnDemandFutureSubscription<Downstream>: Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype
{
private class OnDemandFutureSubscription<Downstream: Subscriber & SendableMetatype>: Subscription, @unchecked Sendable {
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
-10
View File
@@ -23,16 +23,6 @@ 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: GRDBSendableMetatype {
public protocol _ValueReducer {
/// The Sendable type that fetches database values
associatedtype Fetcher: _ValueReducerFetcher
@@ -58,7 +58,7 @@ public protocol _ValueReducerFetcher: Sendable {
/// ### Supporting Types
///
/// - ``ValueReducers``
public protocol ValueReducer: _ValueReducer { }
public protocol ValueReducer: _ValueReducer, SendableMetatype { }
/// A namespace for concrete types that adopt the ``ValueReducer`` protocol.
public enum ValueReducers { }
+2 -6
View File
@@ -511,11 +511,7 @@ extension DatabasePublishers {
self.start = start
}
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = ValueSubscription(
start: start,
downstream: subscriber)
@@ -525,7 +521,7 @@ extension DatabasePublishers {
private class ValueSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype,
where Downstream: Subscriber & SendableMetatype,
Downstream.Failure == Error
{
// @unchecked Sendable because `cancellable` and `state` are
+1 -6
View File
@@ -1880,9 +1880,8 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 2600;
LastUpgradeCheck = 1400;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
F3BA80591CFB2BB2003DC1BA = {
@@ -2556,7 +2555,6 @@
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 = (
@@ -2564,7 +2562,6 @@
"@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;
@@ -2591,7 +2588,6 @@
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 = (
@@ -2599,7 +2595,6 @@
"@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 = "2600"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+3 -13
View File
@@ -15,16 +15,6 @@
<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+
@@ -335,7 +325,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/GRDB7MigrationGuide.md)
- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/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)
@@ -2194,7 +2184,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`, `aroundUpdate`, `didUpdate` 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`, `aroundUdate`, `didUdate` are not called.
[PersistableRecord] provides three upsert methods:
@@ -3008,7 +2998,7 @@ try player.insert(db)
> // INSERT OR IGNORE INTO player ... RETURNING *
> do {
> let insertedPlayer = try player.insertAndFetch(db) {
> // Successful insertion
> // Succesful insertion
> catch RecordError.recordNotFound {
> // Failed insertion due to IGNORE policy
> }
+2 -2
View File
@@ -1,4 +1,4 @@
#import <Foundation/Foundation.h>
@import Foundation;
//! 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/GRDB-Bridging.h>
#import "GRDB-Bridging.h"
+1
View File
@@ -18,6 +18,7 @@ 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.

Before

Width:  |  Height:  |  Size: 78 KiB

+2 -1
View File
@@ -1,4 +1,4 @@
#import <Foundation/Foundation.h>
@import Foundation;
//! Project version number for GRDB.
FOUNDATION_EXPORT double GRDB_VersionNumber;
@@ -7,3 +7,4 @@ 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);
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�"
""")
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')")
// 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])
// 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])
}
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"),
[10,9,1,3,2,4,6,5,7,8,11])
[1,3,2,4,6,5,7,8])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCaseInsensitiveCompare.name), id"),
[10,9,1,3,2,4,6,5,7,8,11])
[1,3,2,4,6,5,7,8])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCompare.name), id"),
[10,9,1,3,2,4,6,5,8,7,11])
[1,3,2,4,6,5,8,7])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedStandardCompare.name), id"),
[10,9,1,2,3,4,6,5,8,7,11])
[1,2,3,4,6,5,8,7])
}
}
@@ -1109,67 +1109,4 @@ 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,52 +677,4 @@ 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 = "2600"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"