diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e6019cd72..85d1ab951 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -721,6 +721,13 @@ extension DatabasePool: DatabaseWriter { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> 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 { @@ -731,6 +738,27 @@ extension DatabasePool: DatabaseWriter { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + 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 updates(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b6cf6a5b2..3c34be6a8 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -362,11 +362,25 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> 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: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { writer.async { updates(.success($0)) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index e92334047..a1d18fbe6 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -26,14 +26,14 @@ import Dispatch /// - ``writePublisher(receiveOn:updates:)`` /// - ``writePublisher(receiveOn:updates:thenRead:)`` /// - ``writeWithoutTransaction(_:)-4qh1w`` -/// - ``writeWithoutTransaction(_:)-tckw`` +/// - ``writeWithoutTransaction(_:)-4kzng`` /// - ``asyncWrite(_:completion:)`` /// - ``asyncWriteWithoutTransaction(_:)`` /// /// ### Exclusive Access to the Database /// /// - ``barrierWriteWithoutTransaction(_:)-280j1`` -/// - ``barrierWriteWithoutTransaction(_:)-7u4xw`` +/// - ``barrierWriteWithoutTransaction(_:)-6py5x`` /// - ``asyncBarrierWriteWithoutTransaction(_:)`` /// /// ### Reading from the Latest Committed Database State @@ -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: @Sendable @escaping (Database) throws -> T + ) async throws -> 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: @Sendable @escaping (Database) throws -> T) + async throws -> T + /// Schedules database operations for execution, and returns immediately. /// /// Database operations are not executed until all currently executing @@ -563,104 +641,16 @@ 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 { - try await withUnsafeThrowingContinuation { continuation in - asyncWrite(updates, 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: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncWriteWithoutTransaction { db in - do { - try continuation.resume(returning: updates(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: @Sendable @escaping (Database) throws -> T) - async throws -> T - { - try await withUnsafeThrowingContinuation { continuation in - asyncBarrierWriteWithoutTransaction { dbResult in - continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } }) + public func write( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writeWithoutTransaction { db in + var result: T? + try db.inTransaction { + result = try updates(db) + return .commit } + return result! } } @@ -951,11 +941,25 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.writeWithoutTransaction(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> 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: @Sendable @escaping (Database) throws -> T) + async throws -> T { + try await base.barrierWriteWithoutTransaction(updates) + } + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { base.asyncBarrierWriteWithoutTransaction(updates) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index faa7b1af1..fed985b56 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -384,7 +384,7 @@ extension CancellableDatabaseAccess: DatabaseCancellable { /// Wraps a full database access with cancellation support. When this /// method returns, the database is NOT cancelled. - func inDatabase(_ db: Database, _ work: () throws -> sending Value) throws -> sending Value { + func inDatabase(_ db: Database, execute work: () throws -> Value) throws -> Value { try withLock { state in switch state { case .connected, .expired: diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 581f7d307..181263764 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -427,4 +427,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()) + } }