From e7eac0d500ba59fc2c3a768286084fcbf86f9e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Nov 2023 18:33:03 +0100 Subject: [PATCH] Sendable annotations --- GRDB/Core/Configuration.swift | 2 +- GRDB/Core/Database.swift | 30 ++- GRDB/Core/DatabasePool.swift | 37 ++-- GRDB/Core/DatabaseQueue.swift | 18 +- GRDB/Core/DatabaseReader.swift | 38 ++-- GRDB/Core/DatabaseRegion.swift | 8 +- GRDB/Core/DatabaseRegionObservation.swift | 26 +-- GRDB/Core/DatabaseSnapshot.swift | 6 +- GRDB/Core/DatabaseSnapshotPool.swift | 4 +- GRDB/Core/DatabaseValueConvertible.swift | 24 +- GRDB/Core/DatabaseWriter.swift | 71 ++++-- GRDB/Core/FetchRequest.swift | 12 +- GRDB/Core/Row.swift | 24 +- GRDB/Core/RowAdapter.swift | 6 +- GRDB/Core/SQLRequest.swift | 2 +- GRDB/Core/SerializedDatabase.swift | 2 +- GRDB/Core/StatementColumnConvertible.swift | 24 +- .../Foundation/DatabaseDateComponents.swift | 2 +- GRDB/Core/Support/Foundation/NSData.swift | 1 + GRDB/Core/Support/Foundation/NSString.swift | 1 + GRDB/Core/TransactionClock.swift | 8 +- GRDB/Core/TransactionObserver.swift | 13 +- GRDB/Core/WALSnapshotTransaction.swift | 8 +- GRDB/FTS/FTS5CustomTokenizer.swift | 2 +- GRDB/Migration/DatabaseMigrator.swift | 6 +- GRDB/Migration/Migration.swift | 4 +- GRDB/QueryInterface/ForeignKey.swift | 2 +- .../Request/Association/Association.swift | 12 +- .../Request/CommonTableExpression.swift | 6 +- .../Request/QueryInterfaceRequest.swift | 14 +- .../Request/RequestProtocols.swift | 12 +- GRDB/QueryInterface/SQL/DatabasePromise.swift | 8 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 6 +- GRDB/QueryInterface/SQL/SQLOrdering.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 30 +-- GRDB/QueryInterface/SQL/SQLSelection.swift | 4 +- GRDB/QueryInterface/SQL/Table.swift | 30 +-- .../SQLGeneration/SQLQueryGenerator.swift | 4 +- .../TableRecord+Association.swift | 3 +- GRDB/Record/FetchableRecord+TableRecord.swift | 24 +- GRDB/Record/FetchableRecord.swift | 24 +- GRDB/Record/TableRecord.swift | 2 +- GRDB/Utils/Inflections+English.swift | 5 +- GRDB/Utils/Inflections.swift | 8 + GRDB/Utils/OnDemandFuture.swift | 9 +- GRDB/Utils/OrderedDictionary.swift | 2 + GRDB/Utils/Pool.swift | 11 +- GRDB/Utils/Utils.swift | 19 +- .../DatabaseCancellable.swift | 28 ++- .../Observers/ValueConcurrentObserver.swift | 48 ++-- .../Observers/ValueWriteOnlyObserver.swift | 8 +- GRDB/ValueObservation/Reducers/Fetch.swift | 6 +- GRDB/ValueObservation/Reducers/Map.swift | 8 +- .../Reducers/RemoveDuplicates.swift | 10 +- GRDB/ValueObservation/Reducers/Trace.swift | 4 +- .../Reducers/ValueReducer.swift | 6 +- .../SharedValueObservation.swift | 19 +- GRDB/ValueObservation/ValueObservation.swift | 66 +++--- .../ValueObservationScheduler.swift | 10 +- .../GRDBTests/CompilationProtocolTests.swift | 2 +- ...abaseAfterNextTransactionCommitTests.swift | 44 ++-- .../DatabaseConfigurationTests.swift | 38 ++-- Tests/GRDBTests/DatabaseMigratorTests.swift | 11 +- .../DatabasePoolConcurrencyTests.swift | 29 ++- Tests/GRDBTests/DatabaseReaderTests.swift | 10 +- .../DatabaseRegionObservationTests.swift | 55 +++-- Tests/GRDBTests/DatabaseTraceTests.swift | 14 +- ...atabaseValueConvertibleSubclassTests.swift | 2 +- Tests/GRDBTests/FTS4TableBuilderTests.swift | 15 +- Tests/GRDBTests/GRDBTestCase.swift | 8 +- ...ntable+DatabaseValueConvertibleTests.swift | 1 + Tests/GRDBTests/RecordEditedTests.swift | 2 +- ...imalNonOptionalPrimaryKeySingleTests.swift | 2 +- .../RecordMinimalPrimaryKeyRowIDTests.swift | 2 +- .../RecordMinimalPrimaryKeySingleTests.swift | 2 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 2 +- .../RecordPrimaryKeyMultipleTests.swift | 2 +- .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 2 +- .../RecordPrimaryKeyRowIDTests.swift | 2 +- .../RecordPrimaryKeySingleTests.swift | 2 +- ...leWithReplaceConflictResolutionTests.swift | 2 +- Tests/GRDBTests/RecordSubClassTests.swift | 2 +- .../RecordWithColumnNameManglingTests.swift | 2 +- .../SharedValueObservationTests.swift | 172 +++++++++------ Tests/GRDBTests/TransactionDateTests.swift | 161 +++++++++----- .../ValueObservationPrintTests.swift | 18 +- ...ValueObservationRegionRecordingTests.swift | 30 ++- Tests/GRDBTests/ValueObservationTests.swift | 205 ++++++++++-------- 88 files changed, 957 insertions(+), 711 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 780ce452a..19647c17e 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -223,7 +223,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) } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 509818929..e42987c5f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -130,20 +130,28 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Configuration + @LockedBox private static var logErrorFunction: LogErrorFunction? = nil + /// The error logging function. /// /// Related SQLite documentation: - public static var logError: LogErrorFunction? = nil { - didSet { - if logError != nil { - _registerErrorLogCallback { (_, code, message) in - guard let logError = Database.logError else { return } - guard let message = message.map(String.init) else { return } - let resultCode = ResultCode(rawValue: code) - logError(resultCode, message) + public static var logError: LogErrorFunction? { + get { + logErrorFunction + } + set { + $logErrorFunction.update { + $0 = newValue + if $0 != nil { + _registerErrorLogCallback { (_, code, message) in + guard let logError = Database.logError else { return } + guard let message = message.map(String.init) else { return } + let resultCode = ResultCode(rawValue: code) + logError(resultCode, message) + } + } else { + _registerErrorLogCallback(nil) } - } else { - _registerErrorLogCallback(nil) } } } @@ -1785,7 +1793,7 @@ extension Database { /// Related SQLite documentation: /// - /// - - public struct CollationName: RawRepresentable, Hashable { + public struct CollationName: RawRepresentable, Hashable, Sendable { public let rawValue: String /// Creates a collation name. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index c7786861b..8a9f40e62 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -257,7 +257,9 @@ extension DatabasePool { // has freed its memory. That's better than nothing. releaseMemoryEventually() writer.async { _ in - application.endBackgroundTask(task) + DispatchQueue.main.async { + application.endBackgroundTask(task) + } } } } @@ -357,7 +359,7 @@ extension DatabasePool: DatabaseReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -401,7 +403,7 @@ extension DatabasePool: DatabaseReader { } } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -446,25 +448,18 @@ extension DatabasePool: DatabaseReader { } } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - // The semaphore that blocks until futureResult is defined: - let futureSemaphore = DispatchSemaphore(value: 0) - var futureResult: Result? = nil + public func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture { + let builder = DatabaseFutureBuilder() asyncConcurrentRead { dbResult in // Fetch and release the future - futureResult = dbResult.flatMap { db in Result { try value(db) } } - futureSemaphore.signal() + builder.resolve(dbResult.flatMap { db in Result { try value(db) } }) } - return DatabaseFuture { - // Block the future until results are fetched - _ = futureSemaphore.wait(timeout: .distantFuture) - return try futureResult!.get() - } + return builder.future() } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { asyncConcurrentRead(value) } @@ -505,7 +500,7 @@ extension DatabasePool: DatabaseReader { /// ``` /// /// - parameter value: A function that accesses the database. - public func asyncConcurrentRead(_ value: @escaping (Result) -> Void) { + public func asyncConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -665,7 +660,7 @@ extension DatabasePool: DatabaseReader { /// /// - important: The `completion` argument is executed in a serial /// dispatch queue, so make sure you use the transaction asynchronously. - func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { + func asyncWALSnapshotTransaction(_ completion: @escaping @Sendable (Result) -> Void) { guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) return @@ -691,7 +686,7 @@ extension DatabasePool: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if configuration.readonly { @@ -722,7 +717,7 @@ extension DatabasePool: DatabaseReader { private func _addConcurrent( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -756,7 +751,7 @@ extension DatabasePool: DatabaseWriter { } } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) return @@ -809,7 +804,7 @@ extension DatabasePool: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { writer.async(updates) } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 65b200177..fa9105a01 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -169,7 +169,9 @@ extension DatabaseQueue { // Release memory asynchronously writer.async { db in db.releaseMemory() - application.endBackgroundTask(task) + DispatchQueue.main.async { + application.endBackgroundTask(task) + } } } } @@ -233,7 +235,7 @@ extension DatabaseQueue: DatabaseReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { writer.async { db in defer { // Ignore error because we can not notify it. @@ -258,7 +260,7 @@ extension DatabaseQueue: DatabaseReader { try writer.sync(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { writer.async { value(.success($0)) } } @@ -266,7 +268,7 @@ extension DatabaseQueue: DatabaseReader { try writer.reentrantSync(value) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { + public func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture { // DatabaseQueue can't perform parallel reads. // Perform a blocking read instead. return DatabaseFuture(Result { @@ -279,7 +281,7 @@ extension DatabaseQueue: DatabaseReader { }) } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -309,7 +311,7 @@ extension DatabaseQueue: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if configuration.readonly { @@ -379,7 +381,7 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { writer.async { updates(.success($0)) } } @@ -425,7 +427,7 @@ extension DatabaseQueue: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { writer.async(updates) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 3706b2d4d..f00c724f6 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -213,7 +213,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. - func asyncRead(_ value: @escaping (Result) -> Void) + func asyncRead(_ value: @escaping @Sendable (Result) -> Void) /// Executes database operations, and returns their result after they have /// finished executing. @@ -284,7 +284,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. - func asyncUnsafeRead(_ value: @escaping (Result) -> Void) + func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) /// Executes database operations, and returns their result after they have /// finished executing. @@ -342,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable { func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable } @@ -458,7 +458,7 @@ extension DatabaseReader { /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func read(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func read(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncRead { result in do { @@ -504,7 +504,7 @@ extension DatabaseReader { /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func unsafeRead(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func unsafeRead(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncUnsafeRead { result in do { @@ -551,14 +551,12 @@ extension DatabaseReader { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping (Database) throws -> Output) + value: @escaping @Sendable (Database) throws -> Output) -> DatabasePublishers.Read { - 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) @@ -601,7 +599,7 @@ extension DatabaseReader { func _addReadOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { @@ -619,16 +617,16 @@ extension DatabaseReader { } return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ }) } else { - var isCancelled = false + let cancellable = AnyDatabaseCancellable { } asyncRead { dbResult in - guard !isCancelled else { return } + guard !cancellable.isCancelled else { return } let result = dbResult.flatMap { db in Result { try observation.fetchInitialValue(db) } } scheduler.schedule { - guard !isCancelled else { return } + guard !cancellable.isCancelled else { return } do { try onChange(result.get()) } catch { @@ -636,7 +634,7 @@ extension DatabaseReader { } } } - return AnyDatabaseCancellable(cancel: { isCancelled = true }) + return cancellable } } } @@ -677,7 +675,7 @@ extension AnyDatabaseReader: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncRead(value) } @@ -686,7 +684,7 @@ extension AnyDatabaseReader: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncUnsafeRead(value) } @@ -697,7 +695,7 @@ extension AnyDatabaseReader: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { base._add( @@ -757,7 +755,7 @@ extension DatabaseSnapshotReader { } // There is no such thing as an unsafe access to a snapshot. - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { asyncRead(value) } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 232cd472d..c10f0b1b3 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -378,11 +378,11 @@ private struct TableRegion: Equatable { /// ### Supporting Types /// /// - ``AnyDatabaseRegionConvertible`` -public protocol DatabaseRegionConvertible { +public protocol DatabaseRegionConvertible: Sendable { /// Returns a database region. /// /// - parameter db: A database connection. - func databaseRegion(_ db: Database) throws -> DatabaseRegion + @Sendable func databaseRegion(_ db: Database) throws -> DatabaseRegion } extension DatabaseRegionConvertible where Self == DatabaseRegion { @@ -399,9 +399,9 @@ 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 } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 06d3e8507..cd459e12b 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -43,7 +43,7 @@ extension DatabaseRegionObservation { extension DatabaseRegionObservation { /// The state of a started DatabaseRegionObservation - private enum ObservationState { + private enum ObservationState: Sendable { case cancelled case pending case started(DatabaseRegionObserver) @@ -85,23 +85,23 @@ extension DatabaseRegionObservation { /// - returns: A DatabaseCancellable that can stop the observation. public func start( in writer: some DatabaseWriter, - onError: @escaping (any Error) -> Void, - onChange: @escaping (Database) -> Void) + onError: @escaping @Sendable (any Error) -> Void, + onChange: @escaping @Sendable (Database) -> Void) -> AnyDatabaseCancellable { - @LockedBox var state = ObservationState.pending + let state = LockedBox(wrappedValue: ObservationState.pending) // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. writer.unsafeReentrantWrite { db in do { let region = try observedRegion(db).observableRegion(db) - $state.update { - let observer = DatabaseRegionObserver(region: region, onChange: { - if case .cancelled = state { + state.update { + let observer = DatabaseRegionObserver(region: region, onChange: { db in + if case .cancelled = state.wrappedValue { return } - onChange($0) + onChange(db) }) // Use the `.observerLifetime` extent so that we can cancel @@ -122,7 +122,7 @@ extension DatabaseRegionObservation { // Deallocates the transaction observer. This makes sure that the // `onChange` callback will never be called again, because the // observation was started with the `.observerLifetime` extent. - state = .cancelled + state.wrappedValue = .cancelled } } } @@ -147,12 +147,12 @@ extension DatabaseRegionObservation { } #endif -private class DatabaseRegionObserver: TransactionObserver { +private class DatabaseRegionObserver: TransactionObserver, @unchecked Sendable { let region: DatabaseRegion - let onChange: (Database) -> Void + let onChange: @Sendable (Database) -> Void var isChanged = false - init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) { + init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) { self.region = region self.onChange = onChange } @@ -207,7 +207,7 @@ extension DatabasePublishers { } } - private class DatabaseRegionSubscription: Subscription + private class DatabaseRegionSubscription: Subscription, @unchecked Sendable where Downstream.Failure == any Error, Downstream.Input == Database { private struct WaitingForDemand { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 4811cc494..4222a36cb 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { try reader.sync(block) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { reader.async { value(.success($0)) } } @@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { try reader.sync(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { reader.async { value(.success($0)) } } @@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { _addReadOnly( diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 18f12bbdf..6b9c5ee8d 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -292,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -330,7 +330,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { _addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 47f54c5af..b7b8f74fc 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -301,7 +301,7 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -335,7 +335,7 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -370,7 +370,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - adapter: Optional RowAdapter /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -447,7 +447,7 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -482,7 +482,7 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -516,7 +516,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - adapter: Optional RowAdapter /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -603,7 +603,7 @@ extension DatabaseValueConvertible { /// - request: A FetchRequest. /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { + @Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchAll(request.statement, adapter: request.adapter) } @@ -640,7 +640,7 @@ extension DatabaseValueConvertible { /// - request: A FetchRequest. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) return try fetchOne(request.statement, adapter: request.adapter) } @@ -676,7 +676,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - request: A FetchRequest. /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + @Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchSet(request.statement, adapter: request.adapter) } @@ -753,7 +753,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + @Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } @@ -787,7 +787,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + @Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } @@ -820,7 +820,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try RowDecoder.fetchSet(db, self) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 055a5bf6f..02da0cb32 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -181,7 +181,7 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the barrier access to the database. - func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) + func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) /// Schedules database operations for execution, and returns immediately. /// @@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader { /// for more information. /// /// - parameter updates: A closure which accesses the database. - func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) /// Executes database operations, and returns their result after they have /// finished executing. @@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader { /// returned ``DatabaseFuture`` blocks a thread. You may prefer /// ``spawnConcurrentRead(_:)`` instead. /// - parameter value: A closure which accesses the database. - func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture + func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture // Exposed for RxGRDB and GRBCombine. Naming is not stabilized. /// Schedules read-only database operations for execution. @@ -340,7 +340,7 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. - func spawnConcurrentRead(_ value: @escaping (Result) -> Void) + func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) } extension DatabaseWriter { @@ -426,8 +426,8 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - parameter completion: A closure called with the transaction result. public func asyncWrite( - _ updates: @escaping (Database) throws -> T, - completion: @escaping (Database, Result) -> Void) + _ updates: @escaping @Sendable (Database) throws -> T, + completion: @escaping @Sendable (Database, Result) -> Void) { asyncWriteWithoutTransaction { db in do { @@ -557,7 +557,7 @@ extension DatabaseWriter { func _addWriteOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -608,7 +608,7 @@ extension DatabaseWriter { /// would happen while establishing the database access or committing /// the transaction. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func write(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func write(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncWrite(updates, completion: { _, result in continuation.resume(with: result) @@ -646,7 +646,7 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func writeWithoutTransaction(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func writeWithoutTransaction(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncWriteWithoutTransaction { db in do { @@ -699,7 +699,7 @@ extension DatabaseWriter { /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func barrierWriteWithoutTransaction( - _ updates: @Sendable @escaping (Database) throws -> T) + _ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -803,7 +803,7 @@ extension DatabaseWriter { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - updates: @escaping (Database) throws -> Output) + updates: @escaping @Sendable (Database) throws -> Output) -> DatabasePublishers.Write { OnDemandFuture { fulfill in @@ -866,10 +866,10 @@ extension DatabaseWriter { /// - parameter updates: A closure which writes in the database. /// - parameter value: A closure which reads from the database. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func writePublisher( + public func writePublisher( receiveOn scheduler: S = DispatchQueue.main, - updates: @escaping (Database) throws -> T, - thenRead value: @escaping (Database, T) throws -> Output) + updates: @escaping @Sendable (Database) throws -> T, + thenRead value: @escaping @Sendable (Database, T) throws -> Output) -> DatabasePublishers.Write where S: Scheduler { @@ -885,7 +885,7 @@ extension DatabaseWriter { fulfill(.failure(error)) return } - self.spawnConcurrentRead { dbResult in + self.spawnConcurrentRead { [updatesValue] dbResult in fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } }) } } @@ -941,7 +941,7 @@ extension Publisher where Failure == any Error { /// /// let count: Int = try futureCount.wait() /// ``` -public class DatabaseFuture { +public class DatabaseFuture { private var consumed = false private let _wait: () throws -> Value @@ -967,6 +967,31 @@ public class DatabaseFuture { } } +/// Helps building DatabaseFuture with strict concurrency checkings +final class DatabaseFutureBuilder: @unchecked Sendable { + /// The semaphore that blocks until result is set. + let semaphore = DispatchSemaphore(value: 0) + + var result: Result? = nil + + init() { } + + /// - precondition: MUST be called once. + func resolve(_ result: Result) { + self.result = result + semaphore.signal() + } + + /// - precondition: MUST be called once. + func future() -> DatabaseFuture { + DatabaseFuture { [self] in + // Block the future until results are fetched + _ = semaphore.wait(timeout: .distantFuture) + return try result!.get() + } + } +} + /// A type-erased database writer. /// /// An instance of `AnyDatabaseWriter` forwards its operations to an underlying @@ -1003,7 +1028,7 @@ extension AnyDatabaseWriter: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncRead(value) } @@ -1012,7 +1037,7 @@ extension AnyDatabaseWriter: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncUnsafeRead(value) } @@ -1023,7 +1048,7 @@ extension AnyDatabaseWriter: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { base._add( @@ -1044,11 +1069,11 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.barrierWriteWithoutTransaction(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { base.asyncBarrierWriteWithoutTransaction(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { base.asyncWriteWithoutTransaction(updates) } @@ -1056,11 +1081,11 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { + public func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture { base.concurrentRead(value) } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { base.spawnConcurrentRead(value) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 87ff4b340..97e207317 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -166,7 +166,7 @@ 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 { + public func adapted(_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } } @@ -176,11 +176,11 @@ extension FetchRequest { /// See ``FetchRequest/adapted(_:)``. public struct AdaptedFetchRequest { 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 } @@ -195,7 +195,7 @@ extension AdaptedFetchRequest: SQLSubqueryable { extension AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder - public func fetchCount(_ db: Database) throws -> Int { + @Sendable public func fetchCount(_ db: Database) throws -> Int { try base.fetchCount(db) } @@ -255,7 +255,7 @@ extension AnyFetchRequest: SQLSubqueryable { } extension AnyFetchRequest: FetchRequest { - public func fetchCount(_ db: Database) throws -> Int { + @Sendable public func fetchCount(_ db: Database) throws -> Int { try request.fetchCount(db) } @@ -269,7 +269,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 { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 4c3698f7e..16fcf533a 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1447,7 +1447,7 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -1476,7 +1476,7 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -1505,7 +1505,7 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -1589,7 +1589,7 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -1618,7 +1618,7 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -1647,7 +1647,7 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -1736,7 +1736,7 @@ extension Row { /// - request: A FetchRequest. /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] { + @Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] { let request = try request.makePreparedRequest(db, forSingleResult: false) let rows = try fetchAll(request.statement, adapter: request.adapter) try request.supplementaryFetch?(db, rows, nil) @@ -1768,7 +1768,7 @@ extension Row { /// - request: A FetchRequest. /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + @Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try fetchAll(request.statement, adapter: request.adapter) @@ -1804,7 +1804,7 @@ extension Row { /// - request: A FetchRequest. /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? { + @Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? { let request = try request.makePreparedRequest(db, forSingleResult: true) guard let row = try fetchOne(request.statement, adapter: request.adapter) else { return nil @@ -1874,7 +1874,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: An array of fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { + @Sendable public func fetchAll(_ db: Database) throws -> [Row] { try Row.fetchAll(db, self) } @@ -1895,7 +1895,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: A set of fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try Row.fetchSet(db, self) } @@ -1916,7 +1916,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { + @Sendable public func fetchOne(_ db: Database) throws -> Row? { try Row.fetchOne(db, self) } } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index a17062460..d755640b0 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -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 } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 6ec272c57..274d675e1 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -191,7 +191,7 @@ extension SQLRequest: FetchRequest { .literal(sqlLiteral) } - public func fetchCount(_ db: Database) throws -> Int { + @Sendable public func fetchCount(_ db: Database) throws -> Int { try SQLRequest("SELECT COUNT(*) FROM (\(self))").fetchOne(db)! } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index f1dfe0572..fa5f86dc0 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -223,7 +223,7 @@ final class SerializedDatabase { } /// Schedules database operations for execution, and returns immediately. - func async(_ block: @escaping (Database) -> Void) { + func async(_ block: @escaping @Sendable (Database) -> Void) { queue.async { block(self.db) self.preconditionNoUnsafeTransactionLeft(self.db) diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 3b18bcb9a..23893eaa3 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -312,7 +312,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -346,7 +346,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -384,7 +384,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - adapter: Optional RowAdapter /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -461,7 +461,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -496,7 +496,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -530,7 +530,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - adapter: Optional RowAdapter /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -619,7 +619,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A FetchRequest. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { + @Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchAll(request.statement, adapter: request.adapter) } @@ -656,7 +656,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A FetchRequest. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) return try fetchOne(request.statement, adapter: request.adapter) } @@ -692,7 +692,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - request: A FetchRequest. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + @Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchSet(request.statement, adapter: request.adapter) } @@ -769,7 +769,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + @Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } @@ -803,7 +803,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + @Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } @@ -836,7 +836,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try RowDecoder.fetchSet(db, self) } } diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index ea4ca1e35..0d707df84 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -4,7 +4,7 @@ import Foundation public struct DatabaseDateComponents { /// The SQLite formats for date components. - public enum Format: String { + public enum Format: String, Sendable { /// The format "yyyy-MM-dd". case YMD = "yyyy-MM-dd" diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 72861ac02..9bc4683be 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -1,6 +1,7 @@ #if !os(Linux) import Foundation +// GRDB7: remove conformance because NSData is not Sendable. /// NSData is convertible to and from DatabaseValue. extension NSData: DatabaseValueConvertible { diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index acddddb35..2a006a772 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -1,6 +1,7 @@ #if !os(Linux) import Foundation +// GRDB7: remove conformance because NSString is not Sendable. /// NSString adopts DatabaseValueConvertible extension NSString: DatabaseValueConvertible { diff --git a/GRDB/Core/TransactionClock.swift b/GRDB/Core/TransactionClock.swift index d878cd450..b467ce724 100644 --- a/GRDB/Core/TransactionClock.swift +++ b/GRDB/Core/TransactionClock.swift @@ -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 } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 995515947..36f768ab4 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -101,14 +101,17 @@ extension Database { /// - parameter onCommit: A closure executed on transaction commit. /// - parameter onRollback: A closure executed on transaction rollback. public func afterNextTransaction( - onCommit: @escaping (Database) -> Void, - onRollback: @escaping (Database) -> Void = { _ in }) + onCommit: @escaping @Sendable (Database) -> Void, + onRollback: @escaping @Sendable (Database) -> Void = { _ in }) { class TransactionHandler: TransactionObserver { - let onCommit: (Database) -> Void - let onRollback: (Database) -> Void + let onCommit: @Sendable (Database) -> Void + let onRollback: @Sendable (Database) -> Void - init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) { + init( + onCommit: @escaping @Sendable (Database) -> Void, + onRollback: @escaping @Sendable (Database) -> Void) + { self.onCommit = onCommit self.onRollback = onRollback } diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index 32eb3afca..336b579be 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -4,9 +4,9 @@ /// /// `WALSnapshotTransaction` **takes ownership** of its reader /// `SerializedDatabase` (TODO: make it a move-only type eventually). -class WALSnapshotTransaction { +final class WALSnapshotTransaction: Sendable { private let reader: SerializedDatabase - private let release: (_ isInsideTransaction: Bool) -> Void + private let release: @Sendable (_ isInsideTransaction: Bool) -> Void /// The state of the database at the beginning of the transaction. let walSnapshot: WALSnapshot @@ -37,7 +37,7 @@ 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) @@ -71,7 +71,7 @@ class WALSnapshotTransaction { /// Schedules database operations for execution, and /// returns immediately. - func asyncRead(_ value: @escaping (Database) -> Void) { + func asyncRead(_ value: @escaping @Sendable (Database) -> Void) { // We should check the validity of the snapshot, as DatabaseSnapshotPool does. reader.async(value) } diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index a294c35b3..f0dbc932a 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -50,7 +50,7 @@ extension Database { init( db: Database, - constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> CInt) + constructor: @escaping @Sendable (Database, [String], UnsafeMutablePointer?) -> CInt) { self.db = db self.constructor = constructor diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 67673cb3e..adf4a824b 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -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 { /// 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 { @@ -264,7 +264,7 @@ public struct DatabaseMigrator { /// from succeeding. public func asyncMigrate( _ writer: some DatabaseWriter, - completion: @escaping (Result) -> Void) + completion: @escaping @Sendable (Result) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in do { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 36676d017..5a100bdec 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -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 { diff --git a/GRDB/QueryInterface/ForeignKey.swift b/GRDB/QueryInterface/ForeignKey.swift index f89ee964c..fbe27461d 100644 --- a/GRDB/QueryInterface/ForeignKey.swift +++ b/GRDB/QueryInterface/ForeignKey.swift @@ -80,7 +80,7 @@ /// using: Book.translatorForeignKey) /// } /// ``` -public struct ForeignKey: Equatable { +public struct ForeignKey: Equatable, Sendable { var originColumns: [String] var destinationColumns: [String]? diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index debe9590a..b7e9f72f8 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -173,7 +173,7 @@ 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 +181,7 @@ 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 +192,7 @@ 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 +203,7 @@ 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 +239,7 @@ 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 +247,7 @@ 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 diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 17d192fb2..ee505fa3b 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -385,7 +385,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -421,7 +421,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Destination.Type, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation where Destination: TableRecord { @@ -458,7 +458,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Table, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index c573a2f3c..749350470 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -86,7 +86,7 @@ extension QueryInterfaceRequest: FetchRequest { .relation(relation) } - public func fetchCount(_ db: Database) throws -> Int { + @Sendable public func fetchCount(_ db: Database) throws -> Int { try relation.fetchCount(db) } @@ -117,7 +117,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 { @@ -281,7 +281,7 @@ extension QueryInterfaceRequest: SelectionRequest { } public func annotatedWhenConnected( - with selection: @escaping (Database) throws -> [any SQLSelectable]) + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self { with { @@ -294,7 +294,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 { @@ -307,7 +307,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 { @@ -354,7 +354,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 { @@ -365,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest { } public func havingWhenConnected( - _ predicate: @escaping (Database) throws -> any SQLExpressible) + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self { with { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index def5c2f52..2001882eb 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -58,7 +58,7 @@ 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 +78,7 @@ 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 +240,7 @@ 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 { @@ -729,7 +729,7 @@ 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. /// @@ -753,7 +753,7 @@ 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 { @@ -934,7 +934,7 @@ 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. /// diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index 9d497b584..2949c1e5d 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -21,9 +21,9 @@ /// /// Such late computations are backed by DatabasePromise. In our example, /// see SQLRelation.filterPromise. -struct DatabasePromise { +struct DatabasePromise { /// 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) { @@ -31,12 +31,12 @@ struct DatabasePromise { } /// 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(_ transform: @escaping (T) throws -> U) -> DatabasePromise { + func map(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise { DatabasePromise { db in try transform(resolve(db)) } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 3613bdb16..1af13cd63 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -57,7 +57,7 @@ public struct SQLExpression { var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite /// The private implementation of the public `SQLExpression`. - private enum Impl { + private enum Impl: Sendable { /// A column. /// /// id @@ -315,7 +315,7 @@ public struct SQLExpression { /// 1000.databaseValue] /// let request = Player.select(values.joined(operator: .add)) /// ``` - public struct AssociativeBinaryOperator: Hashable { + public struct AssociativeBinaryOperator: Hashable, Sendable { /// The SQL operator let sql: String @@ -2109,7 +2109,7 @@ extension SQLExpression { /// A type that can be used as an SQL expression. /// /// Related SQLite documentation -public protocol SQLExpressible { +public protocol SQLExpressible: Sendable { /// Returns an SQL expression. var sqlExpression: SQLExpression { get } } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index e7b18f974..0cfa330ae 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -138,7 +138,7 @@ extension SQLOrdering { /// ### Supporting Type /// /// - ``SQLOrdering`` -public protocol SQLOrderingTerm { +public protocol SQLOrderingTerm: Sendable { /// Returns an SQL ordering. var sqlOrdering: SQLOrdering { get } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 9f01841c2..e1c4a869e 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -90,8 +90,8 @@ /// // JOIN passport ON passport.citizenId = citizens.id /// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...); /// Country.including(all: Country.citizens) -struct SQLRelation { - struct Child: Refinable { +struct SQLRelation: Sendable { + struct Child: Refinable, Sendable { enum Kind { // Record.including(optional: association) case oneOptional @@ -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. @@ -847,7 +847,7 @@ enum SQLAssociationCondition { } /// An association condition based on a foreign key. -struct SQLForeignKeyCondition: Equatable { +struct SQLForeignKeyCondition: Equatable, Sendable { /// The destination table of an association. /// /// In `Author.hasMany(Book.self)`, the destination is `book`. diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index 351b48377..952d159b4 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -19,7 +19,7 @@ public struct SQLSelection { private var impl: Impl /// The private implementation of the public `SQLSelection`. - private enum Impl { + private enum Impl: Sendable { /// All columns: `*` case allColumns @@ -301,7 +301,7 @@ enum SQLCount { /// /// - ``AllColumns`` /// - ``SQLSelection`` -public protocol SQLSelectable { +public protocol SQLSelectable: Sendable { /// Returns an SQL selection. var sqlSelection: SQLSelection { get } } diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 0bad29a8e..0836c1e48 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -138,7 +138,7 @@ /// ### Database Observation Support /// /// - ``databaseRegion(_:)`` -public struct Table { +public struct Table: Sendable { /// The table name. public var tableName: String @@ -800,7 +800,7 @@ extension Table { /// ``` /// /// - parameter db: A database connection. - public func fetchCount(_ db: Database) throws -> Int { + @Sendable public func fetchCount(_ db: Database) throws -> Int { try all().fetchCount(db) } } @@ -860,7 +860,7 @@ extension Table where RowDecoder: FetchableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + @Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] { try all().fetchAll(db) } @@ -880,7 +880,7 @@ extension Table where RowDecoder: FetchableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + @Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) } } @@ -902,7 +902,7 @@ extension Table where RowDecoder: FetchableRecord & Hashable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } } @@ -961,7 +961,7 @@ extension Table where RowDecoder == Row { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { + @Sendable public func fetchAll(_ db: Database) throws -> [Row] { try all().fetchAll(db) } @@ -980,7 +980,7 @@ extension Table where RowDecoder == Row { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { + @Sendable public func fetchOne(_ db: Database) throws -> Row? { try all().fetchOne(db) } @@ -999,7 +999,7 @@ extension Table where RowDecoder == Row { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } } @@ -1034,7 +1034,7 @@ extension Table where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + @Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] { try all().fetchAll(db) } @@ -1048,7 +1048,7 @@ extension Table where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + @Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) } } @@ -1061,7 +1061,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable { /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } } @@ -1096,7 +1096,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + @Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] { try all().fetchAll(db) } @@ -1110,7 +1110,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + @Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) } } @@ -1123,7 +1123,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } } @@ -1297,7 +1297,7 @@ extension Table { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 17551514b..9f615b98c 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -547,7 +547,7 @@ struct SQLQueryGenerator: Refinable { /// ORDER BY ... -- ordering /// LIMIT ... -- limit -private struct SQLQualifiedRelation { +private struct SQLQualifiedRelation: Sendable { /// All aliases, including aliases of joined relations var allAliases: [TableAlias] { joins.reduce(into: [source.alias].compactMap { $0 }) { @@ -713,7 +713,7 @@ private struct SQLQualifiedRelation { extension SQLQualifiedRelation: Refinable { } /// A "qualified" source, where all tables are identified with a table alias. -private struct SQLQualifiedSource { +private struct SQLQualifiedSource: Sendable { var tableName: String var alias: TableAlias diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index e86a54814..374911316 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -339,7 +339,7 @@ extension TableRecord { /// - returns: An association to the common table expression. public static func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -540,6 +540,7 @@ extension TableRecord { // MARK: - Request for associated records extension TableRecord where Self: EncodableRecord { + // TODO: GRDB7: require that Self is Sendable /// Returns a request for the associated record(s). /// /// For example: diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 97178adeb..ca43d70c4 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -52,7 +52,7 @@ extension FetchableRecord where Self: TableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database) throws -> [Self] { + @Sendable public static func fetchAll(_ db: Database) throws -> [Self] { try all().fetchAll(db) } @@ -71,7 +71,7 @@ extension FetchableRecord where Self: TableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database) throws -> Self? { try all().fetchOne(db) } } @@ -92,7 +92,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database) throws -> Set { + @Sendable public static func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } } @@ -154,7 +154,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Keys) + @Sendable public static func fetchAll(_ db: Database, keys: Keys) throws -> [Self] where Keys: Sequence, Keys.Element: DatabaseValueConvertible { @@ -182,7 +182,7 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { if key.databaseValue.isNull { // Don't hit the database return nil @@ -275,7 +275,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, ids: IDS) throws -> [Self] + @Sendable public static func fetchAll(_ db: Database, ids: IDS) throws -> [Self] where IDS: Collection, IDS.Element == ID { if ids.isEmpty { @@ -301,7 +301,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - id: A primary key value. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, id: ID) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database, id: ID) throws -> Self? { try filter(id: id).fetchOne(db) } @@ -346,7 +346,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: A sequence of primary keys. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: Keys) + @Sendable public static func fetchSet(_ db: Database, keys: Keys) throws -> Set where Keys: Sequence, Keys.Element: DatabaseValueConvertible { @@ -377,7 +377,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: /// - ids: A collection of primary keys. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, ids: IDS) throws -> Set + @Sendable public static func fetchSet(_ db: Database, ids: IDS) throws -> Set where IDS: Collection, IDS.Element == ID { if ids.isEmpty { @@ -449,7 +449,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { + @Sendable public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { if keys.isEmpty { // Avoid hitting the database return [] @@ -473,7 +473,7 @@ extension FetchableRecord where Self: TableRecord { /// - key: A key dictionary. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { guard let key else { // Avoid hitting the database return nil @@ -527,7 +527,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: An array of key dictionaries. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set { + @Sendable public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set { if keys.isEmpty { // Avoid hitting the database return [] diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index c36fe41c9..b4c338fc8 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -320,7 +320,7 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -348,7 +348,7 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -378,7 +378,7 @@ extension FetchableRecord where Self: Hashable { /// - adapter: Optional RowAdapter /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) @@ -449,7 +449,7 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll( + @Sendable public static func fetchAll( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -478,7 +478,7 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne( + @Sendable public static func fetchOne( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -509,7 +509,7 @@ extension FetchableRecord where Self: Hashable { /// - adapter: Optional RowAdapter /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet( + @Sendable public static func fetchSet( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), @@ -589,7 +589,7 @@ extension FetchableRecord { /// - sql: a FetchRequest. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { + @Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) @@ -624,7 +624,7 @@ extension FetchableRecord { /// - sql: a FetchRequest. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { + @Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) if let supplementaryFetch = request.supplementaryFetch { guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else { @@ -664,7 +664,7 @@ extension FetchableRecord where Self: Hashable { /// - sql: a FetchRequest. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + @Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) @@ -746,7 +746,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - sql: a FetchRequest. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + @Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } @@ -774,7 +774,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - sql: a FetchRequest. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + @Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } @@ -805,7 +805,7 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// - sql: a FetchRequest. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + @Sendable public func fetchSet(_ db: Database) throws -> Set { try RowDecoder.fetchSet(db, self) } } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 4e8d8b1b4..95f3d3153 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -224,7 +224,7 @@ extension TableRecord { /// ``` /// /// - parameter db: A database connection. - public static func fetchCount(_ db: Database) throws -> Int { + @Sendable public static func fetchCount(_ db: Database) throws -> Int { try all().fetchCount(db) } } diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index 58338ec4f..08c53d675 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -43,8 +43,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. extension Inflections { - /// The default inflections - public static var `default`: Inflections = { + static func makeEnglishInflections() -> Self { // Defines the standard inflection rules. These are the starting point // for new projects and are not considered complete. The current set of // inflection rules is frozen. This means, we do not change them to @@ -134,5 +133,5 @@ extension Inflections { inflections.irregularSuffix("zombie", "zombies") return inflections - }() + } } diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index 860b4d0ba..9384a7897 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -32,6 +32,14 @@ extension String { /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) public struct Inflections { + @LockedBox fileprivate static var defaultInflections: Inflections = makeEnglishInflections() + + /// The default inflections + public static var `default`: Inflections { + get { defaultInflections } + set { defaultInflections = newValue } + } + private var pluralizeRules: [(NSRegularExpression, String)] = [] private var singularizeRules: [(NSRegularExpression, String)] = [] private var uncountablesRegularExpressions: [String: NSRegularExpression] = [:] diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index 6826014a4..9f54da8c3 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -16,12 +16,11 @@ import Foundation /// queue, and fulfill GRDB preconditions. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) struct OnDemandFuture: Publisher { - typealias Promise = (Result) -> Void typealias Output = Output typealias Failure = Failure - fileprivate let attemptToFulfill: (@escaping Promise) -> Void + fileprivate let attemptToFulfill: (@escaping @Sendable (Result) -> Void) -> Void - init(_ attemptToFulfill: @escaping (@escaping Promise) -> Void) { + init(_ attemptToFulfill: @escaping (@escaping @Sendable (Result) -> Void) -> Void) { self.attemptToFulfill = attemptToFulfill } @@ -34,8 +33,8 @@ struct OnDemandFuture: Publisher { } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -private class OnDemandFutureSubscription: Subscription { - typealias Promise = (Result) -> Void +private final class OnDemandFutureSubscription: Subscription, @unchecked Sendable { + typealias Promise = @Sendable (Result) -> Void private enum State { case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void) diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 4f7d5242b..228f84dfc 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -207,6 +207,8 @@ extension OrderedDictionary: CustomStringConvertible { } } +extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable { } + extension Dictionary { init(_ orderedDictionary: OrderedDictionary) { self = orderedDictionary.dictionary diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 9dba92203..3130e8b73 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -35,8 +35,9 @@ import Dispatch /// got 2 /// got 1 /// got 3 -final class Pool { - private class Item { +final class Pool: @unchecked Sendable { + // @unchecked Sendable because protected by Pool. + private class Item: @unchecked Sendable { let element: T var isAvailable: Bool @@ -75,7 +76,7 @@ final class Pool { /// 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 -> (element: T, release: @Sendable (PoolCompletion) -> Void) { try barrierQueue.sync { itemsSemaphore.wait() itemsGroup.enter() @@ -107,7 +108,7 @@ final class Pool { /// /// - 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), any Error>) -> Void) { + func asyncGet(_ execute: @escaping @Sendable (Result<(element: T, release: @Sendable (PoolCompletion) -> Void), any 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 @@ -172,7 +173,7 @@ final class Pool { /// Asynchronously runs the `barrier` function when no element is used, and /// before any other element is dequeued. - func asyncBarrier(execute barrier: @escaping () -> Void) { + func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) { barrierQueue.async(flags: [.barrier]) { self.itemsGroup.wait() barrier() diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 881193137..0a981d51d 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -67,7 +67,7 @@ extension Dictionary { } extension DispatchQueue { - private static var mainKey: DispatchSpecificKey<()> = { + private static let mainKey: DispatchSpecificKey<()> = { let key = DispatchSpecificKey<()>() DispatchQueue.main.setSpecific(key: key, value: ()) return key @@ -124,8 +124,21 @@ struct PrintOutputStream: TextOutputStream { } } +final class LockedTextOutputStream: @unchecked Sendable { + var stream: any TextOutputStream + let lock = NSLock() + init(stream: any TextOutputStream) { + self.stream = stream + } + func write(_ string: String) { + lock.lock() + defer { lock.unlock() } + stream.write(string) + } +} + /// Concatenates two functions -func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? { +func concat(_ rhs: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (@Sendable () -> Void)? { switch (rhs, lhs) { case let (rhs, nil): return rhs @@ -140,7 +153,7 @@ func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? { } /// Concatenates two functions -func concat(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? { +func concat(_ rhs: (@Sendable (T) -> Void)?, _ lhs: (@Sendable(T) -> Void)?) -> (@Sendable(T) -> Void)? { switch (rhs, lhs) { case let (rhs, nil): return rhs diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index de6298791..80b6a5daf 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -5,7 +5,7 @@ /// ### Supporting Types /// /// - ``AnyDatabaseCancellable`` -public protocol DatabaseCancellable { +public protocol DatabaseCancellable: Sendable { /// Cancel the activity. func cancel() } @@ -15,31 +15,35 @@ public protocol DatabaseCancellable { /// /// An `AnyDatabaseCancellable` instance automatically calls ``cancel()`` /// when deinitialized. -public class AnyDatabaseCancellable: DatabaseCancellable { - private var _cancel: (() -> Void)? +public class AnyDatabaseCancellable: DatabaseCancellable, @unchecked Sendable { + @LockedBox private var _cancel: (() -> Void)? + + var isCancelled: Bool { + _cancel == nil + } /// Initializes the cancellable object with the given cancel-time closure. - public init(cancel: @escaping () -> Void) { + public init(cancel: @escaping @Sendable () -> Void) { _cancel = 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 = $_cancel.update { + let result = $0 + $0 = nil + return result + } + cancel?() } } diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index e8075f00f..2f5d310d6 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -18,7 +18,7 @@ import Foundation /// reducing stage. /// /// **Notify** is calling user callbacks, in case of database change or error. -final class ValueConcurrentObserver { +final class ValueConcurrentObserver: @unchecked Sendable { // MARK: - Configuration // // Configuration is not mutable. @@ -72,7 +72,7 @@ final class ValueConcurrentObserver Void + let onChange: @Sendable (Reducer.Value) -> Void } /// Relationship with the `TransactionObserver` protocol @@ -161,7 +161,7 @@ final class ValueConcurrentObserver Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) { // Configuration self.scheduler = scheduler @@ -373,7 +373,7 @@ extension ValueConcurrentObserver { // // Reducing is performed asynchronously, so that we do not lock // a database dispatch queue longer than necessary. - self.reduceQueue.async { + self.reduceQueue.async { [fetchedValue] in let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ } @@ -383,7 +383,7 @@ extension ValueConcurrentObserver { } // Notify - self.scheduler.schedule { + self.scheduler.schedule { [initialValue] in let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } guard let onChange else { return /* Cancelled */ } onChange(initialValue) @@ -419,24 +419,24 @@ extension ValueConcurrentObserver { initialFetchTransaction: WALSnapshotTransaction, initialRegion: DatabaseRegion) { - // We'll start the observation when we can access the writer - // connection. Until then, maybe the database has been modified - // since the initial fetch: we'll then need to notify a fresh value. - // - // To know if the database has been modified between the initial - // fetch and the writer access, we'll compare WAL snapshots. - // - // WAL snapshots can only be compared if the database is not - // checkpointed. That's why we'll keep `initialFetchTransaction` - // alive until the comparison is done. - // - // However, we want to release `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 - - databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in + databaseAccess.dbPool.asyncWriteWithoutTransaction { [initialFetchTransaction] writerDB in + // We'll start the observation when we can access the writer + // connection. Until then, maybe the database has been modified + // since the initial fetch: we'll then need to notify a fresh value. + // + // To know if the database has been modified between the initial + // fetch and the writer access, we'll compare WAL snapshots. + // + // WAL snapshots can only be compared if the database is not + // checkpointed. That's why we'll keep `initialFetchTransaction` + // alive until the comparison is done. + // + // However, we want to release `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 + let events = self.lock.synchronized { self.notificationCallbacks?.events } guard let events else { return /* Cancelled */ } diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index 1c2e69504..43b3612e2 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -21,7 +21,7 @@ import Foundation final class ValueWriteOnlyObserver< Writer: DatabaseWriter, Reducer: ValueReducer, - Scheduler: ValueObservationScheduler> + Scheduler: ValueObservationScheduler>: @unchecked Sendable { // MARK: - Configuration // @@ -76,7 +76,7 @@ final class ValueWriteOnlyObserver< // be notified. See error catching clauses. /// Ability to access the database - private struct DatabaseAccess { + private struct DatabaseAccess: Sendable { /// The observed DatabaseWriter. let writer: Writer @@ -112,7 +112,7 @@ final class ValueWriteOnlyObserver< /// Ability to notify observation events private struct NotificationCallbacks { let events: ValueObservationEvents - let onChange: (Reducer.Value) -> Void + let onChange: @Sendable (Reducer.Value) -> Void } /// Relationship with the `TransactionObserver` protocol @@ -150,7 +150,7 @@ final class ValueWriteOnlyObserver< trackingMode: ValueObservationTrackingMode, reducer: Reducer, events: ValueObservationEvents, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) { // Configuration self.scheduler = scheduler diff --git a/GRDB/ValueObservation/Reducers/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift index 4f9b16c88..007aa162e 100644 --- a/GRDB/ValueObservation/Reducers/Fetch.swift +++ b/GRDB/ValueObservation/Reducers/Fetch.swift @@ -1,10 +1,10 @@ extension ValueReducers { /// A `ValueReducer` that perform database fetches. - public struct Fetch: ValueReducer { - private let __fetch: (Database) throws -> Value + public struct Fetch: ValueReducer { + private let __fetch: @Sendable (Database) throws -> Value /// Creates a reducer which passes raw fetched values through. - init(fetch: @escaping (Database) throws -> Value) { + init(fetch: @escaping @Sendable (Database) throws -> Value) { self.__fetch = fetch } diff --git a/GRDB/ValueObservation/Reducers/Map.swift b/GRDB/ValueObservation/Reducers/Map.swift index b69984b24..becd79c93 100644 --- a/GRDB/ValueObservation/Reducers/Map.swift +++ b/GRDB/ValueObservation/Reducers/Map.swift @@ -18,7 +18,7 @@ extension ValueObservation { /// /// - parameter transform: A closure that takes one value as its parameter /// and returns a new value. - public func map(_ transform: @escaping (Reducer.Value) throws -> T) + public func map(_ transform: @escaping @Sendable (Reducer.Value) throws -> T) -> ValueObservation> { mapReducer { ValueReducers.Map($0, transform) } @@ -30,11 +30,11 @@ extension ValueReducers { /// passed through a transform function. /// /// See ``ValueObservation/map(_:)``. - public struct Map: _ValueReducer { + public struct Map: _ValueReducer { private var base: Base - private let transform: (Base.Value) throws -> Value + private let transform: @Sendable (Base.Value) throws -> Value - init(_ base: Base, _ transform: @escaping (Base.Value) throws -> Value) { + init(_ base: Base, _ transform: @escaping @Sendable (Base.Value) throws -> Value) { self.base = base self.transform = transform } diff --git a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift index 6d2e64e53..5417f2941 100644 --- a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift @@ -5,7 +5,7 @@ extension ValueObservation { /// - parameter predicate: A closure to evaluate whether two values are /// equivalent, for purposes of filtering. Return true from this closure /// to indicate that the second element is a duplicate of the first. - public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool) + public func removeDuplicates(by predicate: @escaping @Sendable (Reducer.Value, Reducer.Value) -> Bool) -> ValueObservation> { mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) } @@ -58,7 +58,9 @@ extension ValueObservation where Reducer.Value: Equatable { public func removeDuplicates() -> ValueObservation> { - mapReducer { ValueReducers.RemoveDuplicates($0, predicate: ==) } + mapReducer { + ValueReducers.RemoveDuplicates($0, predicate: { $0 == $1 }) + } } } @@ -70,9 +72,9 @@ extension ValueReducers { public struct RemoveDuplicates: _ValueReducer { private var base: Base private var previousValue: Base.Value? - private var predicate: (Base.Value, Base.Value) -> Bool + private var predicate: @Sendable (Base.Value, Base.Value) -> Bool - init(_ base: Base, predicate: @escaping (Base.Value, Base.Value) -> Bool) { + init(_ base: Base, predicate: @escaping @Sendable (Base.Value, Base.Value) -> Bool) { self.base = base self.predicate = predicate } diff --git a/GRDB/ValueObservation/Reducers/Trace.swift b/GRDB/ValueObservation/Reducers/Trace.swift index bb2db4f62..d31df0b0a 100644 --- a/GRDB/ValueObservation/Reducers/Trace.swift +++ b/GRDB/ValueObservation/Reducers/Trace.swift @@ -6,8 +6,8 @@ extension ValueReducers { /// and ``ValueObservation/print(_:to:)``. public struct Trace: _ValueReducer { var base: Base - let willFetch: () -> Void - let didReceiveValue: (Base.Value) -> Void + let willFetch: @Sendable () -> Void + let didReceiveValue: @Sendable (Base.Value) -> Void public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { guard let value = try base._value(fetched) else { diff --git a/GRDB/ValueObservation/Reducers/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift index 0a4706057..2444b48d5 100644 --- a/GRDB/ValueObservation/Reducers/ValueReducer.swift +++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift @@ -1,10 +1,10 @@ /// Implementation details of `ValueReducer`. -public protocol _ValueReducer { +public protocol _ValueReducer: Sendable { /// The type of fetched database values - associatedtype Fetched + associatedtype Fetched: Sendable /// The type of observed values - associatedtype Value + associatedtype Value: Sendable /// Transforms a fetched value into an eventual observed value. Returns nil /// when observer should not be notified. diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index c327163a7..7416fd7bb 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -1,7 +1,7 @@ import Foundation /// The extent of the shared subscription to a ``SharedValueObservation``. -public enum SharedValueObservationExtent { +public enum SharedValueObservationExtent: Sendable { /// The ``SharedValueObservation`` starts a single database observation, /// which stops when the `SharedValueObservation` is deallocated and all /// subscriptions terminated. @@ -167,7 +167,7 @@ extension ValueObservation { /// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// ``` -public final class SharedValueObservation { +public final class SharedValueObservation: @unchecked Sendable { private let scheduler: any ValueObservationScheduler private let extent: SharedValueObservationExtent private let startObservation: ValueObservationStart @@ -179,11 +179,14 @@ public final class SharedValueObservation { private var cancellable: AnyDatabaseCancellable? private var lastResult: Result? - private final class Client { - var onError: (any Error) -> Void - var onChange: (Element) -> Void + private final class Client: Sendable { + let onError: @Sendable (any Error) -> Void + let onChange: @Sendable (Element) -> Void - init(onError: @escaping (any Error) -> Void, onChange: @escaping (Element) -> Void) { + init( + onError: @escaping @Sendable (any Error) -> Void, + onChange: @escaping @Sendable (Element) -> Void) + { self.onError = onError self.onChange = onChange } @@ -224,8 +227,8 @@ public final class SharedValueObservation { /// fresh value. /// - returns: A DatabaseCancellable that can stop the observation. public func start( - onError: @escaping (any Error) -> Void, - onChange: @escaping (Element) -> Void) + onError: @escaping @Sendable (any Error) -> Void, + onChange: @escaping @Sendable (Element) -> Void) -> AnyDatabaseCancellable { synchronized { diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 85da4780a..90b26842d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -4,7 +4,7 @@ import Combine import Dispatch import Foundation -public struct ValueObservation { +public struct ValueObservation: Sendable { var events = ValueObservationEvents() /// A boolean value indicating whether the observation requires write access @@ -30,10 +30,10 @@ public struct ValueObservation { /// The reducer is created when observation starts, and is triggered upon /// each database change. - var makeReducer: () -> Reducer + var makeReducer: @Sendable () -> Reducer /// Returns a ValueObservation with a transformed reducer. - func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { + func mapReducer(_ transform: @escaping @Sendable (Reducer) -> R) -> ValueObservation { let makeReducer = self.makeReducer return ValueObservation( events: events, @@ -44,7 +44,7 @@ public struct ValueObservation { } /// Configures the tracked region -enum ValueObservationTrackingMode { +enum ValueObservationTrackingMode: Sendable { /// The tracked region is constant and explicit. /// /// Use case: @@ -73,17 +73,17 @@ enum ValueObservationTrackingMode { case nonConstantRegionRecordedFromSelection } -struct ValueObservationEvents: Refinable { - var willStart: (() -> Void)? - var willTrackRegion: ((DatabaseRegion) -> Void)? - var databaseDidChange: (() -> Void)? - var didFail: ((any Error) -> Void)? - var didCancel: (() -> Void)? +struct ValueObservationEvents: Sendable, Refinable { + var willStart: (@Sendable () -> Void)? + var willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? + var databaseDidChange: (@Sendable () -> Void)? + var didFail: (@Sendable (any Error) -> Void)? + var didCancel: (@Sendable () -> Void)? } -typealias ValueObservationStart = ( - _ onError: @escaping (any Error) -> Void, - _ onChange: @escaping (T) -> Void) +typealias ValueObservationStart = @Sendable ( + _ onError: @escaping @Sendable (any Error) -> Void, + _ onChange: @escaping @Sendable (T) -> Void) -> AnyDatabaseCancellable extension ValueObservation: Refinable { @@ -138,8 +138,8 @@ extension ValueObservation: Refinable { public func start( in reader: some DatabaseReader, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), - onError: @escaping (any Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + onError: @escaping @Sendable (any Error) -> Void, + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { @@ -175,13 +175,13 @@ extension ValueObservation: Refinable { /// - returns: A `ValueObservation` that performs the specified closures /// when ValueObservation events occur. public func handleEvents( - willStart: (() -> Void)? = nil, - willFetch: (() -> Void)? = nil, - willTrackRegion: ((DatabaseRegion) -> Void)? = nil, - databaseDidChange: (() -> Void)? = nil, - didReceiveValue: ((Reducer.Value) -> Void)? = nil, - didFail: ((any Error) -> Void)? = nil, - didCancel: (() -> Void)? = nil) + willStart: (@Sendable () -> Void)? = nil, + willFetch: (@Sendable () -> Void)? = nil, + willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? = nil, + databaseDidChange: (@Sendable () -> Void)? = nil, + didReceiveValue: (@Sendable (Reducer.Value) -> Void)? = nil, + didFail: (@Sendable (any Error) -> Void)? = nil, + didCancel: (@Sendable () -> Void)? = nil) -> ValueObservation> { self @@ -231,33 +231,25 @@ extension ValueObservation: Refinable { /// used to log messages to other destinations. public func print( _ prefix: String = "", - to stream: (any TextOutputStream)? = nil) + to stream: (any TextOutputStream & Sendable)? = nil) -> ValueObservation> { - let lock = NSLock() let prefix = prefix.isEmpty ? "" : "\(prefix): " - var stream = stream ?? PrintOutputStream() + let stream = LockedTextOutputStream(stream: stream ?? PrintOutputStream()) return handleEvents( willStart: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)start") }, willFetch: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)fetch") }, willTrackRegion: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)tracked region: \($0)") }, databaseDidChange: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)database did change") }, didReceiveValue: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)value: \($0)") }, didFail: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)failure: \($0)") }, didCancel: { - lock.lock(); defer { lock.unlock() } stream.write("\(prefix)cancel") }) } @@ -472,7 +464,7 @@ extension DatabasePublishers { } } - private class ValueSubscription: Subscription + private class ValueSubscription: Subscription, @unchecked Sendable where Downstream.Failure == any Error { private struct WaitingForDemand { @@ -703,7 +695,7 @@ extension ValueObservation { /// /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( - _ fetch: @escaping (Database) throws -> Value) + _ fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -764,7 +756,7 @@ extension ValueObservation { public static func tracking( region: any DatabaseRegionConvertible, _ otherRegions: any DatabaseRegionConvertible..., - fetch: @escaping (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -820,7 +812,7 @@ extension ValueObservation { /// - parameter fetch: The closure that fetches the observed value. public static func tracking( regions: [any DatabaseRegionConvertible], - fetch: @escaping (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -877,7 +869,7 @@ extension ValueObservation { /// /// - parameter fetch: The closure that fetches the observed value. public static func tracking( - _ fetch: @escaping (Database) throws -> Value) + _ fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 6ca3447cf..30c11becc 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -11,17 +11,17 @@ 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. func immediateInitialValue() -> Bool - func schedule(_ action: @escaping () -> Void) + func schedule(_ action: @escaping @Sendable () -> Void) } extension ValueObservationScheduler { - func scheduleInitial(_ action: @escaping () -> Void) { + func scheduleInitial(_ action: @escaping @Sendable () -> Void) { if immediateInitialValue() { action() } else { @@ -42,7 +42,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler { public func immediateInitialValue() -> Bool { false } - public func schedule(_ action: @escaping () -> Void) { + public func schedule(_ action: @escaping @Sendable () -> Void) { queue.async(execute: action) } } @@ -86,7 +86,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler { return true } - public func schedule(_ action: @escaping () -> Void) { + public func schedule(_ action: @escaping @Sendable () -> Void) { DispatchQueue.main.async(execute: action) } } diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 183fd89ed..6420ed135 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -43,7 +43,7 @@ private struct UserDatabaseValueConvertible1 : DatabaseValueConvertible { static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UserDatabaseValueConvertible1? { preconditionFailure() } } -private class UserDatabaseValueConvertible2 : DatabaseValueConvertible { +private final class UserDatabaseValueConvertible2 : DatabaseValueConvertible { var databaseValue: DatabaseValue { preconditionFailure() } static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { preconditionFailure() } } diff --git a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift index 3daa8f55c..2093f7cff 100644 --- a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift +++ b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift @@ -39,10 +39,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { func assertTransaction_registerBefore(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws { class Witness { } + class Recorder { var commitCount = 0 } let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - var commitCount = 0 + let recorder = Recorder() weak var deallocationWitness: Witness? = nil do { let witness = Witness() @@ -51,19 +52,19 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { db.afterNextTransaction { _ in // use witness withExtendedLifetime(witness, { }) - commitCount += 1 + recorder.commitCount += 1 } } XCTAssertNotNil(deallocationWitness) - XCTAssertEqual(commitCount, 0) + XCTAssertEqual(recorder.commitCount, 0) try db.execute(sql: startSQL) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) @@ -73,20 +74,23 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { } switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)") } } } func assertTransaction_registerBetween(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws { class Witness { } + class Recorder { + var commitCount = 0 + var rollbackCount = 0 + } let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - var commitCount = 0 - var rollbackCount = 0 + let recorder = Recorder() try db.execute(sql: startSQL) weak var deallocationWitness: Witness? = nil @@ -98,25 +102,25 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { onCommit: { _ in // use witness withExtendedLifetime(witness, { }) - commitCount += 1 + recorder.commitCount += 1 }, onRollback: { _ in // use witness withExtendedLifetime(witness, { }) - rollbackCount += 1 + recorder.rollbackCount += 1 }) } XCTAssertNotNil(deallocationWitness) - XCTAssertEqual(commitCount, 0) + XCTAssertEqual(recorder.commitCount, 0) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.rollbackCount, 0, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.rollbackCount, 1, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) @@ -126,11 +130,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { } switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.rollbackCount, 0, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(recorder.rollbackCount, 1, "\(startSQL); \(endSQL)") } } } diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 7ff0f4702..ee0dcf057 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -6,40 +6,46 @@ class DatabaseConfigurationTests: GRDBTestCase { func testPrepareDatabase() throws { // prepareDatabase is called when connection opens - var connectionCount = 0 + class Recorder { + var connectionCount = 0 + } + let recorder = Recorder() var configuration = Configuration() configuration.prepareDatabase { db in - connectionCount += 1 + recorder.connectionCount += 1 } _ = try DatabaseQueue(configuration: configuration) - XCTAssertEqual(connectionCount, 1) + XCTAssertEqual(recorder.connectionCount, 1) _ = try makeDatabaseQueue(configuration: configuration) - XCTAssertEqual(connectionCount, 2) + XCTAssertEqual(recorder.connectionCount, 2) let pool = try makeDatabasePool(configuration: configuration) - XCTAssertEqual(connectionCount, 3) + XCTAssertEqual(recorder.connectionCount, 3) try pool.read { _ in } - XCTAssertEqual(connectionCount, 4) + XCTAssertEqual(recorder.connectionCount, 4) try pool.makeSnapshot().read { _ in } - XCTAssertEqual(connectionCount, 5) + XCTAssertEqual(recorder.connectionCount, 5) #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) try pool.makeSnapshotPool().read { _ in } - XCTAssertEqual(connectionCount, 6) + XCTAssertEqual(recorder.connectionCount, 6) #endif } func testPrepareDatabaseError() throws { struct TestError: Error { } - var error: TestError? + class Context { + var error: TestError? + } + let context = Context() var configuration = Configuration() configuration.prepareDatabase { db in - if let error { + if let error = context.error { throw error } } @@ -47,36 +53,36 @@ class DatabaseConfigurationTests: GRDBTestCase { // TODO: what about in-memory DatabaseQueue??? do { - error = TestError() + context.error = TestError() _ = try makeDatabaseQueue(configuration: configuration) XCTFail("Expected TestError") } catch is TestError { } do { - error = TestError() + context.error = TestError() _ = try makeDatabasePool(configuration: configuration) XCTFail("Expected TestError") } catch is TestError { } do { - error = nil + context.error = nil let pool = try makeDatabasePool(configuration: configuration) do { - error = TestError() + context.error = TestError() try pool.read { _ in } XCTFail("Expected TestError") } catch is TestError { } do { - error = TestError() + context.error = TestError() _ = try pool.makeSnapshot() XCTFail("Expected TestError") } catch is TestError { } #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) do { - error = TestError() + context.error = TestError() _ = try pool.makeSnapshotPool() XCTFail("Expected TestError") } catch is TestError { } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index e9a65cba4..b898c050d 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -122,7 +122,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() @@ -789,13 +789,16 @@ class DatabaseMigratorTests : GRDBTestCase { var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true - var witness = 1 + class Context { + var value = 1 + } + let context = Context() migrator.registerMigration("1") { db in try db.execute(sql: """ CREATE TABLE t1(id INTEGER PRIMARY KEY); INSERT INTO t1(id) VALUES (?) - """, arguments: [witness]) - witness += 1 + """, arguments: [context.value]) + context.value += 1 } let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 595c7e2d2..b95065abf 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1146,13 +1146,16 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testAsyncConcurrentReadOpensATransaction() throws { let dbPool = try makeDatabasePool() - var isInsideTransaction: Bool? = nil + class Recorder { + var isInsideTransaction: Bool? = nil + } + let recorder = Recorder() let expectation = self.expectation(description: "read") dbPool.writeWithoutTransaction { db in dbPool.asyncConcurrentRead { dbResult in do { let db = try dbResult.get() - isInsideTransaction = db.isInsideTransaction + recorder.isInsideTransaction = db.isInsideTransaction do { try db.execute(sql: "BEGIN DEFERRED TRANSACTION") XCTFail("Expected error") @@ -1165,7 +1168,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(isInsideTransaction, true) + XCTAssertEqual(recorder.isInsideTransaction, true) } func testAsyncConcurrentReadOutsideOfTransaction() throws { @@ -1188,14 +1191,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // < // } - var count: Int? = nil + class Recorder { + var count: Int? = nil + } + let recorder = Recorder() let expectation = self.expectation(description: "read") try dbPool.writeWithoutTransaction { db in dbPool.asyncConcurrentRead { dbResult in do { _ = s1.wait(timeout: .distantFuture) let db = try dbResult.get() - count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! + recorder.count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! } catch { XCTFail("Unexpected error: \(error)") } @@ -1205,14 +1211,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { s1.signal() } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 0) + XCTAssertEqual(recorder.count, 0) } func testAsyncConcurrentReadError() throws { // Necessary for this test to run as quickly as possible dbConfiguration.readonlyBusyMode = .immediateError let dbPool = try makeDatabasePool() - var readError: DatabaseError? = nil + class Recorder { + var readError: DatabaseError? = nil + } + let recorder = Recorder() let expectation = self.expectation(description: "read") try dbPool.writeWithoutTransaction { db in try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE") @@ -1224,12 +1233,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { XCTFail("Unexpected result: \(dbResult)") return } - readError = dbError + recorder.readError = dbError expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY) - XCTAssertEqual(readError!.message!, "database is locked") + XCTAssertEqual(recorder.readError!.resultCode, .SQLITE_BUSY) + XCTAssertEqual(recorder.readError!.message!, "database is locked") } } diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index df99cf9cc..e2a679a53 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -205,15 +205,19 @@ class DatabaseReaderTests : GRDBTestCase { // MARK: - AsyncRead func testAsyncRead() throws { + class Recorder { + var count: Int? + } + func test(_ dbReader: some DatabaseReader) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) - var count: Int? + let recorder = Recorder() dbReader.asyncRead { dbResult in // Make sure this block executes asynchronously semaphore.wait() do { - count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master") + recorder.count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master") } catch { XCTFail("Unexpected error: \(error)") } @@ -222,7 +226,7 @@ class DatabaseReaderTests : GRDBTestCase { semaphore.signal() waitForExpectations(timeout: 1, handler: nil) - XCTAssertNotNil(count) + XCTAssertNotNil(recorder.count) } try test(makeDatabaseQueue()) diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index bec4f9cf9..5f077c93b 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -15,12 +15,15 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: .fullDatabase) - var count = 0 + class Recorder { + var count = 0 + } + let recorder = Recorder() let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + recorder.count += 1 notificationExpectation.fulfill() }) @@ -37,7 +40,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 3) + XCTAssertEqual(recorder.count, 3) } } @@ -84,12 +87,15 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: request1, request2) - var count = 0 + class Recorder { + var count = 0 + } + let recorder = Recorder() let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + recorder.count += 1 notificationExpectation.fulfill() }) @@ -106,7 +112,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 3) + XCTAssertEqual(recorder.count, 3) } } @@ -126,12 +132,15 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: [request1, request2]) - var count = 0 + class Recorder { + var count = 0 + } + let recorder = Recorder() let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + recorder.count += 1 notificationExpectation.fulfill() }) @@ -148,7 +157,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 3) + XCTAssertEqual(recorder.count, 3) } } @@ -162,13 +171,16 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - var count = 0 + class Recorder { + var count = 0 + } + let recorder = Recorder() do { let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + recorder.count += 1 notificationExpectation.fulfill() }) @@ -187,7 +199,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 2) + XCTAssertEqual(recorder.count, 2) } func testDatabaseRegionExtentNextTransaction() throws { @@ -200,18 +212,21 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - var count = 0 - var cancellable: AnyDatabaseCancellable? - cancellable = observation.start( + class Recorder { + var count = 0 + var cancellable: AnyDatabaseCancellable? + } + let recorder = Recorder() + recorder.cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, - onChange: { db in - cancellable?.cancel() - count += 1 + onChange: { [weak recorder] db in + recorder?.cancellable?.cancel() + recorder?.count += 1 notificationExpectation.fulfill() }) - try withExtendedLifetime(cancellable) { + try withExtendedLifetime(recorder) { try dbQueue.write { db in try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") } @@ -221,7 +236,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 1) + XCTAssertEqual(recorder.count, 1) } } diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index df9d73119..b50aebc7f 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -114,11 +114,12 @@ class DatabaseTraceTests : GRDBTestCase { } func testTraceFromConfigurationWithDefaultOptions() throws { - var events: [String] = [] + class Recorder { var events: [String] = [] } + let recorder = Recorder() var configuration = Configuration() configuration.prepareDatabase { db in db.trace { event in - events.append("SQL: \(event)") + recorder.events.append("SQL: \(event)") } } let dbQueue = try makeDatabaseQueue(configuration: configuration) @@ -127,19 +128,20 @@ class DatabaseTraceTests : GRDBTestCase { CREATE table t(a); INSERT INTO t (a) VALUES (?) """, arguments: [1]) - XCTAssertEqual(events.suffix(2), [ + XCTAssertEqual(recorder.events.suffix(2), [ "SQL: CREATE table t(a)", "SQL: INSERT INTO t (a) VALUES (?)"]) } } func testTraceFromConfigurationWithPublicStatementArguments() throws { - var events: [String] = [] + class Recorder { var events: [String] = [] } + let recorder = Recorder() var configuration = Configuration() configuration.publicStatementArguments = true configuration.prepareDatabase { db in db.trace { event in - events.append("SQL: \(event)") + recorder.events.append("SQL: \(event)") } } let dbQueue = try makeDatabaseQueue(configuration: configuration) @@ -148,7 +150,7 @@ class DatabaseTraceTests : GRDBTestCase { CREATE table t(a); INSERT INTO t (a) VALUES (?) """, arguments: [1]) - XCTAssertEqual(events.suffix(2), [ + XCTAssertEqual(recorder.events.suffix(2), [ "SQL: CREATE table t(a)", "SQL: INSERT INTO t (a) VALUES (1)"]) } diff --git a/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift index 7cf3e8912..c3953516c 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleSubclassTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private class FetchableParent : DatabaseValueConvertible, CustomStringConvertible { +private class FetchableParent : DatabaseValueConvertible, CustomStringConvertible, @unchecked Sendable { var databaseValue: DatabaseValue { "Parent".databaseValue } class func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index ad7287b4d..e9762ebdb 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -272,16 +272,19 @@ class FTS4TableBuilderTests: GRDBTestCase { func testFTS4Compression() throws { // Based on https://github.com/groue/GRDB.swift/issues/369 - var compressCalled = false - var uncompressCalled = false + class Recorder { + var compressCalled = false + var uncompressCalled = false + } + let recorder = Recorder() dbConfiguration.prepareDatabase { db in db.add(function: DatabaseFunction("zipit", argumentCount: 1, pure: true, function: { dbValues in - compressCalled = true + recorder.compressCalled = true return dbValues[0] })) db.add(function: DatabaseFunction("unzipit", argumentCount: 1, pure: true, function: { dbValues in - uncompressCalled = true + recorder.uncompressCalled = true return dbValues[0] })) } @@ -296,12 +299,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(recorder.compressCalled) } try dbPool.read { db in _ = try Row.fetchOne(db, sql: "SELECT * FROM documents") - XCTAssertTrue(uncompressCalled) + XCTAssertTrue(recorder.uncompressCalled) } } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 9028d491f..40ac2a316 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -219,12 +219,12 @@ extension FetchRequest { /// A type-erased ValueReducer. public struct AnyValueReducer: ValueReducer { - private var __fetch: (Database) throws -> Fetched - private var __value: (Fetched) -> Value? + private var __fetch: @Sendable (Database) throws -> Fetched + private var __value: @Sendable (Fetched) -> Value? public init( - fetch: @escaping (Database) throws -> Fetched, - value: @escaping (Fetched) -> Value?) + fetch: @escaping @Sendable (Database) throws -> Fetched, + value: @escaping @Sendable (Fetched) -> Value?) { self.__fetch = fetch self.__value = value diff --git a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift index 7dfdfb171..ef5b6d5a4 100644 --- a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift @@ -50,6 +50,7 @@ extension Wrapper: SQLExpressible where RawValue: SQLExpressible { } extension Wrapper: StatementBinding where RawValue: StatementBinding { } extension Wrapper: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { } +extension FastWrapper: Sendable where RawValue: Sendable { } extension FastWrapper: SQLSelectable where RawValue: SQLSelectable { } extension FastWrapper: SQLOrderingTerm where RawValue: SQLOrderingTerm { } extension FastWrapper: SQLSpecificExpressible where RawValue: SQLSpecificExpressible { } diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 31316f5c0..4e7416cd4 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 1ce98c182..9f9d784e8 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)") } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 43e649f46..866bb9a75 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)") } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 8c5c1f036..ffe2d3961 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)") } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 677772281..94a54d146 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( creationDate TEXT NOT NULL, diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index f8b8c8e10..885cee2a1 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE citizenships ( personName TEXT NOT NULL, diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 8582a5e48..9330925eb 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -14,7 +14,7 @@ private class Item : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE items ( name TEXT, diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index eb9023cf2..a1e4c9b76 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 69664f729..dd5c772f9 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -12,7 +12,7 @@ class Pet : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE pets ( UUID TEXT NOT NULL PRIMARY KEY, diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index e1444cdf3..af701890e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -11,7 +11,7 @@ class Email : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE emails ( email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE, diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index fc3d8dc3f..4942773ec 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 0ce7021e0..74a5b092c 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -13,7 +13,7 @@ class BadlyMangledStuff : Record { super.init() } - static func setup(inDatabase db: Database) throws { + @Sendable static func setup(inDatabase db: Database) throws { try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)") } diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index a6a0aa7e4..76c2b42ff 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -23,12 +23,15 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value: Int? + class Recorder { + var value: Int? + } + let recorder = Recorder() let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { recorder.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(recorder.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -36,12 +39,15 @@ class SharedValueObservationTests: GRDBTestCase { } do { - var value: Int? + class Recorder { + var value: Int? + } + let recorder = Recorder() let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { recorder.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(recorder.value, 0) XCTAssertEqual(log.flush(), []) cancellable.cancel() @@ -75,21 +81,24 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value1: Int? - var value2: Int? + class Recorder { + var value1: Int? + var value2: Int? + } + let recorder = Recorder() let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value1 = value + recorder.value1 = value _ = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value2 = value + recorder.value2 = value }) }) - XCTAssertEqual(value1, 0) - XCTAssertEqual(value2, 0) + XCTAssertEqual(recorder.value1, 0) + XCTAssertEqual(recorder.value2, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable1.cancel() @@ -159,12 +168,15 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value: Int? + class Recorder { + var value: Int? + } + let recorder = Recorder() let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { recorder.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(recorder.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -172,12 +184,15 @@ class SharedValueObservationTests: GRDBTestCase { } do { - var value: Int? + class Recorder { + var value: Int? + } + let recorder = Recorder() let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { recorder.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(recorder.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -210,21 +225,24 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in - var value1: Int? - var value2: Int? + class Context { + var value1: Int? + var value2: Int? + } + let context = Context() let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value1 = value + context.value1 = value _ = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value2 = value + context.value2 = value }) }) - XCTAssertEqual(value1, 0) - XCTAssertEqual(value2, 0) + XCTAssertEqual(context.value1, 0) + XCTAssertEqual(context.value2, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable1.cancel() @@ -256,41 +274,46 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated try withExtendedLifetime(sharedObservation) { sharedObservation in + class Context { + var values1: [Int] = [] + var values2: [Int] = [] + var values3: [Int] = [] + } + let context = Context() + // --- Start observation 1 - var values1: [Int] = [] let exp1 = expectation(description: "") exp1.expectedFulfillmentCount = 2 exp1.assertForOverFulfill = false let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { - values1.append($0) + context.values1.append($0) exp1.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp1], timeout: 1) - XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(context.values1, [0, 1]) XCTAssertEqual(log.flush(), [ "start", "fetch", "tracked region: player(*)", "value: 0", "database did change", "fetch", "value: 1"]) // --- Start observation 2 - var values2: [Int] = [] let exp2 = expectation(description: "") exp2.expectedFulfillmentCount = 2 exp2.assertForOverFulfill = false let cancellable2 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { - values2.append($0) + context.values2.append($0) exp2.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp2], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(context.values1, [0, 1, 2]) + XCTAssertEqual(context.values2, [1, 2]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) // --- Stop observation 1 @@ -298,22 +321,21 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) // --- Start observation 3 - var values3: [Int] = [] let exp3 = expectation(description: "") exp3.expectedFulfillmentCount = 2 exp3.assertForOverFulfill = false let cancellable3 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { - values3.append($0) + context.values3.append($0) exp3.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp3], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2, 3]) - XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(context.values1, [0, 1, 2]) + XCTAssertEqual(context.values2, [1, 2, 3]) + XCTAssertEqual(context.values3, [2, 3]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) // --- Stop observation 2 @@ -338,24 +360,30 @@ class SharedValueObservationTests: GRDBTestCase { } } + class Context { + var sharedObservation: SharedValueObservation? + init(dbQueue: DatabaseQueue, log: Log) { + sharedObservation = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .async(onQueue: .main), + extent: .observationLifetime) + } + } let log = Log() - var sharedObservation: SharedValueObservation? = ValueObservation - .tracking(Table("player").fetchCount) - .print(to: log) - .shared( - in: dbQueue, - scheduling: .async(onQueue: .main), - extent: .observationLifetime) + let context = Context(dbQueue: dbQueue, log: log) XCTAssertEqual(log.flush(), []) // --- let exp = expectation(description: "") exp.expectedFulfillmentCount = 3 - let cancellable = sharedObservation!.start( + let cancellable = context.sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value in + onChange: { [weak context] value in // Early release - sharedObservation = nil + context?.sharedObservation = nil switch value { case 0: @@ -435,41 +463,46 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated try withExtendedLifetime(sharedObservation) { sharedObservation in + class Context { + var values1: [Int] = [] + var values2: [Int] = [] + var values3: [Int] = [] + } + let context = Context() + // --- Start observation 1 - var values1: [Int] = [] let exp1 = expectation(description: "") exp1.expectedFulfillmentCount = 2 exp1.assertForOverFulfill = false let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { - values1.append($0) + context.values1.append($0) exp1.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp1], timeout: 1) - XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(context.values1, [0, 1]) XCTAssertEqual(log.flush(), [ "start", "fetch", "tracked region: player(*)", "value: 0", "database did change", "fetch", "value: 1"]) // --- Start observation 2 - var values2: [Int] = [] let exp2 = expectation(description: "") exp2.expectedFulfillmentCount = 2 exp2.assertForOverFulfill = false let cancellable2 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { - values2.append($0) + context.values2.append($0) exp2.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp2], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(context.values1, [0, 1, 2]) + XCTAssertEqual(context.values2, [1, 2]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) // --- Stop observation 1 @@ -477,22 +510,21 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) // --- Start observation 3 - var values3: [Int] = [] let exp3 = expectation(description: "") exp3.expectedFulfillmentCount = 2 exp3.assertForOverFulfill = false let cancellable3 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { - values3.append($0) + context.values3.append($0) exp3.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp3], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2, 3]) - XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(context.values1, [0, 1, 2]) + XCTAssertEqual(context.values2, [1, 2, 3]) + XCTAssertEqual(context.values3, [2, 3]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) // --- Stop observation 2 @@ -522,11 +554,15 @@ class SharedValueObservationTests: GRDBTestCase { } } + class Context { + var fetchError: (any Error)? = nil + } + let context = Context() let log = Log() - var fetchError: (any Error)? = nil + let publisher = ValueObservation .tracking { db -> Int in - if let error = fetchError { throw error } + if let error = context.fetchError { throw error } return try Table("player").fetchCount(db) } .print(to: log) @@ -540,7 +576,7 @@ class SharedValueObservationTests: GRDBTestCase { try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0) try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0) - fetchError = TestError() + context.fetchError = TestError() try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") } @@ -557,7 +593,7 @@ class SharedValueObservationTests: GRDBTestCase { } do { - fetchError = nil + context.fetchError = nil let recorder = publisher.record() if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") } XCTAssertEqual(log.flush(), []) @@ -578,11 +614,15 @@ class SharedValueObservationTests: GRDBTestCase { } } + class Context { + var fetchError: (any Error)? = nil + } + let context = Context() let log = Log() - var fetchError: (any Error)? = nil + let publisher = ValueObservation .tracking { db -> Int in - if let error = fetchError { throw error } + if let error = context.fetchError { throw error } return try Table("player").fetchCount(db) } .print(to: log) @@ -596,7 +636,7 @@ class SharedValueObservationTests: GRDBTestCase { try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0) try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0) - fetchError = TestError() + context.fetchError = TestError() try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") } @@ -613,7 +653,7 @@ class SharedValueObservationTests: GRDBTestCase { } do { - fetchError = nil + context.fetchError = nil let recorder = publisher.record() try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 1"]) diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift index 5f2707223..44cc2727f 100644 --- a/Tests/GRDBTests/TransactionDateTests.swift +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -3,14 +3,20 @@ import GRDB class TransactionDateTests: GRDBTestCase { func testTransactionDateOutsideOfTransaction() throws { - let dates = [ - Date.distantPast, - Date(), - Date.distantFuture, - ] - var dateIterator = dates.makeIterator() + class Context { + static let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator: [Date].Iterator + init() { + dateIterator = Self.dates.makeIterator() + } + } + let context = Context() dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + context.dateIterator.next()! } var collectedDates: [Date] = [] @@ -19,18 +25,24 @@ class TransactionDateTests: GRDBTestCase { try collectedDates.append(db.transactionDate) try collectedDates.append(db.transactionDate) } - XCTAssertEqual(collectedDates, dates) + XCTAssertEqual(collectedDates, Context.dates) } func testTransactionDateInsideTransaction_commit() throws { - let dates = [ - Date.distantPast, - Date(), - Date.distantFuture, - ] - var dateIterator = dates.makeIterator() + class Context { + static let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator: [Date].Iterator + init() { + dateIterator = Self.dates.makeIterator() + } + } + let context = Context() dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + context.dateIterator.next()! } var collectedDates: [Date] = [] @@ -42,18 +54,29 @@ class TransactionDateTests: GRDBTestCase { try db.execute(sql: "COMMIT") try collectedDates.append(db.transactionDate) } - XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + XCTAssertEqual(collectedDates, [ + Context.dates[0], + Context.dates[1], + Context.dates[1], + Context.dates[2], + ]) } func testTransactionDateInsideTransaction_rollback() throws { - let dates = [ - Date.distantPast, - Date(), - Date.distantFuture, - ] - var dateIterator = dates.makeIterator() + class Context { + static let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator: [Date].Iterator + init() { + dateIterator = Self.dates.makeIterator() + } + } + let context = Context() dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + context.dateIterator.next()! } var collectedDates: [Date] = [] @@ -65,18 +88,29 @@ class TransactionDateTests: GRDBTestCase { try db.execute(sql: "ROLLBACK") try collectedDates.append(db.transactionDate) } - XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + XCTAssertEqual(collectedDates, [ + Context.dates[0], + Context.dates[1], + Context.dates[1], + Context.dates[2], + ]) } func testTransactionDateInsideTransaction_rollbackingError() throws { - let dates = [ - Date.distantPast, - Date(), - Date.distantFuture, - ] - var dateIterator = dates.makeIterator() + class Context { + static let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator: [Date].Iterator + init() { + dateIterator = Self.dates.makeIterator() + } + } + let context = Context() dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + context.dateIterator.next()! } var collectedDates: [Date] = [] @@ -92,7 +126,12 @@ class TransactionDateTests: GRDBTestCase { """) try collectedDates.append(db.transactionDate) } - XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + XCTAssertEqual(collectedDates, [ + Context.dates[0], + Context.dates[1], + Context.dates[1], + Context.dates[2], + ]) } func test_TimestampedRecord_default_willInsert() throws { @@ -107,8 +146,11 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + class Context { + var currentDate = Date.distantPast + } + let context = Context() + dbConfiguration.transactionClock = .custom { _ in context.currentDate } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -119,7 +161,7 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast + context.currentDate = Date.distantPast try dbQueue.write { db in do { var player = Player(name: "Arthur") @@ -152,8 +194,11 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + class Context { + var currentDate = Date.distantPast + } + let context = Context() + dbConfiguration.transactionClock = .custom { _ in context.currentDate } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -164,14 +209,14 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast + context.currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur") try player.insert(db) } let newTransactionDate = Date() - currentDate = newTransactionDate + context.currentDate = newTransactionDate try dbQueue.write { db in var player = try Player.find(db, key: 1) @@ -198,8 +243,11 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + class Context { + var currentDate = Date.distantPast + } + let context = Context() + dbConfiguration.transactionClock = .custom { _ in context.currentDate } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -210,14 +258,14 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast + context.currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur") try player.insert(db) } let newTransactionDate = Date() - currentDate = newTransactionDate + context.currentDate = newTransactionDate try dbQueue.write { db in var player = try Player.find(db, key: 1) @@ -251,8 +299,11 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + class Context { + var currentDate = Date.distantPast + } + let context = Context() + dbConfiguration.transactionClock = .custom { _ in context.currentDate } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -267,7 +318,7 @@ class TransactionDateTests: GRDBTestCase { } let newTransactionDate = Date() - currentDate = newTransactionDate + context.currentDate = newTransactionDate try dbQueue.write { db in var player = try Player.find(db, key: 1) try player.touch(db) @@ -303,8 +354,11 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + class Context { + var currentDate = Date.distantPast + } + let context = Context() + dbConfiguration.transactionClock = .custom { _ in context.currentDate } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -315,7 +369,7 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast + context.currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur", isInserted: false) try player.insert(db) @@ -354,8 +408,11 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + class Context { + var currentDate = Date.distantPast + } + let context = Context() + dbConfiguration.transactionClock = .custom { _ in context.currentDate } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -366,7 +423,7 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast + context.currentDate = Date.distantPast try dbQueue.write { db in let player = Player(name: "Arthur") try player.insert(db) diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 51f57f5b6..1da1fad3e 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -410,11 +410,14 @@ class ValueObservationPrintTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + class Context { + var needsChange = true + } + let context = Context() let observation = ValueObservation .trackingConstantRegion { db -> Int? in - if needsChange { - needsChange = false + if context.needsChange { + context.needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO player DEFAULT VALUES; @@ -461,11 +464,14 @@ class ValueObservationPrintTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + class Context { + var needsChange = true + } + let context = Context() let observation = ValueObservation .trackingConstantRegion { db -> Int? in - if needsChange { - needsChange = false + if context.needsChange { + context.needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO player DEFAULT VALUES; diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 90bd8beb8..690ace2e3 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -130,24 +130,27 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { """) } - var results: [Int] = [] let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - var regions: [DatabaseRegion] = [] + class Recorder { + var regions: [DatabaseRegion] = [] + var results: [Int] = [] + } + let recorder = Recorder() let observation = ValueObservation .tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - .handleEvents(willTrackRegion: { regions.append($0) }) + .handleEvents(willTrackRegion: { recorder.regions.append($0) }) let observer = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) + recorder.results.append(count) notificationExpectation.fulfill() }) @@ -162,9 +165,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) + XCTAssertEqual(recorder.results, [0, 1, 2, 3]) - XCTAssertEqual(regions.map(\.description), [ + XCTAssertEqual(recorder.regions.map(\.description), [ "a(value),source(name)", "b(value),source(name)"]) } @@ -181,25 +184,28 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { """) } - var results: [Int] = [] let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - var regions: [DatabaseRegion] = [] + class Recorder { + var regions: [DatabaseRegion] = [] + var results: [Int] = [] + } + let recorder = Recorder() let observation = ValueObservation .tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - .handleEvents(willTrackRegion: { regions.append($0) }) + .handleEvents(willTrackRegion: { recorder.regions.append($0) }) let observer = observation.start( in: dbQueue, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) + recorder.results.append(count) notificationExpectation.fulfill() }) @@ -214,9 +220,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) + XCTAssertEqual(recorder.results, [0, 1, 2, 3]) - XCTAssertEqual(regions.map(\.description), [ + XCTAssertEqual(recorder.regions.map(\.description), [ "a(value),source(name)", "b(value),source(name)"]) } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index fe3a3a1cd..c0ca563cb 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -5,19 +5,22 @@ import Dispatch class ValueObservationTests: GRDBTestCase { func testImmediateError() throws { struct TestError: Error { } + class Recorder { + var error: TestError? + } func test(_ dbWriter: some DatabaseWriter) throws { // Create an observation let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() } // Start observation - var error: TestError? + let recorder = Recorder() _ = observation.start( in: dbWriter, scheduling: .immediate, - onError: { error = $0 as? TestError }, + onError: { recorder.error = $0 as? TestError }, onChange: { _ in }) - XCTAssertNotNil(error) + XCTAssertNotNil(recorder.error) } try test(makeDatabaseQueue()) @@ -26,7 +29,11 @@ class ValueObservationTests: GRDBTestCase { func testErrorCompletesTheObservation() throws { struct TestError: Error { } - + class Context { + var nextError: (any Error)? = nil // If not null, observation throws an error + var errorCaught = false + } + func test(_ dbWriter: some DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -37,25 +44,24 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 4 notificationExpectation.isInverted = true - var nextError: (any Error)? = nil // If not null, observation throws an error + let context = Context() let observation = ValueObservation.trackingConstantRegion { _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") - if let error = nextError { + if let error = context.nextError { throw error } } // Start observation - var errorCaught = false let cancellable = observation.start( in: dbWriter, onError: { _ in - errorCaught = true + context.errorCaught = true notificationExpectation.fulfill() }, onChange: { - XCTAssertFalse(errorCaught) - nextError = TestError() + XCTAssertFalse(context.errorCaught) + context.nextError = TestError() notificationExpectation.fulfill() // Trigger another change try! dbWriter.writeWithoutTransaction { db in @@ -65,7 +71,7 @@ class ValueObservationTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertTrue(errorCaught) + XCTAssertTrue(context.errorCaught) } } @@ -92,12 +98,15 @@ class ValueObservationTests: GRDBTestCase { // Test that view v is not included in the observed region. // This optimization helps observation of views that feed from a // single table. - var region: DatabaseRegion? + class Recorder { + var region: DatabaseRegion? + } + let recorder = Recorder() let expectation = self.expectation(description: "") let observation = ValueObservation .trackingConstantRegion(request.fetchAll) .handleEvents(willTrackRegion: { - region = $0 + recorder.region = $0 expectation.fulfill() }) let observer = observation.start( @@ -106,7 +115,7 @@ class ValueObservationTests: GRDBTestCase { onChange: { _ in }) withExtendedLifetime(observer) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(region!.description, "t(id,name)") // view is NOT tracked + XCTAssertEqual(recorder.region!.description, "t(id,name)") // view is NOT tracked } } @@ -125,12 +134,15 @@ class ValueObservationTests: GRDBTestCase { // Test that no pragma table is included in the observed region. // This optimization helps observation that feed from a single table. - var region: DatabaseRegion? + class Recorder { + var region: DatabaseRegion? + } + let recorder = Recorder() let expectation = self.expectation(description: "") let observation = ValueObservation .trackingConstantRegion(request.fetchAll) .handleEvents(willTrackRegion: { - region = $0 + recorder.region = $0 expectation.fulfill() }) let observer = observation.start( @@ -139,7 +151,7 @@ class ValueObservationTests: GRDBTestCase { onChange: { _ in }) withExtendedLifetime(observer) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(region!.description, "t(id,name)[1]") // pragma_table_xinfo is NOT tracked + XCTAssertEqual(recorder.region!.description, "t(id,name)[1]") // pragma_table_xinfo is NOT tracked } } @@ -325,10 +337,14 @@ class ValueObservationTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + class Context { + var needsChange = true + var observedCounts: [Int] = [] + } + let context = Context() let observation = ValueObservation.trackingConstantRegion { db -> Int in - if needsChange { - needsChange = false + if context.needsChange { + context.needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO t DEFAULT VALUES; @@ -341,18 +357,17 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] let cancellable = observation.start( in: dbPool, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + context.observedCounts.append(count) expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0]) + XCTAssertEqual(context.observedCounts, [0, 0]) } } @@ -365,10 +380,14 @@ class ValueObservationTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + class Context { + var needsChange = true + var observedCounts: [Int] = [] + } + let context = Context() let observation = ValueObservation.trackingConstantRegion { db -> Int in - if needsChange { - needsChange = false + if context.needsChange { + context.needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO t DEFAULT VALUES; @@ -381,18 +400,17 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] let cancellable = observation.start( in: dbPool, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + context.observedCounts.append(count) expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0]) + XCTAssertEqual(context.observedCounts, [0, 0]) } } @@ -405,10 +423,14 @@ class ValueObservationTests: GRDBTestCase { // Allow pool to perform a single initial fetch, because between // its first read access, and its write access that installs the // transaction observer, no write did happen. - var needsChange = true + class Context { + var needsChange = true + var observedCounts: [Int] = [] + } + let context = Context() let observation = ValueObservation.trackingConstantRegion { db -> Int in - if needsChange { - needsChange = false + if context.needsChange { + context.needsChange = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { try! dbPool.write { db in try db.execute(sql: """ @@ -431,18 +453,17 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count - var observedCounts: [Int] = [] let cancellable = observation.start( in: dbPool, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + context.observedCounts.append(count) expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, expectedCounts) + XCTAssertEqual(context.observedCounts, expectedCounts) } } @@ -455,10 +476,14 @@ class ValueObservationTests: GRDBTestCase { // Allow pool to perform a single initial fetch, because between // its first read access, and its write access that installs the // transaction observer, no write did happen. - var needsChange = true + class Context { + var needsChange = true + var observedCounts: [Int] = [] + } + let context = Context() let observation = ValueObservation.trackingConstantRegion { db -> Int in - if needsChange { - needsChange = false + if context.needsChange { + context.needsChange = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { try! dbPool.write { db in try db.execute(sql: """ @@ -481,18 +506,17 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count - var observedCounts: [Int] = [] let cancellable = observation.start( in: dbPool, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + context.observedCounts.append(count) expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, expectedCounts) + XCTAssertEqual(context.observedCounts, expectedCounts) } } @@ -531,7 +555,11 @@ class ValueObservationTests: GRDBTestCase { try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } // Track reducer process - var changesCount = 0 + class Context { + var changesCount = 0 + var cancellable: (any DatabaseCancellable)? + } + let context = Context() let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 @@ -542,14 +570,14 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and deallocate cancellable after second change - var cancellable: (any DatabaseCancellable)? - cancellable = observation.start( + context.cancellable = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - changesCount += 1 - if changesCount == 2 { - cancellable = nil + onChange: { [weak context] _ in + guard let context else { return } + context.changesCount += 1 + if context.changesCount == 2 { + context.cancellable = nil } notificationExpectation.fulfill() }) @@ -564,11 +592,8 @@ class ValueObservationTests: GRDBTestCase { try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } - // Avoid "Variable 'cancellable' was written to, but never read" warning - _ = cancellable - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(changesCount, 2) + XCTAssertEqual(context.changesCount, 2) } func testCancellableExplicitCancellation() throws { @@ -577,7 +602,11 @@ class ValueObservationTests: GRDBTestCase { try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } // Track reducer process - var changesCount = 0 + class Context { + var changesCount = 0 + var cancellable: (any DatabaseCancellable)? + } + let context = Context() let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 @@ -588,35 +617,38 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and cancel cancellable after second change - var cancellable: (any DatabaseCancellable)! - cancellable = observation.start( + context.cancellable = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - changesCount += 1 - if changesCount == 2 { - cancellable.cancel() + onChange: { [weak context] _ in + guard let context else { return } + context.changesCount += 1 + if context.changesCount == 2 { + context.cancellable?.cancel() } notificationExpectation.fulfill() }) - try withExtendedLifetime(cancellable) { - // notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - // not notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(changesCount, 2) + // notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } + + // not notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(context.changesCount, 2) } func testCancellableInvalidation1() throws { + class Context { + var shouldStopObservation = false + var cancellable: (any DatabaseCancellable)? = nil + } + // Test that observation stops when cancellable is deallocated func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -626,22 +658,20 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 do { - var cancellable: (any DatabaseCancellable)? = nil - _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning - var shouldStopObservation = false + let context = Context() let observation = ValueObservation( trackingMode: .nonConstantRegionRecordedFromSelection, makeReducer: { AnyValueReducer( fetch: { _ in - if shouldStopObservation { - cancellable = nil /* deallocation */ + if context.shouldStopObservation { + context.cancellable = nil /* deallocation */ } - shouldStopObservation = true + context.shouldStopObservation = true }, value: { _ in () }) }) - cancellable = observation.start( + context.cancellable = observation.start( in: dbWriter, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, @@ -661,6 +691,11 @@ class ValueObservationTests: GRDBTestCase { } func testCancellableInvalidation2() throws { + class Context { + var shouldStopObservation = false + var cancellable: (any DatabaseCancellable)? = nil + } + // Test that observation stops when cancellable is deallocated func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -670,23 +705,21 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 do { - var cancellable: (any DatabaseCancellable)? = nil - _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning - var shouldStopObservation = false + let context = Context() let observation = ValueObservation( trackingMode: .nonConstantRegionRecordedFromSelection, makeReducer: { AnyValueReducer( fetch: { _ in }, value: { _ in - if shouldStopObservation { - cancellable = nil /* deallocation right before notification */ + if context.shouldStopObservation { + context.cancellable = nil /* deallocation right before notification */ } - shouldStopObservation = true + context.shouldStopObservation = true return () }) }) - cancellable = observation.start( + context.cancellable = observation.start( in: dbWriter, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") },