diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index a7d94127a..72915c0bf 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -274,9 +274,12 @@ The `asyncMigrate(_:completion:)` method: ```swift // Completes in a protected dispatch queue that can write in the database -migrator.asyncMigrate(dbQueue, completion: { db, error in - if let error = error { +migrator.asyncMigrate(dbQueue, completion: { result in + switch result { + case .failure: // Some error occurred during migrations + case let .success(db): + // Migrations succeeded } }) ``` diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index db11fd85a..5c670e829 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -651,17 +651,22 @@ extension DatabasePool: DatabaseReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - // TODO: throw instead of crashing when the database is closed - try readerPool!.barrier { + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { + guard let readerPool = readerPool else { + throw DatabaseError.connectionIsClosed() + } + return try readerPool.barrier { try writer.sync(updates) } } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { - // TODO: throw instead of crashing when the database is closed - readerPool!.asyncBarrier { - self.writer.sync(updates) + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + guard let readerPool = readerPool else { + updates(.failure(DatabaseError.connectionIsClosed())) + return + } + readerPool.asyncBarrier { + self.writer.sync { updates(.success($0)) } } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ed0936f5c..922c357ab 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -309,12 +309,12 @@ extension DatabaseQueue { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try writer.sync(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { - writer.async(updates) + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + writer.async { updates(.success($0)) } } /// Synchronously executes database updates in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 6b4a8a0ab..d471eb461 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -89,7 +89,7 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T /// Asynchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. @@ -98,8 +98,10 @@ public protocol DatabaseWriter: DatabaseReader { /// until all pending writes and reads are completed. They postpone all /// other writes and reads until they are completed. /// - /// - parameter updates: The updates to the database. - func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + /// - parameter updates: A function that accesses the database. Its argument + /// is a `Result` that provides the database connection, or the failure + /// that would prevent establishing the barrier access to the database. + func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) /// Asynchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction. @@ -446,12 +448,8 @@ extension DatabaseWriter { async throws -> T { try await withUnsafeThrowingContinuation { continuation in - asyncBarrierWriteWithoutTransaction { db in - do { - try continuation.resume(returning: updates(db)) - } catch { - continuation.resume(throwing: error) - } + asyncBarrierWriteWithoutTransaction { dbResult in + continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } }) } } } @@ -754,11 +752,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try base.barrierWriteWithoutTransaction(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { base.asyncBarrierWriteWithoutTransaction(updates) } diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 333bbb559..54a51f0b9 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -33,6 +33,14 @@ extension Database { public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } } +extension DatabaseMigrator { + @available(*, unavailable, message: "The completion function now accepts one Result argument") + public func asyncMigrate( + _ writer: DatabaseWriter, + completion: @escaping (Database, Error?) -> Void) + { preconditionFailure() } +} + extension DatabaseUUIDEncodingStrategy { @available(*, unavailable, renamed: "uppercaseString") public static var string: Self { preconditionFailure() } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 13ae52339..b7546125f 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -224,21 +224,22 @@ public struct DatabaseMigrator { /// /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. - /// - parameter completion: A closure that is called in a protected dispatch - /// queue that can write in the database, with the eventual - /// migration error. + /// - parameter completion: A function that can access the database. Its + /// argument is a `Result` that provides a connection to the migrated + /// database, or the failure that would prevent the migration to complete. public func asyncMigrate( _ writer: DatabaseWriter, - completion: @escaping (Database, Error?) -> Void) + completion: @escaping (Result) -> Void) { - writer.asyncBarrierWriteWithoutTransaction { db in + writer.asyncBarrierWriteWithoutTransaction { dbResult in do { + let db = try dbResult.get() if let lastMigration = self._migrations.last { try self.migrate(db, upTo: lastMigration.identifier) } - completion(db, nil) + completion(.success(db)) } catch { - completion(db, error) + completion(.failure(error)) } } } @@ -477,12 +478,8 @@ extension DatabaseMigrator { { DatabasePublishers.Migrate( upstream: OnDemandFuture { promise in - self.asyncMigrate(writer) { _, error in - if let error = error { - promise(.failure(error)) - } else { - promise(.success(())) - } + self.asyncMigrate(writer) { dbResult in + promise(dbResult.map { _ in }) } } .eraseToAnyPublisher() diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index c1384c914..c9945aa36 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -19,9 +19,10 @@ class DatabaseMigratorTests : GRDBTestCase { func test(writer: DatabaseWriter) throws { let expectation = self.expectation(description: "") let migrator = DatabaseMigrator() - migrator.asyncMigrate(writer, completion: { db, error in + migrator.asyncMigrate(writer, completion: { dbResult in // No migration error - XCTAssertNil(error) + let db = try! dbResult.get() + // Write access try! db.execute(sql: "CREATE TABLE t(a)") expectation.fulfill() @@ -125,16 +126,16 @@ class DatabaseMigratorTests : GRDBTestCase { } let expectation = self.expectation(description: "") - migrator.asyncMigrate(writer, completion: { (db, error) in + migrator.asyncMigrate(writer, completion: { dbResult in // No migration error - XCTAssertNil(error) + let db = try! dbResult.get() XCTAssertTrue(try! db.tableExists("persons")) XCTAssertTrue(try! db.tableExists("pets")) - migrator2.asyncMigrate(writer, completion: { db, error in + migrator2.asyncMigrate(writer, completion: { dbResult in // No migration error - XCTAssertNil(error) + let db = try! dbResult.get() XCTAssertTrue(try! db.tableExists("persons")) XCTAssertFalse(try! db.tableExists("pets")) @@ -413,19 +414,26 @@ class DatabaseMigratorTests : GRDBTestCase { do { let expectation = self.expectation(description: "") let dbQueue = try makeDatabaseQueue() - migrator.asyncMigrate(dbQueue, completion: { db, error in + migrator.asyncMigrate(dbQueue, completion: { dbResult in // The first migration should be committed. // The second migration should be rollbacked. - let error = error as! DatabaseError + guard case let .failure(error as DatabaseError) = dbResult else { + XCTFail("Expected DatabaseError") + expectation.fulfill() + return + } + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) - let names = try! String.fetchAll(db, sql: "SELECT name FROM persons") - XCTAssertEqual(names, ["Arthur"]) - - expectation.fulfill() + dbQueue.asyncRead { dbResult in + let names = try! String.fetchAll(dbResult.get(), sql: "SELECT name FROM persons") + XCTAssertEqual(names, ["Arthur"]) + + expectation.fulfill() + } }) waitForExpectations(timeout: 5, handler: nil) } diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 445d67a39..33327ba72 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1304,7 +1304,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // Wait for read to start s1.wait() - dbPool.barrierWriteWithoutTransaction { _ in } + try! dbPool.barrierWriteWithoutTransaction { _ in } expectation.fulfill() s4.signal() }