diff --git a/GRDB/Core/Concurrency/DatabasePool.swift b/GRDB/Core/Concurrency/DatabasePool.swift index 95a8cb694..377229783 100644 --- a/GRDB/Core/Concurrency/DatabasePool.swift +++ b/GRDB/Core/Concurrency/DatabasePool.swift @@ -751,6 +751,13 @@ extension DatabasePool: DatabaseWriter { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + try await writer.execute(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { guard let readerPool else { @@ -761,6 +768,33 @@ extension DatabasePool: DatabaseWriter { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + // Prevent compiler warning with an unchecked Sendable wrapper, due + // to . + // FIXME: remove the closure copy when is fixed. + let updates: (Database) throws -> T = updates + let updatesWrapper = UncheckedSendableWrapper(value: updates) + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + asyncBarrierWriteWithoutTransaction { dbResult in + do { + try dbAccess.checkCancellation() + let db = try dbResult.get() + let result = try dbAccess.inDatabase(db) { + try updatesWrapper.value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncBarrierWriteWithoutTransaction( _ updates: sending @escaping (Result) -> Void ) { diff --git a/GRDB/Core/Concurrency/DatabaseQueue.swift b/GRDB/Core/Concurrency/DatabaseQueue.swift index 49625d8be..79dc568dc 100644 --- a/GRDB/Core/Concurrency/DatabaseQueue.swift +++ b/GRDB/Core/Concurrency/DatabaseQueue.swift @@ -380,11 +380,25 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + try await writer.execute(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + try await writer.execute(updates) + } + public func asyncBarrierWriteWithoutTransaction( _ updates: sending @escaping (Result) -> Void ) { diff --git a/GRDB/Core/Concurrency/DatabaseWriter.swift b/GRDB/Core/Concurrency/DatabaseWriter.swift index a388350a1..2fe54471a 100644 --- a/GRDB/Core/Concurrency/DatabaseWriter.swift +++ b/GRDB/Core/Concurrency/DatabaseWriter.swift @@ -100,6 +100,40 @@ public protocol DatabaseWriter: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.writeWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func writeWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T + /// Executes database operations, and returns their result after they have /// finished executing. /// @@ -140,6 +174,50 @@ public protocol DatabaseWriter: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// Database operations are not executed until all currently executing + /// database accesses performed by the database writer finish executing + /// (both reads and writes). At that point, database operations are + /// executed. Once they finish, the database writer can proceed with other + /// database accesses. + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func barrierWriteWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T + /// Schedules database operations for execution, and returns immediately. /// /// Database operations are not executed until all currently executing @@ -572,124 +650,13 @@ extension DatabaseWriter { public func write( _ updates: sending @escaping (Database) throws -> sending T ) async throws -> sending T { - // Prevent compiler warning with an unchecked Sendable wrapper, due - // to . - // FIXME: remove the closure copy when is fixed. - let updates: (Database) throws -> T = updates - let updatesWrapper = UncheckedSendableWrapper(value: updates) - return try await withUnsafeThrowingContinuation { continuation in - asyncWrite { db in - try updatesWrapper.value(db) - } completion: { _, result in - continuation.resume(with: result) - } - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let newPlayerCount = try await writer.writeWithoutTransaction { db in - /// try Player(name: "Arthur").insert(db) - /// return try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations run in the writer dispatch queue, serialized - /// with all database updates performed by this `DatabaseWriter`. - /// - /// The ``Database`` argument to `updates` is valid only during the - /// execution of the closure. Do not store or return the database connection - /// for later use. - /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `updates` - /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. - /// - /// - 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: sending @escaping (Database) throws -> sending T - ) async throws -> sending T { - // Prevent compiler warning with an unchecked Sendable wrapper, due - // to . - // FIXME: remove the closure copy when is fixed. - let updates: (Database) throws -> T = updates - let updatesWrapper = UncheckedSendableWrapper(value: updates) - return try await withUnsafeThrowingContinuation { continuation in - asyncWriteWithoutTransaction { db in - do { - try continuation.resume(returning: updatesWrapper.value(db)) - } catch { - continuation.resume(throwing: error) - } - } - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// Database operations are not executed until all currently executing - /// database accesses performed by the database writer finish executing - /// (both reads and writes). At that point, database operations are - /// executed. Once they finish, the database writer can proceed with other - /// database accesses. - /// - /// For example: - /// - /// ```swift - /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in - /// try Player(name: "Arthur").insert(db) - /// return try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations run in the writer dispatch queue, serialized - /// with all database updates performed by this `DatabaseWriter`. - /// - /// The ``Database`` argument to `updates` is valid only during the - /// execution of the closure. Do not store or return the database connection - /// for later use. - /// - /// It is a programmer error to call this method from another database - /// access method. Doing so raises a "Database methods are not reentrant" - /// fatal error at runtime. - /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `updates` - /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. - /// - /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. - @available(iOS 13, macOS 10.15, tvOS 13, *) - public func barrierWriteWithoutTransaction( - _ updates: sending @escaping (Database) throws -> sending T) - async throws -> sending T - { - // Prevent compiler warning with an unchecked Sendable wrapper, due - // to . - // FIXME: remove the closure copy when is fixed. - let updates: (Database) throws -> T = updates - let updatesWrapper = UncheckedSendableWrapper(value: updates) - return try await withUnsafeThrowingContinuation { continuation in - asyncBarrierWriteWithoutTransaction { dbResult in - continuation.resume(with: dbResult.flatMap { db in - Result { try updatesWrapper.value(db) } - }) + try await writeWithoutTransaction { db in + var result: T? + try db.inTransaction { + result = try updates(db) + return .commit } + return result! } } @@ -988,11 +955,25 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.writeWithoutTransaction(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + try await base.writeWithoutTransaction(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try base.barrierWriteWithoutTransaction(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + try await base.barrierWriteWithoutTransaction(updates) + } + public func asyncBarrierWriteWithoutTransaction( _ updates: sending @escaping (Result) -> Void ) { diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 05f45e3f9..d13f54ea2 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -431,4 +431,337 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) } + + // MARK: - Task Cancellation + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_writeWithoutTransaction_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_write_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_write_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_write_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_write_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_barrierWriteWithoutTransaction_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } }