Merge pull request #1610 from groue/dev/GRDB7-cancellable-database-access

GRDB 7: Async database accesses honor Task cancellation
This commit is contained in:
Gwendal Roué authored and GitHub committed 2024-09-01 16:30:04 +02:00
commit a02601ceae
19 files changed
+1673 -224

No files matched your search

+4
View File
@@ -88,6 +88,7 @@
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; };
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; };
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; };
563866CB2C847659004C515A /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563866CA2C847654004C515A /* AsyncSemaphore.swift */; };
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; };
563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */; };
563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; };
@@ -518,6 +519,7 @@
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = "<group>"; };
5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = "<group>"; };
5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
563866CA2C847654004C515A /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = "<group>"; };
563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = "<group>"; };
563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = "<group>"; };
@@ -1010,6 +1012,7 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
563866CA2C847654004C515A /* AsyncSemaphore.swift */,
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
563EA3E02C7B3A22001BE0D4 /* Mutex.swift */,
@@ -2115,6 +2118,7 @@
56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
563866CB2C847659004C515A /* AsyncSemaphore.swift in Sources */,
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */,
+14
View File
@@ -439,6 +439,7 @@ extension Database {
// documentation of this method for more information).
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
// Cancelled database accesses must not execute.
// Suspended databases must not execute statements that create the risk
// of `0xdead10cc` exception (see the documentation of this method for
// more information).
@@ -491,6 +492,19 @@ extension Database {
// and throws the user-provided cancelled commit error.
try observationBroker?.statementDidFail(statement)
if #available(iOS 13, macOS 10.15, tvOS 13, *) {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
if suspensionMutex.load().isCancelled {
// The only error that a user sees when a Task is cancelled
// is CancellationError.
throw CancellationError()
}
default:
break
}
}
// Throw statement failure
throw DatabaseError(
resultCode: resultCode,
+112 -26
View File
@@ -312,18 +312,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// `isRecordingSelectedRegion` is true.
var selectedRegion = DatabaseRegion()
/// Support for `checkForAbortedTransaction()`
var isInsideTransactionBlock = false
/// Support for `checkForSuspensionViolation(from:)`
let isSuspendedMutex = Mutex(false)
/// Support for `checkForSuspensionViolation(from:)`
/// This cache is never cleared: we assume journal mode never changes.
var journalModeCache: String?
// MARK: - Suspension
struct Suspension {
/// If true, the database is suspended and should not acquire any
/// write lock in order to avoid the 0xDEAD10CC exception.
var isSuspended: Bool
/// If true, the database access has been cancelled.
var isCancelled: Bool
}
/// Support for `checkForSuspensionViolation(from:)`
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
// MARK: - Transaction Date
/// Support for `checkForAbortedTransaction()`
var isInsideTransactionBlock = false
enum AutocommitState {
case off
case on
@@ -635,7 +646,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
guard code == SQLITE_OK else {
// So there remain some unfinalized prepared statement somewhere.
if let log = Self.logError {
if code == SQLITE_BUSY {
if ResultCode(rawValue: code).primaryResultCode == .SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
@@ -1149,12 +1160,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// Suspension ends with `resume()`.
func suspend() {
let needsInterrupt = isSuspendedMutex.withLock { isSuspended in
if isSuspended {
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isSuspended {
return false
}
isSuspended = true
suspension.isSuspended = true
return true
}
@@ -1179,7 +1190,37 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See suspend().
func resume() {
isSuspendedMutex.store(false)
suspensionMutex.withLock {
$0.isSuspended = false
}
}
/// Cancels the current database access. All statements but ROLLBACK
/// will throw `CancellationError`, until `uncancel()` is called.
///
/// This method can be called from any thread.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func cancel() {
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
}
suspension.isCancelled = true
return true
}
if needsInterrupt {
interrupt()
}
}
/// Undo `cancel()`.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func uncancel() {
suspensionMutex.withLock {
$0.isCancelled = false
}
}
/// Support for `checkForSuspensionViolation(from:)`
@@ -1203,15 +1244,51 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return journalMode
}
/// If the database is suspended, and executing the statement would lock the
/// database in a way that may trigger the [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report),
/// this method rollbacks the current transaction and throws `SQLITE_ABORT`.
/// Prevents a statement from running, if the database is suspended, or
/// if the current database access is cancelled by Task cancellation.
///
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
/// Transaction rollbacks are always allowed. For other statements:
///
/// - When database access is cancelled, this method
/// throws `CancellationError`.
///
/// - When database is suspensed, and if the statement would lock the
/// database in a way that may trigger the 0xDEAD10CC exception, this
/// method rollbacks the current transaction and throws `SQLITE_ABORT`.
///
/// See `cancel()`, `suspend()` and
/// ``Configuration/observesSuspensionNotifications``.
func checkForSuspensionViolation(from statement: Statement) throws {
let needsAbort = try isSuspendedMutex.withLock { isSuspended in
guard isSuspended else {
return false
// No reason for suspension should prevent rollbacks:
//
// - A rollback releases the write lock when the database
// is interrupted, when preventing 0xDEAD10CC.
//
// - A rollback properly closes a transaction that fails because
// it runs in a Task that was cancelled.
//
// Finally, a rollback must be run by GRDB, not by a direct call
// to `sqlite3_exec`, so that transaction observers are
// properly notified.
if statement.transactionEffect == .rollbackTransaction {
return
}
// How should we interrupt the statement?
enum Interrupt {
case abort // Rollback and throw SQLITE_ABORT
case cancel // Throw CancellationError
}
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
// Check for cancellation first, so that the only error that
// a user sees when a Task is cancelled is CancellationError.
if suspension.isCancelled {
return .cancel
}
guard suspension.isSuspended else {
return nil
}
if try journalMode() == "wal" && statement.isReadonly {
@@ -1222,7 +1299,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Those are not read-only:
// - INSERT ...
// - BEGIN IMMEDIATE TRANSACTION
return false
return nil
}
if statement.releasesDatabaseLock {
@@ -1231,20 +1308,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// - ROLLBACK
// - ROLLBACK TRANSACTION TO SAVEPOINT
// - RELEASE SAVEPOINT
return false
return nil
}
// Assume statement can acquire a write lock: abort.
return true
return .abort
}
if needsAbort {
switch interrupt {
case nil:
break
case .cancel:
if #available(iOS 13, macOS 10.15, tvOS 13, *) {
throw CancellationError()
} else {
// GRDB bug: cancellation is a Swift concurrency feature
fatalError("Can't cancel without support for Swift concurrency")
}
case .abort:
// Attempt at releasing an eventual lock with ROLLBACk,
// as explained in Database.suspend().
//
// Use sqlite3_exec instead of `try? rollback()` in order to avoid
// an infinite loop in checkForSuspensionViolation(from:)
_ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
try? rollback()
throw DatabaseError(
resultCode: .SQLITE_ABORT,
+102
View File
@@ -351,6 +351,45 @@ extension DatabasePool: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ 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<Database, Error>) -> 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<T>(
_ 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<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -721,6 +795,13 @@ extension DatabasePool: DatabaseWriter {
try writer.sync(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(
_ 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<T>(_ updates: (Database) throws -> T) throws -> T {
guard let readerPool else {
@@ -731,6 +812,27 @@ extension DatabasePool: DatabaseWriter {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ 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<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
+33
View File
@@ -233,6 +233,17 @@ extension DatabaseQueue: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ 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<Database, Error>) -> 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<T>(_ value: (Database) throws -> T) rethrows -> T {
try writer.sync(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -362,11 +381,25 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(
_ 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<T>(_ updates: (Database) throws -> T) throws -> T {
try writer.sync(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
+89 -92
View File
@@ -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,39 @@ public protocol DatabaseReader: AnyObject, Sendable {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func read<T>(_ 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: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func read<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
/// returns immediately.
///
@@ -254,6 +287,45 @@ public protocol DatabaseReader: AnyObject, Sendable {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func unsafeRead<T>(_ 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
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> 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: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func unsafeRead<T>(
_ 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 +500,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<T>(_ 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
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> 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<T>(_ 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 +658,13 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -685,6 +674,13 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -751,6 +747,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<T>(_ value: (Database) throws -> T) throws -> T {
try read(value)
}
+20
View File
@@ -146,18 +146,38 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
try reader.sync(block)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ 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
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await read(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
+45
View File
@@ -293,6 +293,40 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ 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<Database, Error>) -> 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
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync { db in
+124 -102
View File
@@ -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,42 @@ public protocol DatabaseWriter: DatabaseReader {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func writeWithoutTransaction<T>(_ 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: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func writeWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
///
@@ -140,6 +176,52 @@ public protocol DatabaseWriter: DatabaseReader {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func barrierWriteWithoutTransaction<T>(_ 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: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func barrierWriteWithoutTransaction<T>(
_ 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
@@ -559,108 +641,20 @@ extension DatabaseWriter {
/// for later use.
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
/// would happen while establishing the database access or committing
/// the transaction.
/// - throws: Any ``DatabaseError`` that happens while establishing the
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func write<T>(_ 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<T>(_ 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<T>(
_ 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<T>(
_ 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!
}
}
@@ -915,6 +909,13 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -924,6 +925,13 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -951,11 +959,25 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.writeWithoutTransaction(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(
_ 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<T>(_ updates: (Database) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T)
async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
+128
View File
@@ -243,6 +243,26 @@ final class SerializedDatabase {
return try block(db)
}
/// Asynchrously executes the block.
@available(iOS 13, macOS 10.15, tvOS 13, *)
func execute<T>(
_ block: @Sendable @escaping (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
self.async { db in
do {
let result = try dbAccess.inDatabase(db) {
try block(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
}
}
func interrupt() {
// Intentionally not scheduled in our serial queue
db.interrupt()
@@ -286,3 +306,111 @@ final class SerializedDatabase {
// It happens the job of SerializedDatabase is precisely to provide thread-safe
// access to `Database`.
extension SerializedDatabase: @unchecked Sendable { }
// MARK: - Task Cancellation Support
@available(iOS 13, macOS 10.15, tvOS 13, *)
enum DatabaseAccessCancellationState: @unchecked Sendable {
// @unchecked Sendable because database is only accessed from its
// dispatch queue.
case notConnected
case connected(Database)
case cancelled
case expired
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
/// Supports Task cancellation in async database accesses.
///
/// Usage:
///
/// ```swift
/// let dbAccess = CancellableDatabaseAccess()
/// return try dbAccess.withCancellableContinuation { continuation in
/// asyncDatabaseAccess { db in
/// do {
/// let result = try dbAccess.inDatabase(db) {
/// // Perform database operations
/// }
/// continuation.resume(returning: result)
/// } catch {
/// continuation.resume(throwing: error)
/// }
/// }
/// }
/// ```
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension CancellableDatabaseAccess: DatabaseCancellable {
convenience init() {
self.init(.notConnected)
}
func cancel() {
withLock { state in
switch state {
case let .connected(db):
db.cancel()
state = .cancelled
case .notConnected:
state = .cancelled
case .cancelled, .expired:
break
}
}
}
func withCancellableContinuation<Value>(
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
) async throws -> Value {
try await withTaskCancellationHandler {
try checkCancellation()
return try await withUnsafeThrowingContinuation { continuation in
fn(continuation)
}
} onCancel: {
cancel()
}
}
func checkCancellation() throws {
try withLock { state in
if case .cancelled = state {
throw CancellationError()
}
}
}
/// Wraps a full database access with cancellation support. When this
/// method returns, the database is NOT cancelled.
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
try withLock { state in
switch state {
case .connected, .expired:
fatalError("Can't use a CancellableDatabaseAccess twice")
case .notConnected:
state = .connected(db)
case .cancelled:
throw CancellationError()
}
}
return try throwingFirstError {
try work()
} finally: {
let cancelled = withLock { state in
if case .cancelled = state {
db.uncancel()
return true
} else {
state = .expired
return false
}
}
if cancelled {
throw CancellationError()
}
}
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ extension String {
}
public final class Statement {
enum TransactionEffect {
enum TransactionEffect: Equatable {
case beginTransaction
case commitTransaction
case rollbackTransaction
+3 -1
View File
@@ -99,9 +99,11 @@ 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.
The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rollbacked.
- **Combine publishers**
+7 -2
View File
@@ -142,16 +142,21 @@ try dbQueue.writeWithoutTransaction { db
}
```
Transactions can't be left opened unless the ``Configuration/allowsUnsafeTransactions`` configuration flag is set:
Make sure all transactions opened from a database access are committed or rollbacked from that same database access, because it is a programmer error to leave an opened transaction:
```swift
// fatal error: A transaction has been left opened at the end of a database access
// fatal error: A transaction has been left
// opened at the end of a database access.
try dbQueue.writeWithoutTransaction { db in
try db.execute(sql: "BEGIN TRANSACTION")
// <- no commit or rollback
}
```
In particular, since commits may throw an error, make sure you perform a rollback when a commit fails.
This restriction can be left with the ``Configuration/allowsUnsafeTransactions`` configuration flag.
It is possible to ask if a transaction is currently opened:
```swift
+4
View File
@@ -309,6 +309,7 @@
56DF0015228DDB8300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; };
56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */; };
56DF37A723D77AA0009AAA05 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF37A623D77AA0009AAA05 /* Refinable.swift */; };
56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */; };
56E4F7F92392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */; };
56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */; };
56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; };
@@ -830,6 +831,7 @@
56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = "<group>"; };
56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = "<group>"; };
56DF37A623D77AA0009AAA05 /* Refinable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = "<group>"; };
56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = "<group>"; };
@@ -1032,6 +1034,7 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */,
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
563EA3E22C7B3A3A001BE0D4 /* Mutex.swift */,
@@ -2358,6 +2361,7 @@
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */,
56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */,
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
5616B50028B5F5490052017E /* SingletonRecordTest.swift in Sources */,
56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */,
@@ -495,6 +495,8 @@
568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; };
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; };
56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; };
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
@@ -752,6 +754,7 @@
567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F61DEF283D484700AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
@@ -884,6 +887,7 @@
56419CAD24A54054004967E1 /* AssociationPrefetchingSQLTests.swift */,
56419D5824A54061004967E1 /* AssociationRowScopeSearchTests.swift */,
56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */,
56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */,
565A27CB27871FFF00659A62 /* BackupTestCase.swift */,
567B5C272AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift */,
56419CD424A54057004967E1 /* CGFloatTests.swift */,
@@ -1493,6 +1497,7 @@
56419ED724A54063004967E1 /* ColumnInfoTests.swift in Sources */,
56419D9F24A54062004967E1 /* CompilationSubClassTests.swift in Sources */,
567B5C3F2AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */,
56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */,
56419DBB24A54062004967E1 /* ValueObservationRegionRecordingTests.swift in Sources */,
56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */,
@@ -1742,6 +1747,7 @@
56419ED824A54063004967E1 /* ColumnInfoTests.swift in Sources */,
56419DA024A54062004967E1 /* CompilationSubClassTests.swift in Sources */,
567B5C402AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */,
56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */,
56419DBC24A54062004967E1 /* ValueObservationRegionRecordingTests.swift in Sources */,
56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */,
@@ -497,6 +497,8 @@
568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; };
56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; };
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
@@ -755,6 +757,7 @@
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F61DF5283D4AB100AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
@@ -888,6 +891,7 @@
56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */,
56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */,
56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */,
56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */,
565A27C827871FE500659A62 /* BackupTestCase.swift */,
568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */,
56419F6B24A5409A004967E1 /* CGFloatTests.swift */,
@@ -1499,6 +1503,7 @@
5641A02424A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */,
5641A12024A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */,
5641A04224A540A1004967E1 /* FTS5TableBuilderTests.swift in Sources */,
56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */,
5641A10624A540A1004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
5641A11A24A540A1004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5641A05424A540A1004967E1 /* DatabaseWriterTests.swift in Sources */,
@@ -1748,6 +1753,7 @@
5641A02524A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */,
5641A12124A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */,
5641A04324A540A1004967E1 /* FTS5TableBuilderTests.swift in Sources */,
56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */,
5641A10724A540A1004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
5641A11B24A540A1004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5641A05524A540A1004967E1 /* DatabaseWriterTests.swift in Sources */,
+256
View File
@@ -0,0 +1,256 @@
// Vendored from <https://github.com/groue/Semaphore/blob/0.1.0/Sources/Semaphore/AsyncSemaphore.swift>
// Copyright (C) 2022 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// An object that controls access to a resource across multiple execution
/// contexts through use of a traditional counting semaphore.
///
/// You increment a semaphore count by calling the ``signal()`` method, and
/// decrement a semaphore count by calling ``wait()`` or one of its variants.
///
/// ## Topics
///
/// ### Creating a Semaphore
///
/// - ``init(value:)``
///
/// ### Signaling the Semaphore
///
/// - ``signal()``
///
/// ### Waiting for the Semaphore
///
/// - ``wait()``
/// - ``waitUnlessCancelled()``
@available(iOS 13, macOS 10.15, tvOS 13, *)
public final class AsyncSemaphore: @unchecked Sendable {
/// `Suspension` is the state of a task waiting for a signal.
///
/// It is a class because instance identity helps `waitUnlessCancelled()`
/// deal with both early and late cancellation.
///
/// We make it @unchecked Sendable in order to prevent compiler warnings:
/// instances are always protected by the semaphore's lock.
private class Suspension: @unchecked Sendable {
enum State {
/// Initial state. Next is suspendedUnlessCancelled, or cancelled.
case pending
/// Waiting for a signal, with support for cancellation.
case suspendedUnlessCancelled(UnsafeContinuation<Void, Error>)
/// Waiting for a signal, with no support for cancellation.
case suspended(UnsafeContinuation<Void, Never>)
/// Cancelled before we have started waiting.
case cancelled
}
var state: State
init(state: State) {
self.state = state
}
}
// MARK: - Internal State
/// The semaphore value.
private var value: Int
/// As many elements as there are suspended tasks waiting for a signal.
private var suspensions: [Suspension] = []
/// The lock that protects `value` and `suspensions`.
///
/// It is recursive in order to handle cancellation (see the implementation
/// of ``waitUnlessCancelled()``).
private let _lock = NSRecursiveLock()
// MARK: - Creating a Semaphore
/// Creates a semaphore.
///
/// - parameter value: The starting value for the semaphore. Do not pass a
/// value less than zero.
public init(value: Int) {
precondition(value >= 0, "AsyncSemaphore requires a value equal or greater than zero")
self.value = value
}
deinit {
precondition(suspensions.isEmpty, "AsyncSemaphore is deallocated while some task(s) are suspended waiting for a signal.")
}
// MARK: - Locking
// Let's hide the locking primitive in order to avoid a compiler warning:
//
// > Instance method 'lock' is unavailable from asynchronous contexts;
// > Use async-safe scoped locking instead; this is an error in Swift 6.
//
// We're not sweeping bad stuff under the rug. We really need to protect
// our inner state (`value` and `suspension`) across the calls to
// `withUnsafeContinuation`. Unfortunately, this method introduces a
// suspension point. So we need a lock.
private func lock() { _lock.lock() }
private func unlock() { _lock.unlock() }
// MARK: - Waiting for the Semaphore
/// Waits for, or decrements, a semaphore.
///
/// Decrement the counting semaphore. If the resulting value is less than
/// zero, this function suspends the current task until a signal occurs,
/// without blocking the underlying thread. Otherwise, no suspension happens.
public func wait() async {
lock()
value -= 1
if value >= 0 {
unlock()
return
}
await withUnsafeContinuation { continuation in
// Register the continuation that `signal` will resume.
let suspension = Suspension(state: .suspended(continuation))
suspensions.insert(suspension, at: 0) // FIFO
unlock()
}
}
/// Waits for, or decrements, a semaphore, with support for cancellation.
///
/// Decrement the counting semaphore. If the resulting value is less than
/// zero, this function suspends the current task until a signal occurs,
/// without blocking the underlying thread. Otherwise, no suspension happens.
///
/// If the task is canceled before a signal occurs, this function
/// throws `CancellationError`.
public func waitUnlessCancelled() async throws {
lock()
value -= 1
if value >= 0 {
defer { unlock() }
do {
// All code paths check for cancellation
try Task.checkCancellation()
} catch {
// Cancellation is like a signal: we don't really "consume"
// the semaphore, and restore the value.
value += 1
throw error
}
return
}
// Get ready for being suspended waiting for a continuation, or for
// early cancellation.
let suspension = Suspension(state: .pending)
try await withTaskCancellationHandler {
try await withUnsafeThrowingContinuation { (continuation: UnsafeContinuation<Void, Error>) in
if case .cancelled = suspension.state {
// Early cancellation: waitUnlessCancelled() is called from
// a cancelled task, and the `onCancel` closure below
// has marked the suspension as cancelled.
// Resume with a CancellationError.
unlock()
continuation.resume(throwing: CancellationError())
} else {
// Current task is not cancelled: register the continuation
// that `signal` will resume.
suspension.state = .suspendedUnlessCancelled(continuation)
suspensions.insert(suspension, at: 0) // FIFO
unlock()
}
}
} onCancel: {
// withTaskCancellationHandler may immediately call this block (if
// the current task is cancelled), or call it later (if the task is
// cancelled later). In the first case, we're still holding the lock,
// waiting for the continuation. In the second case, we do not hold
// the lock. Being able to handle both situations is the reason why
// we use a recursive lock.
lock()
// We're no longer waiting for a signal
value += 1
if let index = suspensions.firstIndex(where: { $0 === suspension }) {
suspensions.remove(at: index)
}
if case let .suspendedUnlessCancelled(continuation) = suspension.state {
// Late cancellation: the task is cancelled while waiting
// from the semaphore. Resume with a CancellationError.
unlock()
continuation.resume(throwing: CancellationError())
} else {
// Early cancellation: waitUnlessCancelled() is called from
// a cancelled task.
//
// The next step is the `withTaskCancellationHandler`
// operation closure right above.
suspension.state = .cancelled
unlock()
}
}
}
// MARK: - Signaling the Semaphore
/// Signals (increments) a semaphore.
///
/// Increment the counting semaphore. If the previous value was less than
/// zero, this function resumes a task currently suspended in ``wait()``
/// or ``waitUnlessCancelled()``.
///
/// - returns: This function returns true if a suspended task is
/// resumed. Otherwise, the result is false, meaning that no task was
/// waiting for the semaphore.
@discardableResult
public func signal() -> Bool {
lock()
value += 1
switch suspensions.popLast()?.state { // FIFO
case let .suspendedUnlessCancelled(continuation):
unlock()
continuation.resume()
return true
case let .suspended(continuation):
unlock()
continuation.resume()
return true
default:
unlock()
return false
}
}
}
+312
View File
@@ -344,4 +344,316 @@ class DatabaseReaderTests : GRDBTestCase {
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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
func test_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<Task<Void, any Error>?>(nil)
let task = Task {
await semaphore.wait()
try await dbReader.read { 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 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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
func test_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<Task<Void, any Error>?>(nil)
let task = Task {
await semaphore.wait()
try await dbReader.unsafeRead { 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 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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
}
+407
View File
@@ -427,4 +427,411 @@ 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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
func test_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<Task<Void, any Error>?>(nil)
let task = Task {
await semaphore.wait()
try await dbWriter.writeWithoutTransaction { 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.writeWithoutTransaction { db in
try db.execute(sql: "SELECT 0")
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
func test_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<Task<Void, any Error>?>(nil)
let task = Task {
await semaphore.wait()
try await dbWriter.barrierWriteWithoutTransaction { 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.barrierWriteWithoutTransaction { db in
try db.execute(sql: "SELECT 0")
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
@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<Task<Void, any Error>?>(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())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
}