Merge pull request #1607 from groue/dev/GRDB7-Sendable

GRDB 7: Add missing Sendable conformances
This commit is contained in:
Gwendal Roué authored and GitHub committed 2024-08-31 10:45:19 +02:00
commit bdccd110a7
84 files changed
+808 -641

No files matched your search

+22 -6
View File
@@ -10,7 +10,7 @@ import SQLite3
import Dispatch
import Foundation
public struct Configuration {
public struct Configuration: Sendable {
// MARK: - Misc options
@@ -195,7 +195,7 @@ public struct Configuration {
// MARK: - Managing SQLite Connections
private var setups: [(Database) throws -> Void] = []
private var setups: [@Sendable (Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -232,7 +232,7 @@ public struct Configuration {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
setups.append(setup)
}
@@ -432,9 +432,25 @@ public struct Configuration {
/// through a `SerializedDatabase`.
var threadingMode = Database.ThreadingMode.default
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
private(set) var SQLiteConnectionDidOpen: (@Sendable () -> Void)?
private(set) var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)?
private(set) var SQLiteConnectionDidClose: (@Sendable () -> Void)?
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidOpen(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidOpen = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionWillClose(_ callback: @escaping @Sendable (SQLiteConnection) -> Void) {
SQLiteConnectionWillClose = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidClose(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidClose = callback
}
var SQLiteOpenFlags: CInt {
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
if sqlite3_libversion_number() >= 3037000 {
+4
View File
@@ -909,6 +909,10 @@ public final class FilterCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable.
@available(*, unavailable)
extension FilterCursor: Sendable { }
extension FilterCursor: Cursor {
public func next() throws -> Base.Element? {
while let element = try base.next() {
+35 -11
View File
@@ -122,8 +122,14 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``logError``
/// - ``releaseMemory()``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
///
/// - ``BusyCallback``
/// - ``BusyMode``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``LogErrorFunction``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
@@ -143,8 +149,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The error logging function.
///
/// SQLite can be configured to invoke a callback function containing
/// an error code and a terse error message whenever anomalies occur.
///
/// This global error callback must be configured early in the lifetime
/// of your application:
///
/// ```swift
/// Database.logError = { (resultCode, message) in
/// NSLog("%@", "SQLite error \(resultCode): \(message)")
/// }
/// ```
///
/// - warning: Database.logError must be set before any database
/// connection is opened. This includes the connections that your
/// application opens with GRDB, but also connections opened by
/// other tools, such as third-party libraries. Setting it after a
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
public static var logError: LogErrorFunction? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -361,10 +385,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
private var trace: ((TraceEvent) -> Void)?
/// The registered custom SQL functions.
private var functions = Set<DatabaseFunction>()
private var functions: [DatabaseFunction.ID: DatabaseFunction] = [:]
/// The registered custom SQL collations.
private var collations = Set<DatabaseCollation>()
private var collations: [DatabaseCollation.ID: DatabaseCollation] = [:]
/// Support for `beginReadOnly()` and `endReadOnly()`.
private var readOnlyDepth = 0
@@ -707,13 +731,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// let dbPool = try DatabasePool(path: ..., configuration: config)
/// ```
public func add(function: DatabaseFunction) {
functions.update(with: function)
functions[function.id] = function
function.install(in: self)
}
/// Removes a custom SQL function.
public func remove(function: DatabaseFunction) {
functions.remove(function)
functions.removeValue(forKey: function.id)
function.uninstall(in: self)
}
@@ -734,7 +758,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// let dbPool = try DatabasePool(path: ..., configuration: config)
/// ```
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
collations[collation.id] = collation
let collationPointer = Unmanaged.passUnretained(collation).toOpaque()
let code = sqlite3_create_collation_v2(
sqliteConnection,
@@ -753,7 +777,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Removes a collation.
public func remove(collation: DatabaseCollation) {
collations.remove(collation)
collations.removeValue(forKey: collation.id)
sqlite3_create_collation_v2(
sqliteConnection,
collation.name,
@@ -1830,8 +1854,8 @@ extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
/// See ``BusyMode`` and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
/// to access the database while it is locked by another connection.
@@ -1859,7 +1883,7 @@ extension Database {
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
public enum BusyMode {
public enum BusyMode: Sendable {
/// The `SQLITE_BUSY` error is immediately returned to the connection
/// that tries to access the locked database.
case immediateError
@@ -2019,7 +2043,7 @@ extension Database {
}
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void
/// An SQLite storage class.
///
+29 -21
View File
@@ -29,10 +29,36 @@ import Foundation
/// - ``localizedCompare``
/// - ``localizedStandardCompare``
/// - ``unicodeCompare``
public final class DatabaseCollation {
public final class DatabaseCollation: Identifiable, Sendable {
/// The identifier of an SQLite collation.
///
/// SQLite identifies collations by their name (case insensitive).
public struct ID: Hashable {
var name: String
// Collation equality is based on the sqlite3_strnicmp SQLite function.
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
// a hash value that honors the Swift Hashable contract (value equality
// implies hash equality) is thus non trivial. But it's not that
// important, since this hashValue is only used when one adds
// or removes a collation from a database connection.
public func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
/// Two collations are equal if they share the same name (case insensitive)
public static func == (lhs: Self, rhs: Self) -> Bool {
// See <https://www.sqlite.org/c3ref/create_collation.html>
return sqlite3_stricmp(lhs.name, rhs.name) == 0
}
}
/// The identifier of the collation.
public var id: ID { ID(name: name) }
/// The name of the collation.
public let name: String
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -49,7 +75,7 @@ public final class DatabaseCollation {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
@@ -67,21 +93,3 @@ public final class DatabaseCollation {
}
}
}
extension DatabaseCollation: Hashable {
// Collation equality is based on the sqlite3_strnicmp SQLite function.
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
// a hash value that honors the Swift Hashable contract (value equality
// implies hash equality) is thus non trivial. But it's not that
// important, since this hashValue is only used when one adds
// or removes a collation from a database connection.
public func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
/// Two collations are equal if they share the same name (case insensitive)
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See <https://www.sqlite.org/c3ref/create_collation.html>
return sqlite3_stricmp(lhs.name, rhs.name) == 0
}
}
+4
View File
@@ -415,6 +415,10 @@ extension DatabaseError {
static func connectionIsClosed() -> Self {
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
}
static func snapshotIsLost() -> Self {
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
+21 -28
View File
@@ -29,16 +29,20 @@ import SQLite3
/// - ``localizedUppercase``
/// - ``lowercase``
/// - ``uppercase``
public final class DatabaseFunction: Hashable {
// SQLite identifies functions by (name + argument count)
private struct Identity: Hashable {
public final class DatabaseFunction: Identifiable, Sendable {
/// The identifier of an SQLite function.
///
/// SQLite identifies functions by their name and argument count.
public struct ID: Hashable, Sendable {
let name: String
let nArg: CInt // -1 for variadic functions
}
/// The name of the SQL function
public var name: String { identity.name }
private let identity: Identity
/// The name of the SQL function.
public var name: String { id.name }
/// The identifier of the SQL function.
public let id: ID
let isPure: Bool
private let kind: Kind
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
@@ -82,11 +86,11 @@ public final class DatabaseFunction: Hashable {
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function{ (argc, argv) in
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
@@ -148,7 +152,7 @@ public final class DatabaseFunction: Hashable {
pure: Bool = false,
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .aggregate { Aggregate() }
}
@@ -207,8 +211,8 @@ public final class DatabaseFunction: Hashable {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
identity.name,
identity.nArg,
id.name,
id.nArg,
eTextRep,
definitionP,
kind.xFunc,
@@ -230,8 +234,8 @@ public final class DatabaseFunction: Hashable {
func uninstall(in db: Database) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
identity.name,
identity.nArg,
id.name,
id.nArg,
eTextRep,
nil, nil, nil, nil, nil)
@@ -274,12 +278,12 @@ public final class DatabaseFunction: Hashable {
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind {
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(() -> any DatabaseAggregate)
case aggregate(@Sendable () -> any DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
@@ -424,17 +428,6 @@ public final class DatabaseFunction: Hashable {
}
}
extension DatabaseFunction {
public func hash(into hasher: inout Hasher) {
hasher.combine(identity)
}
/// Two functions are equal if they share the same name and arity.
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
lhs.identity == rhs.identity
}
}
/// The protocol for custom SQLite aggregates.
///
/// For example:
+2 -4
View File
@@ -62,17 +62,15 @@ public final class DatabasePool {
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [readerConfiguration] index in
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
purpose: "reader.\(index)")
})
// Set up journal mode unless readonly
+7 -9
View File
@@ -555,11 +555,9 @@ extension DatabaseReader {
value: @escaping (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
.receiveValues(on: scheduler)
@@ -620,16 +618,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
var isCancelled = false
let cancellable = AnyDatabaseCancellable()
asyncRead { dbResult in
guard !isCancelled else { return }
if cancellable.isCancelled { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
guard !isCancelled else { return }
if cancellable.isCancelled { return }
do {
try onChange(result.get())
} catch {
@@ -637,7 +635,7 @@ extension DatabaseReader {
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
return cancellable
}
}
}
+5 -5
View File
@@ -416,7 +416,7 @@ private struct TableRegion: Equatable {
/// ### Supporting Types
///
/// - ``AnyDatabaseRegionConvertible``
public protocol DatabaseRegionConvertible {
public protocol DatabaseRegionConvertible: Sendable {
/// Returns a database region.
///
/// - parameter db: A database connection.
@@ -437,14 +437,14 @@ extension DatabaseRegion: DatabaseRegionConvertible {
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: (Database) throws -> DatabaseRegion
let _region: @Sendable (Database) throws -> DatabaseRegion
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
_region = region
}
public init(_ region: some DatabaseRegionConvertible) {
_region = region.databaseRegion
_region = { try region.databaseRegion($0) }
}
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
@@ -461,7 +461,7 @@ extension DatabaseRegion {
}
}
static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion {
static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion {
return { db in
try regions.reduce(into: DatabaseRegion()) { union, region in
try union.formUnion(region.databaseRegion(db))
+2 -2
View File
@@ -3,10 +3,10 @@ import Combine
#endif
import Foundation
public struct DatabaseRegionObservation {
public struct DatabaseRegionObservation: Sendable {
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: (Database) throws -> DatabaseRegion
var observedRegion: @Sendable (Database) throws -> DatabaseRegion
}
extension DatabaseRegionObservation {
+9 -12
View File
@@ -130,6 +130,7 @@ public final class DatabaseSnapshotPool {
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
// Acquire and hold WAL snapshot
@@ -138,7 +139,7 @@ public final class DatabaseSnapshotPool {
}
var holderConfig = Configuration()
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
@@ -158,20 +159,18 @@ public final class DatabaseSnapshotPool {
}
self.configuration = configuration
self.path = db.path
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: db.path,
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -219,17 +218,15 @@ public final class DatabaseSnapshotPool {
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -321,7 +318,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return try reader.reentrantSync { db in
let result = try value(db)
if snapshotIsLost(db) {
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
throw DatabaseError.snapshotIsLost()
}
return result
}
+7 -5
View File
@@ -171,7 +171,9 @@ extension FetchRequest {
///
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
public func adapted(
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
}
@@ -181,11 +183,11 @@ extension FetchRequest {
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: (Database) throws -> any RowAdapter
let adapter: @Sendable (Database) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
@@ -274,7 +276,7 @@ extension AnyFetchRequest: FetchRequest {
}
// Class-based type erasure, so that we preserve full type information.
private class FetchRequestEraser: FetchRequest {
private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
typealias RowDecoder = Void
var sqlSubquery: SQLSubquery {
@@ -290,7 +292,7 @@ private class FetchRequestEraser: FetchRequest {
}
}
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser {
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser, @unchecked Sendable {
let request: Request
init(request: Request) {
+3 -3
View File
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
/// - ``RenameColumnAdapter``
/// - ``ScopeAdapter``
/// - ``SuffixRowAdapter``
public protocol RowAdapter {
public protocol RowAdapter: Sendable {
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
/// print(Array(adaptedRow.columnNames))
/// ```
public struct RenameColumnAdapter: RowAdapter {
let transform: (String) -> String
let transform: @Sendable (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping (String) -> String) {
public init(_ transform: @escaping @Sendable (String) -> String) {
self.transform = transform
}
+1 -1
View File
@@ -39,7 +39,7 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
public struct SQL {
public struct SQL: Sendable {
/// `SQL.Element` is a component of an `SQL` literal.
///
/// Elements can be qualified with table aliases, and this is how `SQL`
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock {
public protocol TransactionClock: Sendable {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: (Database) throws -> Date
let _now: @Sendable (Database) throws -> Date
public init(_ now: @escaping (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
self._now = now
}
+56 -24
View File
@@ -3,9 +3,28 @@
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
class WALSnapshotTransaction {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
final class WALSnapshotTransaction: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a mutex.
private struct DatabaseAccess {
let reader: SerializedDatabase
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
func commitAndRelease() {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
}
}
// TODO: consider using the serialized DispatchQueue of reader instead of a lock.
/// nil when closed
private let databaseAccessMutex: Mutex<DatabaseAccess?>
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -36,10 +55,11 @@ class WALSnapshotTransaction {
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping (_ isInsideTransaction: Bool) -> Void)
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
assert(reader.configuration.readonly)
let databaseAccess = DatabaseAccess(reader: reader, release: release)
do {
// Open a long-lived transaction, and enter snapshot isolation
@@ -50,44 +70,56 @@ class WALSnapshotTransaction {
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.reader = reader
self.release = release
self.databaseAccessMutex = Mutex(databaseAccess)
} catch {
// self is not initialized, so deinit will not run.
Self.commitAndRelease(reader: reader, release: release)
databaseAccess.commitAndRelease()
throw error
}
}
deinit {
Self.commitAndRelease(reader: reader, release: release)
close()
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
try reader.sync(value)
func read<T>(_ value: (Database) throws -> T) throws -> T {
try databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
return try databaseAccess.reader.sync(value)
}
}
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping (Database) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
databaseAccess.reader.async { db in
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
// At least check if self was closed:
if self.databaseAccessMutex.load() == nil {
value(.failure(DatabaseError.snapshotIsLost()))
}
value(.success(db))
}
}
}
private static func commitAndRelease(
reader: SerializedDatabase,
release: (_ isInsideTransaction: Bool) -> Void)
{
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
func close() {
databaseAccessMutex.withLock { databaseAccess in
databaseAccess?.commitAndRelease()
databaseAccess = nil
}
release(isInsideTransaction)
}
}
#endif
@@ -313,6 +313,6 @@ When needed, you can help GRDB optimize observations and reduce database content
- ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)``
- ``print(_:to:)``
### Support
### Supporting Types
- ``ValueReducer``
+2 -2
View File
@@ -40,7 +40,7 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks: Sendable {
/// The migration runs with disabled foreign keys.
@@ -207,7 +207,7 @@ public struct DatabaseMigrator {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping (Database) throws -> Void)
migrate: @escaping @Sendable (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
+2 -2
View File
@@ -1,5 +1,5 @@
/// An internal struct that defines a migration.
struct Migration {
struct Migration: Sendable {
enum ForeignKeyChecks {
case deferred
case immediate
@@ -8,7 +8,7 @@ struct Migration {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: (Database) throws -> Void
let migrate: @Sendable (Database) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
@@ -173,7 +173,9 @@ extension Association {
// SelectionRequest conformance
extension Association {
public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.selectWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -181,7 +183,9 @@ extension Association {
}
}
public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.annotatedWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -192,7 +196,9 @@ extension Association {
// FilteredRequest conformance
extension Association {
public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.filterWhenConnected { db in
try predicate(db).sqlExpression
@@ -203,7 +209,9 @@ extension Association {
// OrderedRequest conformance
extension Association {
public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self {
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
) -> Self {
withDestinationRelation { relation in
relation = relation.orderWhenConnected { db in
try orderings(db).map(\.sqlOrdering)
@@ -239,7 +247,9 @@ extension Association {
// AggregatingRequest conformance
extension Association {
public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self {
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]
) -> Self {
withDestinationRelation { relation in
relation = relation.groupWhenConnected { db in
try expressions(db).map(\.sqlExpression)
@@ -247,7 +257,9 @@ extension Association {
}
}
public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.havingWhenConnected { db in
try predicate(db).sqlExpression
@@ -385,7 +385,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -421,7 +421,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Destination.Type,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
@@ -458,7 +458,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Table<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -118,7 +118,7 @@ extension QueryInterfaceRequest: FetchRequest {
extension QueryInterfaceRequest: SelectionRequest {
public func selectWhenConnected(
_ selection: @escaping (Database) throws -> [any SQLSelectable])
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -282,7 +282,7 @@ extension QueryInterfaceRequest: SelectionRequest {
}
public func annotatedWhenConnected(
with selection: @escaping (Database) throws -> [any SQLSelectable])
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -295,7 +295,7 @@ extension QueryInterfaceRequest: SelectionRequest {
extension QueryInterfaceRequest: FilteredRequest {
public func filterWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -308,7 +308,7 @@ extension QueryInterfaceRequest: FilteredRequest {
extension QueryInterfaceRequest: OrderedRequest {
public func orderWhenConnected(
_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm])
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
-> Self
{
with {
@@ -355,7 +355,7 @@ extension QueryInterfaceRequest: OrderedRequest {
extension QueryInterfaceRequest: AggregatingRequest {
public func groupWhenConnected(
_ expressions: @escaping (Database) throws -> [any SQLExpressible])
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
-> Self
{
with {
@@ -366,7 +366,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
public func havingWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -58,7 +58,9 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self
/// Appends result columns to the selected columns.
///
@@ -78,7 +80,9 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self
}
extension SelectionRequest {
@@ -240,7 +244,9 @@ public protocol FilteredRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self
}
extension FilteredRequest {
@@ -764,7 +770,9 @@ public protocol AggregatingRequest {
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self
func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]
) -> Self
/// Filters the aggregated groups with a boolean SQL expression.
///
@@ -788,7 +796,9 @@ public protocol AggregatingRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self
}
extension AggregatingRequest {
@@ -969,7 +979,9 @@ public protocol OrderedRequest {
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self
func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
) -> Self
/// Returns a request with reversed ordering.
///
@@ -23,20 +23,20 @@
/// see SQLRelation.filterPromise.
struct DatabasePromise<T> {
/// Returns the resolved value.
let resolve: (Database) throws -> T
let resolve: @Sendable (Database) throws -> T
/// Creates a promise that resolves to a value.
init(value: T) {
init(value: T) where T: Sendable {
self.resolve = { _ in value }
}
/// Creates a promise from a closure.
init(_ resolve: @escaping (Database) throws -> T) {
init(_ resolve: @escaping @Sendable (Database) throws -> T) {
self.resolve = resolve
}
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
func map<U>(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(resolve(db))
}
+1 -1
View File
@@ -34,7 +34,7 @@
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html>
public struct SQLExpression {
public struct SQLExpression: Sendable {
private var impl: Impl
/// The preferred interpretation of the expression in JSON
+1 -1
View File
@@ -12,7 +12,7 @@
/// function arguments, prefer the ``SQLOrderingTerm`` protocol.
///
/// Related SQLite documentation: <https://www.sqlite.org/syntax/ordering-term.html>
public struct SQLOrdering {
public struct SQLOrdering: Sendable {
private var impl: Impl
private enum Impl {
+13 -16
View File
@@ -90,7 +90,7 @@
/// // JOIN passport ON passport.citizenId = citizens.id
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...);
/// Country.including(all: Country.citizens)
struct SQLRelation {
struct SQLRelation: Sendable {
struct Child: Refinable {
enum Kind {
// Record.including(optional: association)
@@ -187,7 +187,7 @@ extension SQLRelation {
/// Convenience factory methods which selects all rows from a table.
static func all(
fromTable tableName: String,
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
@@ -672,7 +672,7 @@ struct SQLLimit {
// MARK: - SQLSource
struct SQLSource {
struct SQLSource: Sendable {
var tableName: String
var alias: TableAlias?
@@ -691,7 +691,7 @@ struct SQLSource {
extension SQLRelation {
/// SQLRelation.Ordering provides the order clause to SQLRelation.
struct Ordering {
struct Ordering: Sendable {
private enum Element {
case terms(DatabasePromise<[SQLOrdering]>)
case ordering(SQLRelation.Ordering)
@@ -740,7 +740,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping (Database) throws -> [SQLOrdering]) {
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
self.init(
elements: [.terms(DatabasePromise(orderings))],
isReversed: false)
@@ -796,7 +796,7 @@ extension SQLRelation {
/// // SELECT * FROM book WHERE author.id = 1
/// // ~~~~~~~~~~~~~
/// author.request(for: Author.books)
enum SQLAssociationCondition {
enum SQLAssociationCondition: Sendable {
/// A condition based on a foreign key.
case foreignKey(SQLForeignKeyCondition)
@@ -814,7 +814,7 @@ enum SQLAssociationCondition {
/// player[Column("id")] == bonus[Column("playerID")]
/// })
/// Player.with(bonus).joining(required: association)
case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
/// The condition that does not constrain the two associated tables
/// in any way.
@@ -1027,9 +1027,6 @@ extension Row: ColumnAddressable {
/// PersistenceContainer has columns
extension PersistenceContainer: ColumnAddressable {
func index(forColumn column: String) -> String? { column }
func databaseValue(at column: String) -> DatabaseValue {
self[caseInsensitive: column]?.databaseValue ?? .null
}
}
// MARK: - Merging
+1 -1
View File
@@ -15,7 +15,7 @@
/// function arguments, prefer the ``SQLSelectable`` protocol.
///
/// Related SQLite documentation: <https://www.sqlite.org/syntax/result-column.html>
public struct SQLSelection {
public struct SQLSelection: Sendable {
private var impl: Impl
/// The private implementation of the public `SQLSelection`.
+1 -1
View File
@@ -1,7 +1,7 @@
/// An SQL subquery.
///
/// `SQLSubquery` is an opaque representation of an SQL subquery.
public struct SQLSubquery {
public struct SQLSubquery: Sendable {
private var impl: Impl
private enum Impl {
+1 -1
View File
@@ -1297,7 +1297,7 @@ extension Table {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -213,7 +213,9 @@ class StatementArgumentsSink {
/// See ``TableRequest/aliased(_:)`` for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public class TableAlias {
public class TableAlias: @unchecked Sendable {
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
// TODO: GRDB7 Make TableAlias really Sendable
private enum Impl {
/// A TableAlias is undefined when it is created by the GRDB user:
///
@@ -339,7 +339,7 @@ extension TableRecord {
/// - returns: An association to the common table expression.
public static func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<Self, Destination>
{
JoinAssociation(
+46 -63
View File
@@ -258,7 +258,7 @@ extension EncodableRecord {
/// database representation.
public var databaseDictionary: [String: DatabaseValue] {
get throws {
try Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null }
try Dictionary(uniqueKeysWithValues: PersistenceContainer(self))
}
}
}
@@ -336,19 +336,30 @@ extension EncodableRecord {
///
/// `PersistenceContainer` is the argument of the
/// ``EncodableRecord/encode(to:)-k9pf`` method.
public struct PersistenceContainer {
// fileprivate for Row(_:PersistenceContainer)
public struct PersistenceContainer: Sendable {
// The ordering of the OrderedDictionary helps generating always the same
// SQL queries, and hit the statement cache.
fileprivate var storage: OrderedDictionary<String, (any DatabaseValueConvertible)?>
private var storage: OrderedDictionary<CaseInsensitiveIdentifier, DatabaseValue>
/// The value associated with the given column.
///
/// The setter accepts any ``DatabaseValueConvertible`` type, but the
/// getter always returns a ``DatabaseValue``.
public subscript(_ column: String) -> (any DatabaseValueConvertible)? {
get { self[caseInsensitive: column] }
set { storage.updateValue(newValue, forKey: column) }
get {
storage[CaseInsensitiveIdentifier(rawValue: column)]
}
set {
storage.updateValue(
newValue?.databaseValue ?? .null,
forKey: CaseInsensitiveIdentifier(rawValue: column))
}
}
/// The value associated with the given column.
///
/// The setter accepts any ``DatabaseValueConvertible`` type, but the
/// getter always returns a ``DatabaseValue``.
public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? {
get { self[column.name] }
set { self[column.name] = newValue }
@@ -378,66 +389,25 @@ public struct PersistenceContainer {
}
/// Columns stored in the container, ordered like values.
var columns: [String] { Array(storage.keys) }
var columns: [String] { storage.keys.map(\.rawValue) }
/// Values stored in the container, ordered like columns.
var values: [(any DatabaseValueConvertible)?] { Array(storage.values) }
var values: [DatabaseValue] { storage.values }
/// Accesses the value associated with the given column, in a
/// case-insensitive fashion.
subscript(caseInsensitive column: String) -> (any DatabaseValueConvertible)? {
get {
if let value = storage[column] {
return value
}
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value
}
return nil
}
set {
if storage[column] != nil {
storage[column] = newValue
return
}
let lowercaseColumn = column.lowercased()
for key in storage.keys where key.lowercased() == lowercaseColumn {
storage[key] = newValue
return
}
storage[column] = newValue
}
}
// Returns nil if column is not defined
func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? {
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value?.databaseValue ?? .null
}
return nil
}
var isEmpty: Bool { storage.isEmpty }
/// An iterator over the (column, value) pairs
func makeIterator() -> IndexingIterator<OrderedDictionary<String, (any DatabaseValueConvertible)?>> {
storage.makeIterator()
/// Returns ``DatabaseValue/null`` if column is not defined
func databaseValue(at column: String) -> DatabaseValue {
storage[CaseInsensitiveIdentifier(rawValue: column)] ?? .null
}
@usableFromInline
func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> {
var newValueIterator = makeIterator()
var newValueIterator = storage.makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let oldValue = container[caseInsensitive: column]
let oldDbValue = oldValue?.databaseValue ?? .null
let newDbValue = newValue?.databaseValue ?? .null
while let (column, newDbValue) = newValueIterator.next() {
let oldDbValue = container.storage[column] ?? .null
if newDbValue != oldDbValue {
return (column, oldDbValue)
return (column.rawValue, oldDbValue)
}
}
return nil
@@ -445,13 +415,26 @@ public struct PersistenceContainer {
}
}
extension PersistenceContainer: RandomAccessCollection {
public typealias Index = Int
public var startIndex: Int { storage.startIndex }
public var endIndex: Int { storage.endIndex }
/// Returns the (column, value) pair at given index.
public subscript(position: Int) -> (String, DatabaseValue) {
let element = storage[position]
return (element.key.rawValue, element.value)
}
}
extension Row {
convenience init<Record: EncodableRecord>(_ record: Record) throws {
try self.init(PersistenceContainer(record))
}
convenience init(_ container: PersistenceContainer) {
self.init(Dictionary(container.storage))
self.init(impl: ArrayRowImpl(columns: container.lazy.map { ($0, $1) }))
}
}
@@ -474,7 +457,7 @@ extension Row {
/// var jsonData: Data
/// }
/// ```
public enum DatabaseDataEncodingStrategy {
public enum DatabaseDataEncodingStrategy: Sendable {
/// Encodes `Data` columns as SQL blob.
case deferredToData
@@ -482,7 +465,7 @@ public enum DatabaseDataEncodingStrategy {
case text
/// Encodes `Data` column as the result of the user-provided function.
case custom((Data) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) -> DatabaseValue {
switch self {
@@ -518,7 +501,7 @@ public enum DatabaseDataEncodingStrategy {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy {
public enum DatabaseDateEncodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
@@ -548,7 +531,7 @@ public enum DatabaseDateEncodingStrategy {
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?)
private static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
@@ -638,7 +621,7 @@ public enum DatabaseUUIDEncodingStrategy: Sendable {
/// var playerID: String
/// }
/// ```
public enum DatabaseColumnEncodingStrategy {
public enum DatabaseColumnEncodingStrategy: Sendable {
/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
@@ -646,7 +629,7 @@ public enum DatabaseColumnEncodingStrategy {
case convertToSnakeCase
/// A key encoding strategy defined by the closure you supply.
case custom((any CodingKey) -> String)
case custom(@Sendable (any CodingKey) -> String)
func column(forKey key: some CodingKey) -> String {
switch self {
+6 -6
View File
@@ -882,7 +882,7 @@ extension RecordCursor: Sendable { }
/// var myData: Data
/// }
/// ```
public enum DatabaseDataDecodingStrategy {
public enum DatabaseDataDecodingStrategy: Sendable {
/// Decodes `Data` columns from SQL blobs and UTF8 text.
case deferredToData
@@ -891,7 +891,7 @@ public enum DatabaseDataDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Data?)
case custom(@Sendable (DatabaseValue) -> Data?)
}
// MARK: - DatabaseDateDecodingStrategy
@@ -910,7 +910,7 @@ public enum DatabaseDataDecodingStrategy {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy {
public enum DatabaseDateDecodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
@@ -951,7 +951,7 @@ public enum DatabaseDateDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Date?)
case custom(@Sendable (DatabaseValue) -> Date?)
}
// MARK: - DatabaseColumnDecodingStrategy
@@ -968,7 +968,7 @@ public enum DatabaseDateDecodingStrategy {
/// // Decoded from the player_id column
/// var playerID: Int
/// }
public enum DatabaseColumnDecodingStrategy {
public enum DatabaseColumnDecodingStrategy: Sendable {
/// A key decoding strategy that doesn’t change key names during decoding.
case useDefaultKeys
@@ -976,7 +976,7 @@ public enum DatabaseColumnDecodingStrategy {
case convertFromSnakeCase
/// A key decoding strategy defined by the closure you supply.
case custom((String) -> CodingKey)
case custom(@Sendable (String) -> CodingKey)
func key<K: CodingKey>(forColumn column: String) -> K? {
switch self {
@@ -142,7 +142,7 @@ final class DAO<Record: MutablePersistableRecord> {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
persistenceContainer.databaseValue(at: $0)
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
@@ -173,7 +173,7 @@ final class DAO<Record: MutablePersistableRecord> {
}
let updatedValues = updatedColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
persistenceContainer.databaseValue(at: $0)
}
let query = UpdateQuery(
@@ -193,7 +193,7 @@ final class DAO<Record: MutablePersistableRecord> {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
persistenceContainer.databaseValue(at: $0)
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
@@ -212,7 +212,7 @@ final class DAO<Record: MutablePersistableRecord> {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
persistenceContainer.databaseValue(at: $0)
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
@@ -229,7 +229,7 @@ final class DAO<Record: MutablePersistableRecord> {
/// Throws a RecordError.recordNotFound error
func recordNotFound() throws -> Never {
let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map {
($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null)
($0, persistenceContainer.databaseValue(at: $0))
})
throw RecordError.recordNotFound(
databaseTableName: databaseTableName,
@@ -525,7 +525,7 @@ extension MutablePersistableRecord {
// to false in its `aroundInsert` callback.
var persistenceContainer = dao.persistenceContainer
if let rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowid
persistenceContainer[rowIDColumn] = rowid
}
let inserted = InsertionSuccess(
@@ -409,7 +409,7 @@ extension MutablePersistableRecord {
let primaryKeyInfo = try db.primaryKey(databaseTableName)
let container = try PersistenceContainer(db, self)
let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map {
($0, container[caseInsensitive: $0]?.databaseValue ?? .null)
($0, container.databaseValue(at: $0))
})
if primaryKey.allSatisfy({ $0.value.isNull }) {
return nil
@@ -452,7 +452,7 @@ extension MutablePersistableRecord {
var persistenceContainer = dao.persistenceContainer
let rowIDColumn = dao.primaryKey.rowIDColumn
if let rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowid
persistenceContainer[rowIDColumn] = rowid
}
let inserted = InsertionSuccess(
+1 -2
View File
@@ -201,8 +201,7 @@ open class Record {
var newValueIterator = try PersistenceContainer(self).makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let newDbValue = newValue?.databaseValue ?? .null
while let (column, newDbValue) = newValueIterator.next() {
guard let oldRow, let oldDbValue: DatabaseValue = oldRow[column] else {
return (column, nil)
}
+1 -1
View File
@@ -763,7 +763,7 @@ extension TableRecord where Self: EncodableRecord {
let container = try PersistenceContainer(db, self)
let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map {
($0, container[caseInsensitive: $0]?.databaseValue ?? .null)
($0, container.databaseValue(at: $0))
})
return RecordError.recordNotFound(
databaseTableName: databaseTableName,
+7 -3
View File
@@ -14,9 +14,12 @@ import Foundation
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
///
/// OnDemandFuture also adds Sendable requirements that avoid
/// compiler warnings.
@available(iOS 13, macOS 10.15, tvOS 13, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = (Result<Output, Failure>) -> Void
typealias Promise = @Sendable (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
@@ -34,8 +37,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
+2
View File
@@ -207,6 +207,8 @@ extension OrderedDictionary: CustomStringConvertible {
}
}
extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable { }
extension Dictionary {
init(_ orderedDictionary: OrderedDictionary<Key, Value>) {
self = orderedDictionary.dictionary
+32 -18
View File
@@ -35,8 +35,9 @@ import Dispatch
/// got 2
/// got 1
/// got 3
final class Pool<T> {
private class Item {
final class Pool<T: Sendable>: Sendable {
private class Item: @unchecked Sendable {
// @unchecked because `isAvailable` is protected by `Pool.content`.
let element: T
var isAvailable: Bool
@@ -46,8 +47,19 @@ final class Pool<T> {
}
}
private let makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private struct Content {
var items: [Item]
/// The number of created items. May become greater than the number
/// of elements in items, as some items are destroyed and other
/// are created.
var createdCount = 0
}
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
private let makeElement: @Sendable (Int) throws -> T
private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0))
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
@@ -59,11 +71,12 @@ final class Pool<T> {
/// - maximumCount: The maximum number of elements.
/// - qos: The quality of service of asynchronous accesses.
/// - makeElement: A function that creates an element. It is called
/// on demand.
/// on demand. Its argument is the index of the created elements
/// (1, then 2, etc).
init(
maximumCount: Int,
qos: DispatchQoS = .unspecified,
makeElement: @escaping () throws -> T)
makeElement: @escaping @Sendable (_ index: Int) throws -> T)
{
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
@@ -75,19 +88,20 @@ final class Pool<T> {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
func get() throws -> ElementAndRelease {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
let item = try content.update { content -> Item in
if let item = content.items.first(where: \.isAvailable) {
item.isAvailable = false
return item
} else {
let element = try makeElement()
content.createdCount += 1
let element = try makeElement(content.createdCount)
let item = Item(element: element, isAvailable: false)
items.append(item)
content.items.append(item)
return item
}
}
@@ -107,7 +121,7 @@ final class Pool<T> {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
func asyncGet(_ execute: @escaping (Result<ElementAndRelease, Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -128,7 +142,7 @@ final class Pool<T> {
}
private func release(_ item: Item, completion: PoolCompletion) {
$items.update { items in
content.update { content in
switch completion {
case .reuse:
// This is why Item is a class, not a struct: so that we can
@@ -136,8 +150,8 @@ final class Pool<T> {
item.isAvailable = true
case .discard:
// Discard should be rare: perform lookup.
if let index = items.firstIndex(where: { $0 === item }) {
items.remove(at: index)
if let index = content.items.firstIndex(where: { $0 === item }) {
content.items.remove(at: index)
}
}
}
@@ -148,8 +162,8 @@ final class Pool<T> {
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
try $items.read { items in
for item in items {
try content.read { content in
for item in content.items {
try body(item.element)
}
}
@@ -158,7 +172,7 @@ final class Pool<T> {
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
items = []
content.update { $0.items.removeAll() }
}
/// Blocks until no element is used, and runs the `barrier` function before
+2 -1
View File
@@ -3,7 +3,8 @@ import Dispatch
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a
/// value. It is backed by a concurrent DispatchQueue.
@propertyWrapper
final class ReadWriteBox<T> {
final class ReadWriteBox<T: Sendable>: @unchecked Sendable {
// @unchecked because `_wrappedValue` is protected by `queue`
private var _wrappedValue: T
private var queue: DispatchQueue
+21 -13
View File
@@ -5,7 +5,7 @@
/// ### Supporting Types
///
/// - ``AnyDatabaseCancellable``
public protocol DatabaseCancellable {
public protocol DatabaseCancellable: Sendable {
/// Cancel the activity.
func cancel()
}
@@ -15,31 +15,39 @@ public protocol DatabaseCancellable {
///
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized.
public class AnyDatabaseCancellable: DatabaseCancellable {
private var _cancel: (() -> Void)?
public final class AnyDatabaseCancellable: DatabaseCancellable {
private let cancelMutex: Mutex<(@Sendable () -> Void)?>
var isCancelled: Bool {
cancelMutex.withLock { $0 == nil }
}
convenience init() {
self.init(cancel: { })
}
/// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping () -> Void) {
_cancel = cancel
public init(cancel: @escaping @Sendable () -> Void) {
cancelMutex = Mutex(cancel)
}
/// Creates a cancellable object that forwards cancellation to `base`.
public convenience init(_ base: some DatabaseCancellable) {
var cancellable = Optional.some(base)
self.init {
cancellable?.cancel()
cancellable = nil // Release memory
base.cancel()
}
}
deinit {
_cancel?()
cancel()
}
public func cancel() {
// Don't prevent multiple concurrent calls to _cancel, because it is
// pointless. But release memory!
_cancel?()
_cancel = nil
let cancel = cancelMutex.withLock {
let cancel = $0
$0 = nil
return cancel
}
cancel?()
}
}
@@ -76,25 +76,25 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
/// The observed DatabasePool.
let dbPool: DatabasePool
/// A reducer that fetches database values.
private let reducer: Reducer
/// The fetcher that fetches database values.
private let fetcher: Reducer.Fetcher
init(dbPool: DatabasePool, reducer: Reducer) {
init(dbPool: DatabasePool, fetcher: Reducer.Fetcher) {
self.dbPool = dbPool
self.reducer = reducer
self.fetcher = fetcher
}
func fetch(_ db: Database) throws -> Reducer.Fetched {
func fetch(_ db: Database) throws -> Reducer.Fetcher.Value {
try db.isolated(readOnly: true) {
try reducer._fetch(db)
try fetcher.fetch(db)
}
}
func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetched, DatabaseRegion) {
func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) {
var region = DatabaseRegion()
let fetchedValue = try db.isolated(readOnly: true) {
try db.recordingSelection(&region) {
try reducer._fetch(db)
try fetcher.fetch(db)
}
}
return try (fetchedValue, region.observableRegion(db))
@@ -170,9 +170,9 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
// State
self.databaseAccess = DatabaseAccess(
dbPool: dbPool,
// ValueReducer semantics guarantees that reducer._fetch
// ValueReducer semantics guarantees that the fetcher
// is independent from the reducer state
reducer: reducer)
fetcher: reducer._makeFetcher())
self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange)
self.reducer = reducer
self.reduceQueue = DispatchQueue(
@@ -298,7 +298,9 @@ extension ValueConcurrentObserver {
return try syncStartWithoutWALSnapshot(from: databaseAccess)
}
let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialFetchTransaction.read { db in
let fetchedValue: Reducer.Fetcher.Value
let initialRegion: DatabaseRegion
(fetchedValue, initialRegion) = try initialFetchTransaction.read { db in
switch trackingMode {
case let .constantRegion(regions):
let fetchedValue = try databaseAccess.fetch(db)
@@ -352,10 +354,11 @@ extension ValueConcurrentObserver {
let initialFetchTransaction = try result.get()
// Second async jump because that's how
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
initialFetchTransaction.asyncRead { db in
initialFetchTransaction.asyncRead { dbResult in
do {
let fetchedValue: Reducer.Fetched
let fetchedValue: Reducer.Fetcher.Value
let initialRegion: DatabaseRegion
let db = try dbResult.get()
switch self.trackingMode {
case let .constantRegion(regions):
@@ -429,11 +432,9 @@ extension ValueConcurrentObserver {
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// However, we want to close `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
// available for other reads.
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
let events = self.lock.synchronized { self.notificationCallbacks?.events }
@@ -446,7 +447,7 @@ extension ValueConcurrentObserver {
// Was the database modified since the initial fetch?
let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering")
isModified = ordering < 0
} else {
@@ -454,15 +455,15 @@ extension ValueConcurrentObserver {
isModified = true
}
// Comparison done: end the WAL snapshot transaction
// Comparison done: close the WAL snapshot transaction
// and release its reader connection.
initialFetchTransaction = nil
initialFetchTransaction.close()
if isModified {
events.databaseDidChange?()
// Fetch
let fetchedValue: Reducer.Fetched
let fetchedValue: Reducer.Fetcher.Value
switch self.trackingMode {
case .constantRegion:
@@ -539,7 +540,9 @@ extension ValueConcurrentObserver {
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// transaction to complete.
let (fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db -> (Reducer.Fetched, DatabaseRegion) in
let fetchedValue: Reducer.Fetcher.Value
let initialRegion: DatabaseRegion
(fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db in
switch trackingMode {
case let .constantRegion(regions):
let fetchedValue = try databaseAccess.fetch(db)
@@ -584,7 +587,7 @@ extension ValueConcurrentObserver {
do {
// Fetch
let fetchedValue: Reducer.Fetched
let fetchedValue: Reducer.Fetcher.Value
let initialRegion: DatabaseRegion
let db = try dbResult.get()
switch self.trackingMode {
@@ -644,7 +647,7 @@ extension ValueConcurrentObserver {
do {
try writerDB.isolated(readOnly: true) {
// Fetch
let fetchedValue: Reducer.Fetched
let fetchedValue: Reducer.Fetcher.Value
let observedRegion: DatabaseRegion
switch self.trackingMode {
case .constantRegion:
@@ -823,7 +826,7 @@ extension ValueConcurrentObserver: TransactionObserver {
}
}
private func reduce(_ fetchResult: Result<Reducer.Fetched, Error>) {
private func reduce(_ fetchResult: Result<Reducer.Fetcher.Value, Error>) {
reduceQueue.async {
do {
let fetchedValue = try fetchResult.get()
@@ -83,26 +83,26 @@ final class ValueWriteOnlyObserver<
/// If true, database values are fetched from a read-only access.
private let readOnly: Bool
/// A reducer that fetches database values.
private let reducer: Reducer
/// The fetcher that fetches database values.
private let fetcher: Reducer.Fetcher
init(writer: Writer, readOnly: Bool, reducer: Reducer) {
init(writer: Writer, readOnly: Bool, fetcher: Reducer.Fetcher) {
self.writer = writer
self.readOnly = readOnly
self.reducer = reducer
self.fetcher = fetcher
}
func fetch(_ db: Database) throws -> Reducer.Fetched {
func fetch(_ db: Database) throws -> Reducer.Fetcher.Value {
try db.isolated(readOnly: readOnly) {
try reducer._fetch(db)
try fetcher.fetch(db)
}
}
func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetched, DatabaseRegion) {
func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) {
var region = DatabaseRegion()
let fetchedValue = try db.isolated(readOnly: readOnly) {
try db.recordingSelection(&region) {
try reducer._fetch(db)
try fetcher.fetch(db)
}
}
return try (fetchedValue, region.observableRegion(db))
@@ -160,9 +160,9 @@ final class ValueWriteOnlyObserver<
self.databaseAccess = DatabaseAccess(
writer: writer,
readOnly: readOnly,
// ValueReducer semantics guarantees that reducer._fetch
// ValueReducer semantics guarantees that the fetcher
// is independent from the reducer state
reducer: reducer)
fetcher: reducer._makeFetcher())
self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange)
self.reducer = reducer
self.reduceQueue = DispatchQueue(
@@ -301,7 +301,7 @@ extension ValueWriteOnlyObserver {
/// By grouping the initial fetch and the beginning of observation in a
/// single database access, we are sure that no concurrent write can happen
/// during the initial fetch, and that we won't miss any future change.
private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? {
private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetcher.Value? {
let (events, databaseAccess) = lock.synchronized {
(notificationCallbacks?.events, self.databaseAccess)
}
@@ -380,7 +380,7 @@ extension ValueWriteOnlyObserver: TransactionObserver {
do {
// Fetch
let fetchedValue: Reducer.Fetched
let fetchedValue: Reducer.Fetcher.Value
switch trackingMode {
case .constantRegion, .constantRegionRecordedFromSelection:
+16 -8
View File
@@ -1,16 +1,24 @@
extension ValueReducers {
/// A `ValueReducer` that perform database fetches.
public struct Fetch<Value>: ValueReducer {
private let __fetch: (Database) throws -> Value
/// Creates a reducer which passes raw fetched values through.
init(fetch: @escaping (Database) throws -> Value) {
self.__fetch = fetch
public struct _Fetcher: _ValueReducerFetcher {
let _fetch: @Sendable (Database) throws -> Value
public func fetch(_ db: Database) throws -> Value {
assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal")
return try _fetch(db)
}
}
public func _fetch(_ db: Database) throws -> Value {
assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal")
return try __fetch(db)
private let _fetch: @Sendable (Database) throws -> Value
/// Creates a reducer which passes raw fetched values through.
init(fetch: @escaping @Sendable (Database) throws -> Value) {
self._fetch = fetch
}
public func _makeFetcher() -> _Fetcher {
_Fetcher(_fetch: _fetch)
}
public func _value(_ fetched: Value) -> Value? {
+7 -9
View File
@@ -26,11 +26,11 @@ extension ValueObservation {
}
extension ValueReducers {
/// A `ValueReducer` whose values consist of those in a `Base` reduced
/// A `ValueReducer` whose values consist of those in a `Base` reducer
/// passed through a transform function.
///
/// See ``ValueObservation/map(_:)``.
public struct Map<Base: _ValueReducer, Value>: _ValueReducer {
public struct Map<Base: _ValueReducer, Value>: ValueReducer {
private var base: Base
private let transform: (Base.Value) throws -> Value
@@ -39,15 +39,13 @@ extension ValueReducers {
self.transform = transform
}
public mutating func _value(_ fetched: Base.Fetched) throws -> Value? {
public func _makeFetcher() -> Base.Fetcher {
base._makeFetcher()
}
public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Value? {
guard let value = try base._value(fetched) else { return nil }
return try transform(value)
}
}
}
extension ValueReducers.Map: ValueReducer where Base: ValueReducer {
public func _fetch(_ db: Database) throws -> Base.Fetched {
try base._fetch(db)
}
}
@@ -67,7 +67,7 @@ extension ValueReducers {
/// previously observed value.
///
/// See ``ValueObservation/removeDuplicates()``.
public struct RemoveDuplicates<Base: _ValueReducer>: _ValueReducer {
public struct RemoveDuplicates<Base: ValueReducer>: ValueReducer {
private var base: Base
private var previousValue: Base.Value?
private var predicate: (Base.Value, Base.Value) -> Bool
@@ -77,7 +77,11 @@ extension ValueReducers {
self.predicate = predicate
}
public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? {
public func _makeFetcher() -> Base.Fetcher {
base._makeFetcher()
}
public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Base.Value? {
guard let value = try base._value(fetched) else {
return nil
}
@@ -90,9 +94,3 @@ extension ValueReducers {
}
}
}
extension ValueReducers.RemoveDuplicates: ValueReducer where Base: ValueReducer {
public func _fetch(_ db: Database) throws -> Base.Fetched {
try base._fetch(db)
}
}
+17 -10
View File
@@ -4,12 +4,26 @@ extension ValueReducers {
///
/// See ``ValueObservation/handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)``
/// and ``ValueObservation/print(_:to:)``.
public struct Trace<Base: _ValueReducer>: _ValueReducer {
public struct Trace<Base: ValueReducer>: ValueReducer {
public struct _Fetcher: _ValueReducerFetcher {
let base: Base.Fetcher
let willFetch: @Sendable () -> Void
public func fetch(_ db: Database) throws -> Base.Fetcher.Value {
willFetch()
return try base.fetch(db)
}
}
var base: Base
let willFetch: () -> Void
let willFetch: @Sendable () -> Void
let didReceiveValue: (Base.Value) -> Void
public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? {
public func _makeFetcher() -> _Fetcher {
_Fetcher(base: base._makeFetcher(), willFetch: willFetch)
}
public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Base.Value? {
guard let value = try base._value(fetched) else {
return nil
}
@@ -19,10 +33,3 @@ extension ValueReducers {
}
// swiftlint:enable line_length
}
extension ValueReducers.Trace: ValueReducer where Base: ValueReducer {
public func _fetch(_ db: Database) throws -> Base.Fetched {
willFetch()
return try base._fetch(db)
}
}
@@ -1,11 +1,28 @@
// A `ValueReducer` fetches and transforms the database values
// observed by a ``ValueObservation``.
//
// It is NOT Sendable, because we need `ValueReducers.RemoveDuplicates` to
// be able to call `Equatable.==`, which IS not a Sendable function.
// Thread-safety will be assured by `ValueObservation`, which will make sure
// it does not invoke the reducer concurrently.
//
// However, we need to be able to fetch from any database dispatch queue,
// and maybe concurrently. That's why a `ValueReducer` has a Sendable facet,
// which is its `Fetcher`.
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer {
/// The type of fetched database values
associatedtype Fetched
/// The Sendable type that fetches database values
associatedtype Fetcher: _ValueReducerFetcher
/// The type of observed values
associatedtype Value
/// Returns a value that fetches database values upon changes in an
/// observed database region. The returned value method must not depend
/// on the state of the reducer.
func _makeFetcher() -> Fetcher
/// Transforms a fetched value into an eventual observed value. Returns nil
/// when observer should not be notified.
///
@@ -18,7 +35,14 @@ public protocol _ValueReducer {
/// reducer._value(...) // MUST NOT be nil
/// reducer._value(...) // MAY be nil
/// reducer._value(...) // MAY be nil
mutating func _value(_ fetched: Fetched) throws -> Value?
mutating func _value(_ fetched: Fetcher.Value) throws -> Value?
}
public protocol _ValueReducerFetcher: Sendable {
/// The type of fetched database values
associatedtype Value
func fetch(_ db: Database) throws -> Value
}
/// `ValueReducer` supports ``ValueObservation``.
@@ -26,17 +50,15 @@ public protocol _ValueReducer {
/// A `ValueReducer` fetches and transforms the database values
/// observed by a ``ValueObservation``.
///
/// Do not declare new conformances to `ValueReducer`. Only the built-in
/// conforming types are valid.
///
/// ## Topics
///
/// ### Support
/// ### Supporting Types
///
/// - ``ValueReducers``
public protocol ValueReducer: _ValueReducer {
/// Fetches database values upon changes in an observed database region.
///
/// This method must does not depend on the state of the reducer.
func _fetch(_ db: Database) throws -> Fetched
}
public protocol ValueReducer: _ValueReducer { }
/// A namespace for concrete types that adopt the ``ValueReducer`` protocol.
public enum ValueReducers { }
+9 -7
View File
@@ -4,7 +4,7 @@ import Combine
import Dispatch
import Foundation
public struct ValueObservation<Reducer: _ValueReducer> {
public struct ValueObservation<Reducer: ValueReducer> {
var events = ValueObservationEvents()
/// A boolean value indicating whether the observation requires write access
@@ -176,7 +176,7 @@ extension ValueObservation: Refinable {
/// when ValueObservation events occur.
public func handleEvents(
willStart: (() -> Void)? = nil,
willFetch: (() -> Void)? = nil,
willFetch: (@Sendable () -> Void)? = nil,
willTrackRegion: ((DatabaseRegion) -> Void)? = nil,
databaseDidChange: (() -> Void)? = nil,
didReceiveValue: ((Reducer.Value) -> Void)? = nil,
@@ -267,7 +267,9 @@ extension ValueObservation: Refinable {
where Reducer: ValueReducer
{
var reducer = makeReducer()
guard let value = try reducer._value(reducer._fetch(db)) else {
let fetcher = reducer._makeFetcher()
let fetchedValue = try fetcher.fetch(db)
guard let value = try reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
return value
@@ -731,7 +733,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func trackingConstantRegion<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -805,7 +807,7 @@ extension ValueObservation {
public static func tracking<Value>(
region: any DatabaseRegionConvertible,
_ otherRegions: any DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -874,7 +876,7 @@ extension ValueObservation {
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
regions: [any DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -931,7 +933,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -11,7 +11,7 @@ import Foundation
/// - ``immediate``
/// - ``AsyncValueObservationScheduler``
/// - ``ImmediateValueObservationScheduler``
public protocol ValueObservationScheduler {
public protocol ValueObservationScheduler: Sendable {
/// Returns whether the initial value should be immediately notified.
///
/// If the result is true, then this method was called on the main thread.
+44 -30
View File
@@ -92,28 +92,28 @@
- [X] GRDB7/BREAKING: Stop exporting SQLite (679d6463)
- [X] GRDB7/BREAKING: Remove Configuration.defaultTransactionKind (2661ff46)
- [X] GRDB7: Replace LockedBox with Mutex (00ccab06)
- [ ] GRDB7: Sendable: BusyCallback (e0d8e20b)
- [ ] GRDB7: Sendable: BusyMode (e0d8e20b)
- [ ] GRDB7: Sendable: TransactionClock (f7dc72a5)
- [ ] GRDB7: Sendable: Configuration (54ffb21f)
- [ ] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5)
- [ ] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5)
- [ ] GRDB7: Sendable: DatabaseColumnEncodingStrategy (264d7fb5)
- [ ] GRDB7: Sendable: DatabaseDataDecodingStrategy (264d7fb5)
- [ ] GRDB7: Sendable: DatabaseDateDecodingStrategy (264d7fb5)
- [ ] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5)
- [X] GRDB7: Sendable: BusyCallback (e0d8e20b)
- [X] GRDB7: Sendable: BusyMode (e0d8e20b)
- [X] GRDB7: Sendable: TransactionClock (f7dc72a5)
- [X] GRDB7: Sendable: Configuration (54ffb21f)
- [X] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5)
- [X] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5)
- [X] GRDB7: Sendable: DatabaseColumnEncodingStrategy (264d7fb5)
- [X] GRDB7: Sendable: DatabaseDataDecodingStrategy (264d7fb5)
- [X] GRDB7: Sendable: DatabaseDateDecodingStrategy (264d7fb5)
- [X] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5)
- [X] GRDB7/BREAKING: Remove DatabaseFuture and concurrentRead (05f7d3c8)
- [ ] GRDB7: Sendable: DatabaseFunction (6e691fe7)
- [ ] GRDB7: Sendable: DatabaseMigrator (22114ad4)
- [ ] GRDB7: Not Sendable: FilterCursor (b26e9709)
- [ ] GRDB7: Sendable: RowAdapter (d138af26)
- [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68)
- [ ] GRDB7: Sendable: DatabaseCollation (4d9d67dd)
- [ ] GRDB7: Sendable: LogErrorFunction (f362518d)
- [ ] GRDB7: Sendable: ReadWriteBox (57a86a0e)
- [ ] GRDB7: Sendable: Pool (f13b2d2e)
- [ ] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1)
- [ ] GRDB7: Sendable: WALSnapshotTransaction (7fd34012)
- [X] GRDB7: Sendable: DatabaseFunction (6e691fe7)
- [X] GRDB7: Sendable: DatabaseMigrator (22114ad4)
- [X] GRDB7: Not Sendable: FilterCursor (b26e9709)
- [X] GRDB7: Sendable: RowAdapter (d138af26)
- [X] GRDB7: Sendable: ValueObservationScheduler (8429eb68)
- [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd)
- [X] GRDB7: Sendable: LogErrorFunction (f362518d)
- [X] GRDB7: Sendable: ReadWriteBox (57a86a0e)
- [X] GRDB7: Sendable: Pool (f13b2d2e)
- [X] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1)
- [X] GRDB7: Sendable: WALSnapshotTransaction (7fd34012)
- [ ] GRDB7: sending closures for SerializedDatabase
- [ ] GRDB7: sending closures for ValueObservationScheduler
- [ ] GRDB7: Sendable closures for ValueObservation.handleEvents
@@ -122,28 +122,42 @@
- [ ] GRDB7: Sendable closures for writePublisher
- [ ] GRDB7: Sendable closures for readPublisher
- [ ] GRDB7: Not Sendable: fts5customtokenizer, fts5tokenizer, fts5wrappertokenizer
- [ ] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8)
- [ ] GRDB7: Sendable: TableAlias (f2b0b186)
- [ ] GRDB7: Sendable: SQLRelation (9545bf70)
- [ ] GRDB7: Sendable: SQL (ac33856f)
- [X] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8)
- [X] GRDB7: Sendable: TableAlias (f2b0b186)
- [X] GRDB7: Sendable: SQLRelation (9545bf70)
- [X] GRDB7: Sendable: SQL (ac33856f)
- [ ] GRDB7: Split Row.swift (2ce8a619)
- [ ] GRDB7: Cleanup ValueReducer (6c73b1c5)
- [X] GRDB7: DatabaseCursor has a primary associated type (b11c5dd2)
- [ ] GRDB7: Enable Strict Concurrency Checks (6aa43ded)
- [ ] GRDB7: Sendable: OrderedDictionary (e022c35b)
- [X] GRDB7: Sendable: OrderedDictionary (e022c35b)
- [ ] GRDB7: Rename ReadWriteBox to ReadWriteLock (7f5205ef)
- [ ] GRDB7: Sendable: DatabaseRegionConvertible (b4677ded)
- [X] GRDB7: Sendable: DatabaseRegionConvertible (b4677ded)
- [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65, 5465d056)
- [ ] GRDB7: Sendable: ValueWriteOnlyObserver (ff2a7548)
- [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65)
- [ ] GRDB7: Sendable: DatabaseCancellable (2f93f00b, 8f486a5e)
- [X] GRDB7: Sendable: DatabaseCancellable (2f93f00b, 8f486a5e)
- [ ] GRDB7: ValueObservation closures
- [?] GRDB7: DatabasePublishers.ValueSubscription
- [ ] GRDB7: Sendable: ValueObservation (93f6f982)
- [X] GRDB7: Sendable: ValueObservation (93f6f982)
- [?] GRDB7: Not Sendable: SharedValueObservation
- [ ] GRDB7: doc (c0838cf9)
- [ ] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c)
- [X] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c)
- [ ] GRDB7: TableRecord.databaseSelection must be declared as a computed property (24d232aa)
- [ ] GRDB7: Sendable: Association (b06aaee4)
- [ ] GRDB7/Tests: Sendable: ValueObservationRecorder (2947b3d7)
- [ ] GRDB7: ValueObservation.print cautiously uses its stream argument (5f8b39b7)
- [ ] GRDB7/Tests: use a single and Sendable test TextOutputStream (bbb1a736)
- [ ] GRDB7: ValueObservation needs a ValueReducer, not a `_ValueReducer` (08733108)
- [ ] GRDB7: Database support for cancellation (4ddf4bca)
- [ ] GRDB7: SerializedDatabase support for async db access with support for Task cancellation (737cb149)
- [ ] GRDB7: DatabaseWriter async methods support Task cancellation (a5226501)
- [ ] GRDB7: DatabaseReader async methods support Task cancellation (10c9d311)
- [ ] GRDB7: Document that async methods can throw CancellationError (8df18fb8)
- [ ] GRDB7: Sendable: AssociationAggregate (48ad10ae)
- [?] GRDB7: Sendable: AsyncValueObservation (ce63cdfa)
- [X] GRDB7: Sendable: DatabaseRegionObservation (b4ff52fb)
- [ ] GRDB7: DispatchQueue.asyncSending (7b075e6b)
- [?] GRDB7: Change ValueObservation callback argument so that it could expose snapshots? https://github.com/groue/GRDB.swift/discussions/1523#discussioncomment-9092500
@@ -15,40 +15,40 @@ class DatabaseConfigurationTests: GRDBTestCase {
func testPrepareDatabase() throws {
// prepareDatabase is called when connection opens
var connectionCount = 0
let connectionCountMutex = Mutex(0)
var configuration = Configuration()
configuration.prepareDatabase { db in
connectionCount += 1
connectionCountMutex.increment()
}
_ = try DatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 1)
XCTAssertEqual(connectionCountMutex.load(), 1)
_ = try makeDatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 2)
XCTAssertEqual(connectionCountMutex.load(), 2)
let pool = try makeDatabasePool(configuration: configuration)
XCTAssertEqual(connectionCount, 3)
XCTAssertEqual(connectionCountMutex.load(), 3)
try pool.read { _ in }
XCTAssertEqual(connectionCount, 4)
XCTAssertEqual(connectionCountMutex.load(), 4)
try pool.makeSnapshot().read { _ in }
XCTAssertEqual(connectionCount, 5)
XCTAssertEqual(connectionCountMutex.load(), 5)
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try pool.makeSnapshotPool().read { _ in }
XCTAssertEqual(connectionCount, 6)
XCTAssertEqual(connectionCountMutex.load(), 6)
#endif
}
func testPrepareDatabaseError() throws {
struct TestError: Error { }
var error: TestError?
let errorMutex: Mutex<TestError?> = Mutex(nil)
var configuration = Configuration()
configuration.prepareDatabase { db in
if let error {
if let error = errorMutex.load() {
throw error
}
}
@@ -56,36 +56,36 @@ class DatabaseConfigurationTests: GRDBTestCase {
// TODO: what about in-memory DatabaseQueue???
do {
error = TestError()
errorMutex.store(TestError())
_ = try makeDatabaseQueue(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
errorMutex.store(TestError())
_ = try makeDatabasePool(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = nil
errorMutex.store(nil)
let pool = try makeDatabasePool(configuration: configuration)
do {
error = TestError()
errorMutex.store(TestError())
try pool.read { _ in }
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
errorMutex.store(TestError())
_ = try pool.makeSnapshot()
XCTFail("Expected TestError")
} catch is TestError { }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
do {
error = TestError()
errorMutex.store(TestError())
_ = try pool.makeSnapshotPool()
XCTFail("Expected TestError")
} catch is TestError { }
+3 -3
View File
@@ -347,13 +347,13 @@ class DatabaseFunctionTests: GRDBTestCase {
func testFunctionsAreClosures() throws {
let dbQueue = try makeDatabaseQueue()
var x = 123
let mutex = Mutex(123)
let fn = DatabaseFunction("f", argumentCount: 0) { dbValues in
return x
return mutex.load()
}
try dbQueue.inDatabase { db in
db.add(function: fn)
x = 321
mutex.store(321)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f()")!, 321)
}
}
+4 -4
View File
@@ -128,7 +128,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
let expectation = self.expectation(description: "")
migrator.asyncMigrate(writer, completion: { dbResult in
migrator.asyncMigrate(writer, completion: { [migrator2] dbResult in
// No migration error
let db = try! dbResult.get()
@@ -795,13 +795,13 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
var witness = 1
let mutex = Mutex(0)
migrator.registerMigration("1") { db in
let value = mutex.increment()
try db.execute(sql: """
CREATE TABLE t1(id INTEGER PRIMARY KEY);
INSERT INTO t1(id) VALUES (?)
""", arguments: [witness])
witness += 1
""", arguments: [value])
}
let dbQueue = try makeDatabaseQueue()
@@ -13,21 +13,16 @@ import XCTest
class DatabasePoolReleaseMemoryTests: GRDBTestCase {
func testDatabasePoolDeinitClosesAllConnections() throws {
let countQueue = DispatchQueue(label: "GRDB")
var openConnectionCount = 0
var totalOpenConnectionCount = 0
let openConnectionCountMutex = Mutex(0)
let totalOpenConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
countQueue.sync {
totalOpenConnectionCount += 1
openConnectionCount += 1
}
dbConfiguration.onConnectionDidOpen {
totalOpenConnectionCountMutex.increment()
openConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
countQueue.sync {
openConnectionCount -= 1
}
dbConfiguration.onConnectionDidClose {
openConnectionCountMutex.decrement()
}
// write & read
@@ -44,19 +39,19 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
}
// One reader, one writer
XCTAssertEqual(totalOpenConnectionCount, 2)
XCTAssertEqual(totalOpenConnectionCountMutex.load(), 2)
// All connections are closed
XCTAssertEqual(openConnectionCount, 0)
XCTAssertEqual(openConnectionCountMutex.load(), 0)
}
#if os(iOS)
func testDatabasePoolReleasesMemoryOnPressureEvent() throws {
// Create a database pool, and expect a reader connection to be closed
let expectation = self.expectation(description: "Reader connection closed")
var configuration = Configuration()
configuration.SQLiteConnectionWillClose = { conn in
configuration.onConnectionWillClose { conn in
if sqlite3_db_readonly(conn, nil) != 0 {
expectation.fulfill()
}
@@ -76,7 +71,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
waitForExpectations(timeout: 0.5)
}
}
func testDatabasePoolDoesNotReleaseMemoryOnPressureEventIfDisabled() throws {
// Create a database pool, and do not expect any reader connection to be closed
let expectation = self.expectation(description: "Reader connection closed")
@@ -84,7 +79,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
var configuration = Configuration()
configuration.automaticMemoryManagement = false
configuration.SQLiteConnectionWillClose = { conn in
configuration.onConnectionWillClose { conn in
if sqlite3_db_readonly(conn, nil) != 0 {
expectation.fulfill()
}
@@ -126,26 +121,21 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
// Cleanup
semaphore.signal()
}
#endif
func test_DatabasePool_releaseMemory_closes_reader_connections() throws {
// A complicated test setup that opens multiple reader connections.
let countQueue = DispatchQueue(label: "GRDB")
var openConnectionCount = 0
var totalOpenConnectionCount = 0
let openConnectionCountMutex = Mutex(0)
let totalOpenConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
countQueue.sync {
totalOpenConnectionCount += 1
openConnectionCount += 1
}
dbConfiguration.onConnectionDidOpen {
totalOpenConnectionCountMutex.increment()
openConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
countQueue.sync {
openConnectionCount -= 1
}
dbConfiguration.onConnectionDidClose {
openConnectionCountMutex.decrement()
}
let dbPool = try makeDatabasePool()
@@ -201,74 +191,69 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
}
// Two readers, one writer
XCTAssertEqual(totalOpenConnectionCount, 3)
XCTAssertEqual(totalOpenConnectionCountMutex.load(), 3)
// Writer is still open
XCTAssertEqual(openConnectionCount, 1)
XCTAssertEqual(openConnectionCountMutex.load(), 1)
}
func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReadOnlyConnections_is_false() throws {
var persistentConnectionCount = 0
let persistentConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
persistentConnectionCount += 1
dbConfiguration.onConnectionDidOpen {
persistentConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
persistentConnectionCount -= 1
dbConfiguration.onConnectionDidClose {
persistentConnectionCountMutex.decrement()
}
dbConfiguration.persistentReadOnlyConnections = false
let dbPool = try makeDatabasePool()
XCTAssertEqual(persistentConnectionCount, 1) // writer
XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer
try dbPool.read { _ in }
XCTAssertEqual(persistentConnectionCount, 2) // writer + reader
XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader
dbPool.releaseMemory()
XCTAssertEqual(persistentConnectionCount, 1) // writer
XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer
}
func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReadOnlyConnections_is_true() throws {
var persistentConnectionCount = 0
let persistentConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
persistentConnectionCount += 1
dbConfiguration.onConnectionDidOpen {
persistentConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
persistentConnectionCount -= 1
dbConfiguration.onConnectionDidClose {
persistentConnectionCountMutex.decrement()
}
dbConfiguration.persistentReadOnlyConnections = true
let dbPool = try makeDatabasePool()
XCTAssertEqual(persistentConnectionCount, 1) // writer
XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer
try dbPool.read { _ in }
XCTAssertEqual(persistentConnectionCount, 2) // writer + reader
XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader
dbPool.releaseMemory()
XCTAssertEqual(persistentConnectionCount, 2) // writer + reader
XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader
}
func testBlocksRetainConnection() throws {
let countQueue = DispatchQueue(label: "GRDB")
var openConnectionCount = 0
var totalOpenConnectionCount = 0
let openConnectionCountMutex = Mutex(0)
let totalOpenConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
countQueue.sync {
totalOpenConnectionCount += 1
openConnectionCount += 1
}
dbConfiguration.onConnectionDidOpen {
totalOpenConnectionCountMutex.increment()
openConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
countQueue.sync {
openConnectionCount -= 1
}
dbConfiguration.onConnectionDidClose {
openConnectionCountMutex.decrement()
}
// Block 1 Block 2
@@ -311,10 +296,10 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
}
// one writer, one reader
XCTAssertEqual(totalOpenConnectionCount, 2)
XCTAssertEqual(totalOpenConnectionCountMutex.load(), 2)
// All connections are closed
XCTAssertEqual(openConnectionCount, 0)
XCTAssertEqual(openConnectionCountMutex.load(), 0)
}
func testStatementDoNotRetainDatabaseConnection() throws {
+2 -2
View File
@@ -397,7 +397,7 @@ class DatabasePoolTests: GRDBTestCase {
XCTFail("Expected Error")
} catch DatabaseError.SQLITE_BUSY { }
}
XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master"))
XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master"))
// Database is not closed: no error
try dbPool.write { db in
@@ -427,7 +427,7 @@ class DatabasePoolTests: GRDBTestCase {
//
// The first comes from GRDB, and the second, depending on the SQLite
// version, from `sqlite3_close_v2()`. Write the test so that it always pass:
XCTAssert(lastMessage!.contains("unfinalized statement"))
XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement"))
// Database is in a zombie state.
// In the zombie state, access throws SQLITE_MISUSE
@@ -244,9 +244,9 @@ class ConcurrencyTests: GRDBTestCase {
// BEGIN EXCLUSIVE TRANSACTION
// COMMIT
var busyCallbackCalled = false
let busyCallbackCalledMutex = Mutex(false)
self.busyCallback = { n in
busyCallbackCalled = true
busyCallbackCalledMutex.store(true)
s2.signal()
return true
}
@@ -283,7 +283,7 @@ class ConcurrencyTests: GRDBTestCase {
_ = group.wait(timeout: .distantFuture)
XCTAssertTrue(busyCallbackCalled)
XCTAssertTrue(busyCallbackCalledMutex.load())
}
func testReaderDuringDefaultTransaction() throws {
@@ -384,9 +384,9 @@ class ConcurrencyTests: GRDBTestCase {
// COMMIT
// COMMIT
var busyCallbackCalled = false
let busyCallbackCalledMutex = Mutex(false)
self.busyCallback = { n in
busyCallbackCalled = true
busyCallbackCalledMutex.store(true)
s3.signal()
return true
}
@@ -431,6 +431,6 @@ class ConcurrencyTests: GRDBTestCase {
_ = group.wait(timeout: .distantFuture)
XCTAssertTrue(busyCallbackCalled)
XCTAssertTrue(busyCallbackCalledMutex.load())
}
}
@@ -4,21 +4,16 @@ import XCTest
class DatabaseQueueReleaseMemoryTests: GRDBTestCase {
func testDatabaseQueueDeinitClosesConnection() throws {
let countQueue = DispatchQueue(label: "GRDB")
var openConnectionCount = 0
var totalOpenConnectionCount = 0
let openConnectionCountMutex = Mutex(0)
let totalOpenConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
countQueue.sync {
totalOpenConnectionCount += 1
openConnectionCount += 1
}
dbConfiguration.onConnectionDidOpen {
totalOpenConnectionCountMutex.increment()
openConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
countQueue.sync {
openConnectionCount -= 1
}
dbConfiguration.onConnectionDidClose {
openConnectionCountMutex.decrement()
}
do {
@@ -27,28 +22,23 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase {
}
// One reader, one writer
XCTAssertEqual(totalOpenConnectionCount, 1)
XCTAssertEqual(totalOpenConnectionCountMutex.load(), 1)
// All connections are closed
XCTAssertEqual(openConnectionCount, 0)
XCTAssertEqual(openConnectionCountMutex.load(), 0)
}
func testBlocksRetainConnection() throws {
let countQueue = DispatchQueue(label: "GRDB")
var openConnectionCount = 0
var totalOpenConnectionCount = 0
let openConnectionCountMutex = Mutex(0)
let totalOpenConnectionCountMutex = Mutex(0)
dbConfiguration.SQLiteConnectionDidOpen = {
countQueue.sync {
totalOpenConnectionCount += 1
openConnectionCount += 1
}
dbConfiguration.onConnectionDidOpen {
totalOpenConnectionCountMutex.increment()
openConnectionCountMutex.increment()
}
dbConfiguration.SQLiteConnectionDidClose = {
countQueue.sync {
openConnectionCount -= 1
}
dbConfiguration.onConnectionDidClose {
openConnectionCountMutex.decrement()
}
// Block 1 Block 2
@@ -91,10 +81,10 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase {
}
// one writer
XCTAssertEqual(totalOpenConnectionCount, 1)
XCTAssertEqual(totalOpenConnectionCountMutex.load(), 1)
// All connections are closed
XCTAssertEqual(openConnectionCount, 0)
XCTAssertEqual(openConnectionCountMutex.load(), 0)
}
func testStatementDoNotRetainDatabaseConnection() throws {
+2 -2
View File
@@ -378,7 +378,7 @@ class DatabaseQueueTests: GRDBTestCase {
}
let parallelWritesCount = 50
DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { index in
DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { [configuration] index in
let dbQueue = try! makeDatabaseQueue(filename: "test", configuration: configuration)
try! dbQueue.write { db in
_ = try Table("test").fetchCount(db)
@@ -458,7 +458,7 @@ class DatabaseQueueTests: GRDBTestCase {
XCTFail("Expected Error")
} catch DatabaseError.SQLITE_BUSY { }
}
XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master"))
XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master"))
// Database is not closed: no error
try dbQueue.inDatabase { db in
+1 -1
View File
@@ -424,7 +424,7 @@ class DatabaseSnapshotTests: GRDBTestCase {
XCTFail("Expected Error")
} catch DatabaseError.SQLITE_BUSY { }
}
XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master"))
XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master"))
// Database is not closed: no error
try snapshot.read { db in
+6 -6
View File
@@ -114,11 +114,11 @@ class DatabaseTraceTests : GRDBTestCase {
}
func testTraceFromConfigurationWithDefaultOptions() throws {
var events: [String] = []
let eventsMutex: Mutex<[String]> = Mutex([])
var configuration = Configuration()
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
eventsMutex.withLock { $0.append("SQL: \(event)") }
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
@@ -127,19 +127,19 @@ class DatabaseTraceTests : GRDBTestCase {
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
XCTAssertEqual(eventsMutex.load().suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (?)"])
}
}
func testTraceFromConfigurationWithPublicStatementArguments() throws {
var events: [String] = []
let eventsMutex: Mutex<[String]> = Mutex([])
var configuration = Configuration()
configuration.publicStatementArguments = true
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
eventsMutex.withLock { $0.append("SQL: \(event)") }
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
@@ -148,7 +148,7 @@ class DatabaseTraceTests : GRDBTestCase {
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
XCTAssertEqual(eventsMutex.load().suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (1)"])
}
+6 -6
View File
@@ -272,16 +272,16 @@ class FTS4TableBuilderTests: GRDBTestCase {
func testFTS4Compression() throws {
// Based on https://github.com/groue/GRDB.swift/issues/369
var compressCalled = false
var uncompressCalled = false
let compressCalledMutex = Mutex(false)
let uncompressCalledMutex = Mutex(false)
dbConfiguration.prepareDatabase { db in
db.add(function: DatabaseFunction("zipit", argumentCount: 1, pure: true, function: { dbValues in
compressCalled = true
compressCalledMutex.store(true)
return dbValues[0]
}))
db.add(function: DatabaseFunction("unzipit", argumentCount: 1, pure: true, function: { dbValues in
uncompressCalled = true
uncompressCalledMutex.store(true)
return dbValues[0]
}))
}
@@ -296,12 +296,12 @@ class FTS4TableBuilderTests: GRDBTestCase {
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(content, compress=\"zipit\", uncompress=\"unzipit\")")
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["abc"])
XCTAssertTrue(compressCalled)
XCTAssertTrue(compressCalledMutex.load())
}
try dbPool.read { db in
_ = try Row.fetchOne(db, sql: "SELECT * FROM documents")
XCTAssertTrue(uncompressCalled)
XCTAssertTrue(uncompressCalledMutex.load())
}
}
}
+28 -15
View File
@@ -12,15 +12,15 @@ import XCTest
@testable import GRDB
// Support for Database.logError
var lastResultCode: ResultCode? = nil
var lastMessage: String? = nil
struct SQLiteDiagnostic {
var resultCode: ResultCode
var message: String
}
private let lastSQLiteDiagnosticMutex = Mutex<SQLiteDiagnostic?>(nil)
var lastSQLiteDiagnostic: SQLiteDiagnostic? { lastSQLiteDiagnosticMutex.load() }
let logErrorSetup: Void = {
let lock = NSLock()
Database.logError = { (resultCode, message) in
lock.lock()
defer { lock.unlock() }
lastResultCode = resultCode
lastMessage = message
lastSQLiteDiagnosticMutex.store(SQLiteDiagnostic(resultCode: resultCode, message: message))
}
}()
@@ -84,7 +84,7 @@ class GRDBTestCase: XCTestCase {
dbConfiguration = Configuration()
// Test that database are deallocated in a clean state
dbConfiguration.SQLiteConnectionWillClose = { sqliteConnection in
dbConfiguration.onConnectionWillClose { sqliteConnection in
// https://www.sqlite.org/capi3ref.html#sqlite3_close:
// > If sqlite3_close_v2() is called on a database connection that still
// > has outstanding prepared statements, BLOB handles, and/or
@@ -235,26 +235,39 @@ extension FetchRequest {
}
/// A type-erased ValueReducer.
public struct AnyValueReducer<Fetched, Value>: ValueReducer {
private var __fetch: (Database) throws -> Fetched
struct AnyValueReducer<Fetched, Value>: ValueReducer {
private var __fetch: @Sendable (Database) throws -> Fetched
private var __value: (Fetched) -> Value?
public init(
fetch: @escaping (Database) throws -> Fetched,
init(
fetch: @escaping @Sendable (Database) throws -> Fetched,
value: @escaping (Fetched) -> Value?)
{
self.__fetch = fetch
self.__value = value
}
public func _fetch(_ db: Database) throws -> Fetched {
try __fetch(db)
func _makeFetcher() -> AnyValueReducerFetcher<Fetched> {
AnyValueReducerFetcher(fetch: __fetch)
}
public func _value(_ fetched: Fetched) -> Value? {
func _value(_ fetched: Fetched) -> Value? {
__value(fetched)
}
}
/// A type-erased _ValueReducerFetcher.
struct AnyValueReducerFetcher<Fetched>: _ValueReducerFetcher {
private var _fetch: @Sendable (Database) throws -> Fetched
init(fetch: @escaping @Sendable (Database) throws -> Fetched) {
self._fetch = fetch
}
func fetch(_ db: Database) throws -> Fetched {
try _fetch(db)
}
}
// Assume this is correct :-/
extension XCTestExpectation: @unchecked Sendable { }
+3 -1
View File
@@ -5,7 +5,9 @@ class PoolTests: XCTestCase {
/// Returns a Pool whose elements are incremented integers: 1, 2, 3...
private func makeCounterPool(maximumCount: Int) -> Pool<Int> {
let count = ReadWriteBox(wrappedValue: 0)
return Pool(maximumCount: maximumCount, makeElement: count.increment)
return Pool(maximumCount: maximumCount, makeElement: { _ in
count.increment()
})
}
func testElementsAreReused() throws {
+4 -2
View File
@@ -15,7 +15,7 @@ private class Person : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -131,7 +131,9 @@ class RecordEditedTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson", migrate: Person.setup)
migrator.registerMigration("createPerson") {
try Person.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)")
}
@@ -48,7 +48,9 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle", migrate: MinimalNonOptionalPrimaryKeySingle.setup)
migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle") {
try MinimalNonOptionalPrimaryKeySingle.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)")
}
@@ -52,7 +52,9 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createMinimalRowID", migrate: MinimalRowID.setup)
migrator.registerMigration("createMinimalRowID") {
try MinimalRowID.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)")
}
@@ -49,7 +49,9 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createMinimalSingle", migrate: MinimalSingle.setup)
migrator.registerMigration("createMinimalSingle") {
try MinimalSingle.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -16,7 +16,7 @@ private class Person : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
creationDate TEXT NOT NULL,
@@ -84,7 +84,9 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson", migrate: Person.setup)
migrator.registerMigration("createPerson") {
try Person.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE citizenships (
personName TEXT NOT NULL,
@@ -61,7 +61,9 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createCitizenship", migrate: Citizenship.setup)
migrator.registerMigration("createCitizenship") {
try Citizenship.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -14,7 +14,7 @@ private class Item : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE items (
name TEXT,
@@ -58,7 +58,9 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createItem", migrate: Item.setup)
migrator.registerMigration("createItem") {
try Item.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -16,7 +16,7 @@ private class Person : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -78,7 +78,9 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson", migrate: Person.setup)
migrator.registerMigration("createPerson") {
try Person.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -12,7 +12,7 @@ class Pet : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE pets (
UUID TEXT NOT NULL PRIMARY KEY,
@@ -51,7 +51,9 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPet", migrate: Pet.setup)
migrator.registerMigration("createPet") {
try Pet.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -11,7 +11,7 @@ class Email : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE emails (
email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE,
@@ -50,7 +50,9 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createEmail", migrate: Email.setup)
migrator.registerMigration("createEmail") {
try Email.setup($0)
}
try migrator.migrate(dbWriter)
}
+4 -2
View File
@@ -15,7 +15,7 @@ private class Person : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -105,7 +105,9 @@ class RecordSubClassTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson", migrate: Person.setup)
migrator.registerMigration("createPerson") {
try Person.setup($0)
}
try migrator.migrate(dbWriter)
}
@@ -13,7 +13,7 @@ class BadlyMangledStuff : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
static func setup(_ db: Database) throws {
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)")
}
@@ -48,7 +48,9 @@ class RecordWithColumnNameManglingTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createBadlyMangledStuff", migrate: BadlyMangledStuff.setup)
migrator.registerMigration("createBadlyMangledStuff") {
try BadlyMangledStuff.setup($0)
}
try migrator.migrate(dbWriter)
}
+5 -5
View File
@@ -139,20 +139,20 @@ class SelectStatementTests : GRDBTestCase {
func testCachedSelectStatementStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var needsThrow = false
let needsThrowMutex = Mutex(false)
db.add(function: DatabaseFunction("bomb", argumentCount: 0, pure: false) { _ in
if needsThrow {
if needsThrowMutex.load() {
throw DatabaseError(message: "boom")
}
return "success"
})
let sql = "SELECT bomb()"
needsThrow = false
needsThrowMutex.store(false)
XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"])
do {
needsThrow = true
needsThrowMutex.store(true)
_ = try String.fetchAll(db.cachedStatement(sql: sql))
XCTFail()
} catch let error as DatabaseError {
@@ -162,7 +162,7 @@ class SelectStatementTests : GRDBTestCase {
XCTAssertEqual(error.description, "SQLite error 1: boom - while executing `\(sql)`")
}
needsThrow = false
needsThrowMutex.store(false)
XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"])
}
}
+20 -28
View File
@@ -8,9 +8,9 @@ class TransactionDateTests: GRDBTestCase {
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
let dateIteratorMutex = Mutex(dates.makeIterator())
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
dateIteratorMutex.withLock { $0.next()! }
}
var collectedDates: [Date] = []
@@ -28,9 +28,9 @@ class TransactionDateTests: GRDBTestCase {
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
let dateIteratorMutex = Mutex(dates.makeIterator())
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
dateIteratorMutex.withLock { $0.next()! }
}
var collectedDates: [Date] = []
@@ -51,9 +51,9 @@ class TransactionDateTests: GRDBTestCase {
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
let dateIteratorMutex = Mutex(dates.makeIterator())
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
dateIteratorMutex.withLock { $0.next()! }
}
var collectedDates: [Date] = []
@@ -74,9 +74,9 @@ class TransactionDateTests: GRDBTestCase {
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
let dateIteratorMutex = Mutex(dates.makeIterator())
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
dateIteratorMutex.withLock { $0.next()! }
}
var collectedDates: [Date] = []
@@ -107,8 +107,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
dbConfiguration.transactionClock = .custom { _ in .distantPast }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -119,7 +118,6 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
try dbQueue.write { db in
do {
var player = Player(name: "Arthur")
@@ -152,8 +150,8 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
let currentDate = Mutex(Date.distantPast)
dbConfiguration.transactionClock = .custom { _ in currentDate.load() }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -164,14 +162,13 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur")
try player.insert(db)
}
let newTransactionDate = Date()
currentDate = newTransactionDate
currentDate.store(newTransactionDate)
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
@@ -198,8 +195,8 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
let currentDate = Mutex(Date.distantPast)
dbConfiguration.transactionClock = .custom { _ in currentDate.load() }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -210,14 +207,13 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur")
try player.insert(db)
}
let newTransactionDate = Date()
currentDate = newTransactionDate
currentDate.store(newTransactionDate)
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
@@ -251,8 +247,8 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
let currentDate = Mutex(Date.distantPast)
dbConfiguration.transactionClock = .custom { _ in currentDate.load() }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -267,7 +263,7 @@ class TransactionDateTests: GRDBTestCase {
}
let newTransactionDate = Date()
currentDate = newTransactionDate
currentDate.store(newTransactionDate)
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
try player.touch(db)
@@ -303,8 +299,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
dbConfiguration.transactionClock = .custom { _ in .distantPast }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -315,7 +310,6 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur", isInserted: false)
try player.insert(db)
@@ -354,8 +348,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
dbConfiguration.transactionClock = .custom { _ in .distantPast }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -366,7 +359,6 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
try dbQueue.write { db in
let player = Player(name: "Arthur")
try player.insert(db)
@@ -1384,7 +1384,7 @@ class TransactionObserverTests: GRDBTestCase {
dbQueue.add(transactionObserver: observer)
try dbQueue.writeWithoutTransaction { db in
try MinimalRowID.setup(inDatabase: db)
try MinimalRowID.setup(db)
let record = MinimalRowID()
try record.save(db)
+3 -4
View File
@@ -178,17 +178,16 @@ class UpdateStatementTests : GRDBTestCase {
func testUpdateStatementAcceptsSelectQueriesAndConsumeAllRows() throws {
let dbQueue = try makeDatabaseQueue()
var index = 0
let indexMutex = Mutex(0)
try dbQueue.inDatabase { db in
db.add(function: DatabaseFunction("seq", argumentCount: 0, pure: false) { _ in
defer { index += 1 }
return index
indexMutex.increment()
})
try db.execute(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()")
let statement = try db.makeStatement(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()")
try statement.execute()
}
XCTAssertEqual(index, 3 + 3)
XCTAssertEqual(indexMutex.load(), 3 + 3)
}
func testExecuteNothing() throws {