diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index dfaf1e143..1f5a00289 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -251,7 +251,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) + } } } } @@ -351,7 +353,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 @@ -395,7 +397,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 @@ -440,7 +442,7 @@ extension DatabasePool: DatabaseReader { } } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { asyncConcurrentRead(value) } @@ -481,7 +483,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. @@ -640,7 +642,9 @@ 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 @@ -731,7 +735,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 @@ -785,7 +789,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 69ec2fe16..162f357e3 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 spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -367,7 +369,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)) } } @@ -413,7 +415,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 2295f6f03..9f7dc4eab 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -214,7 +214,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. @@ -285,7 +285,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. @@ -459,7 +459,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, *) - 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 { @@ -505,7 +505,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, *) - 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 { @@ -552,7 +552,7 @@ extension DatabaseReader { @available(iOS 13, macOS 10.15, tvOS 13, *) public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping (Database) throws -> Output) + value: @escaping @Sendable (Database) throws -> Output) -> DatabasePublishers.Read { OnDemandFuture { fulfill in @@ -676,7 +676,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) } @@ -685,7 +685,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) } @@ -756,7 +756,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/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 197771b24..3c6b2b8f9 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -150,7 +150,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)) } } @@ -158,7 +158,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)) } } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index bf647bb97..fc6099bd0 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -293,7 +293,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 diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index e92334047..43f827b72 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -179,7 +179,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. /// @@ -211,7 +211,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. @@ -295,7 +295,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 { @@ -381,8 +381,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 { @@ -563,7 +563,7 @@ extension DatabaseWriter { /// would happen while establishing the database access or committing /// the transaction. @available(iOS 13, macOS 10.15, tvOS 13, *) - 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) @@ -601,7 +601,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, *) - 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 { @@ -654,7 +654,7 @@ extension DatabaseWriter { /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, *) public func barrierWriteWithoutTransaction( - _ updates: @Sendable @escaping (Database) throws -> T) + _ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -758,7 +758,7 @@ extension DatabaseWriter { @available(iOS 13, macOS 10.15, tvOS 13, *) 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 @@ -823,8 +823,8 @@ extension DatabaseWriter { @available(iOS 13, macOS 10.15, tvOS 13, *) 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 { @@ -840,7 +840,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!) } }) } } @@ -915,7 +915,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) } @@ -924,7 +924,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) } @@ -956,11 +956,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) } @@ -968,7 +968,7 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { base.spawnConcurrentRead(value) } } 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/TODO.md b/TODO.md index 470e88609..150faa90c 100644 --- a/TODO.md +++ b/TODO.md @@ -98,7 +98,7 @@ - [X] GRDB7: Remove concurrenRead and DatabaseFuture - [ ] GRDB7: Merge `_ValueReducer` into `ValueReducer` - [ ] GRDB7: Sendable conformances - - [ ] SerializedDatabase Sendable async closure + - [X] SerializedDatabase Sendable async closure - [X] OnDemandFuture Sendable async closure - [X] WALSnapshotTransaction refactor - [X] anydatabasecancellable diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 93eaaae3e..b1b3b8746 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1078,13 +1078,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testAsyncConcurrentReadOpensATransaction() throws { let dbPool = try makeDatabasePool() - var isInsideTransaction: Bool? = nil + let isInsideTransactionMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "read") dbPool.writeWithoutTransaction { db in dbPool.asyncConcurrentRead { dbResult in do { let db = try dbResult.get() - isInsideTransaction = db.isInsideTransaction + isInsideTransactionMutex.value = db.isInsideTransaction do { try db.execute(sql: "BEGIN DEFERRED TRANSACTION") XCTFail("Expected error") @@ -1097,7 +1097,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(isInsideTransaction, true) + XCTAssertEqual(isInsideTransactionMutex.value, true) } func testAsyncConcurrentReadOutsideOfTransaction() throws { @@ -1120,14 +1120,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // < // } - var count: Int? = nil + let countMutex: Mutex = Mutex(nil) 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")! + countMutex.value = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! } catch { XCTFail("Unexpected error: \(error)") } @@ -1137,14 +1137,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { s1.signal() } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 0) + XCTAssertEqual(countMutex.value, 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 + let readErrorMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "read") try dbPool.writeWithoutTransaction { db in try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE") @@ -1156,12 +1156,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { XCTFail("Unexpected result: \(dbResult)") return } - readError = dbError + readErrorMutex.value = dbError expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY) - XCTAssertEqual(readError!.message!, "database is locked") + let readError = try XCTUnwrap(readErrorMutex.value) + XCTAssertEqual(readError.resultCode, .SQLITE_BUSY) + XCTAssertEqual(readError.message, "database is locked") } } diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index f5c051730..ded6da2eb 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -237,9 +237,7 @@ class DatabasePoolTests: GRDBTestCase { let group = DispatchGroup() // The maximum number of threads we could witness - var maxThreadCount: CInt = 0 - let lock = NSLock() - + let maxThreadCountMutex: Mutex = Mutex(0) for _ in (0.. = Mutex(0) for _ in (0.. = Mutex(nil) 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") + countMutex.value = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master") } catch { XCTFail("Unexpected error: \(error)") } @@ -238,7 +238,7 @@ class DatabaseReaderTests : GRDBTestCase { semaphore.signal() waitForExpectations(timeout: 1, handler: nil) - XCTAssertNotNil(count) + XCTAssertNotNil(countMutex.value) } try test(makeDatabaseQueue())