From d6b91eec85afa2fa012d2e2b070b68c3db693792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 13:07:49 +0200 Subject: [PATCH] [BREAKING] DatabaseReader async methods support Task cancellation --- GRDB/Core/DatabasePool.swift | 74 +++++++ GRDB/Core/DatabaseQueue.swift | 19 ++ GRDB/Core/DatabaseReader.swift | 179 +++++++++-------- GRDB/Core/DatabaseSnapshot.swift | 20 ++ GRDB/Core/DatabaseSnapshotPool.swift | 45 +++++ GRDB/Core/DatabaseWriter.swift | 14 ++ GRDB/Documentation.docc/Concurrency.md | 2 +- Tests/GRDBTests/DatabaseReaderTests.swift | 226 ++++++++++++++++++++++ 8 files changed, 486 insertions(+), 93 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 85d1ab951..b0f5c1b1a 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -351,6 +351,45 @@ extension DatabasePool: DatabaseReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + try? db.commit() // Ignore commit error + releaseReader(.reuse) + } + do { + let result = try dbAccess.inDatabase(db) { + // The block isolation comes from the DEFERRED transaction. + try db.beginTransaction(.deferred) + try db.clearSchemaCacheIfNeeded() + return try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -395,6 +434,41 @@ extension DatabasePool: DatabaseReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + releaseReader(.reuse) + } + do { + let result = try dbAccess.inDatabase(db) { + try db.clearSchemaCacheIfNeeded() + return try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 3c34be6a8..a1175feee 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -233,6 +233,17 @@ extension DatabaseQueue: DatabaseReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute { db in + try db.isolated(readOnly: true) { + try value(db) + } + } + } + public func asyncRead(_ value: @escaping (Result) -> Void) { writer.async { db in defer { @@ -254,10 +265,18 @@ extension DatabaseQueue: DatabaseReader { } } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { try writer.sync(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { writer.async { value(.success($0)) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 2295f6f03..5c52737f7 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -22,14 +22,14 @@ import Dispatch /// ### Reading from the Database /// /// - ``read(_:)-3806d`` -/// - ``read(_:)-4w6gy`` +/// - ``read(_:)-8gyof`` /// - ``readPublisher(receiveOn:value:)`` /// - ``asyncRead(_:)`` /// /// ### Unsafe Methods /// /// - ``unsafeRead(_:)-5i7tf`` -/// - ``unsafeRead(_:)-11mk0`` +/// - ``unsafeRead(_:)-4w54s`` /// - ``unsafeReentrantRead(_:)`` /// - ``asyncUnsafeRead(_:)`` /// @@ -188,6 +188,38 @@ public protocol DatabaseReader: AnyObject, Sendable { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func read(_ value: (Database) throws -> T) throws -> T + /// Executes read-only 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 count = try await reader.read { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter value: A closure which accesses the database. + /// - 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, *) + func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T + /// Schedules read-only database operations for execution, and /// returns immediately. /// @@ -254,6 +286,44 @@ public protocol DatabaseReader: AnyObject, Sendable { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func unsafeRead(_ value: (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) + /// + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. See + /// for + /// more information. + /// + /// For example: + /// + /// ```swift + /// let count = try await reader.unsafeRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. + /// + /// - parameter value: A closure which accesses the database. + /// - 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, *) + func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T + /// Schedules database operations for execution, and returns immediately. /// /// This method is "unsafe" because the database reader does nothing more @@ -428,96 +498,6 @@ extension DatabaseReader { } } -extension DatabaseReader { - // MARK: - Asynchronous Database Access - - /// Executes read-only 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 count = try await reader.read { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations are isolated in a transaction: they do not see - /// changes performed by eventual concurrent writes (even writes performed - /// by other processes). - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - parameter value: A closure which accesses the database. - /// - 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 { - try await withUnsafeThrowingContinuation { continuation in - asyncRead { result in - do { - try continuation.resume(returning: value(result.get())) - } 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) - /// - /// This method is "unsafe" because the database reader does nothing more - /// than providing a database connection. When you use this method, you - /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. See - /// for - /// more information. - /// - /// For example: - /// - /// ```swift - /// let count = try await reader.unsafeRead { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - warning: Database operations may not be wrapped in a transaction. They - /// may see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `value` - /// closure may not return the same value. - /// - warning: Attempts to write in the database may succeed. - /// - /// - parameter value: A closure which accesses the database. - /// - 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 { - try await withUnsafeThrowingContinuation { continuation in - asyncUnsafeRead { result in - do { - try continuation.resume(returning: value(result.get())) - } catch { - continuation.resume(throwing: error) - } - } - } - } -} - #if canImport(Combine) extension DatabaseReader { // MARK: - Publishing Database Values @@ -676,6 +656,13 @@ extension AnyDatabaseReader: DatabaseReader { try base.read(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.read(value) + } + public func asyncRead(_ value: @escaping (Result) -> Void) { base.asyncRead(value) } @@ -685,6 +672,13 @@ extension AnyDatabaseReader: DatabaseReader { try base.unsafeRead(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.unsafeRead(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { base.asyncUnsafeRead(value) } @@ -751,6 +745,7 @@ extension DatabaseSnapshotReader { } // There is no such thing as an unsafe access to a snapshot. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) throws -> T { try read(value) } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 197771b24..8a868a416 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -146,18 +146,38 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { // MARK: - Reading from Database + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ block: (Database) throws -> T) rethrows -> T { try reader.sync(block) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await reader.execute(value) + } + public func asyncRead(_ value: @escaping (Result) -> Void) { reader.async { value(.success($0)) } } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { try reader.sync(value) } + // There is no such thing as an unsafe access to a snapshot. + // We can't provide this as a default implementation in + // `DatabaseSnapshotReader`, because of + // . + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await read(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { reader.async { value(.success($0)) } } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 715dabf72..1fc8e788d 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -293,6 +293,40 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + releaseReader(self.poolCompletion(db)) + } + do { + let result = try dbAccess.inDatabase(db) { + try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -313,6 +347,17 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } + // There is no such thing as an unsafe access to a snapshot. + // We can't provide this as a default implementation in + // `DatabaseSnapshotReader`, because of + // . + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await read(value) + } + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync { db in diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index a1d18fbe6..c6637f241 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -905,6 +905,13 @@ extension AnyDatabaseWriter: DatabaseReader { try base.read(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.read(value) + } + public func asyncRead(_ value: @escaping (Result) -> Void) { base.asyncRead(value) } @@ -914,6 +921,13 @@ extension AnyDatabaseWriter: DatabaseReader { try base.unsafeRead(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.unsafeRead(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { base.asyncUnsafeRead(value) } diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 1b8050419..475da8262 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -99,7 +99,7 @@ try dbQueue.write { db in } ``` - See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``. + See ``DatabaseReader/read(_:)-8gyof`` and ``DatabaseWriter/write(_:)-88g7e``. Note the identical method names: `read`, `write`. The async version is only available in async Swift functions. diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 6150cd445..df74498b3 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -342,6 +342,232 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool()) +#endif + } + + // MARK: - Task Cancellation + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_read_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbReader.read { 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 dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { 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 dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_read_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { 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 dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_unsafeRead_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { 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 dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { 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 dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_unsafeRead_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { 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 dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) #endif } }