BREAKING: throwing DatabaseWriter.barrierWriteWithoutTransaction

It used to be rethrowing, but it was then unable to deal with closed databases.

The async version is modified accordingly: it accepts a Result<Database, Error>, instead of a raw Database.

DatabaseMigrator.asyncMigrate is impacted as well: it accepts a Result<Database, Error>, instead of a (Database, Error?) tuple.
This commit is contained in:
Gwendal Roué committed 2022-08-21 19:21:57 +02:00
1 parent fe225fe452
commit 6f0d45eedb
8 files changed
+68 -49

No files matched your search

+5 -2
View File
@@ -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
}
})
```
+12 -7
View File
@@ -651,17 +651,22 @@ extension DatabasePool: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
// TODO: throw instead of crashing when the database is closed
try readerPool!.barrier {
public func barrierWriteWithoutTransaction<T>(_ 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<Database, Error>) -> Void) {
guard let readerPool = readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
}
readerPool.asyncBarrier {
self.writer.sync { updates(.success($0)) }
}
}
+3 -3
View File
@@ -309,12 +309,12 @@ extension DatabaseQueue {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func barrierWriteWithoutTransaction<T>(_ 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<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
/// Synchronously executes database updates in a protected dispatch queue,
+9 -11
View File
@@ -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<T>(_ updates: (Database) throws -> T) rethrows -> T
func barrierWriteWithoutTransaction<T>(_ 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<Database, Error>) -> 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<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
+8
View File
@@ -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<Database, Error> argument")
public func asyncMigrate(
_ writer: DatabaseWriter,
completion: @escaping (Database, Error?) -> Void)
{ preconditionFailure() }
}
extension DatabaseUUIDEncodingStrategy {
@available(*, unavailable, renamed: "uppercaseString")
public static var string: Self { preconditionFailure() }
+10 -13
View File
@@ -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<Database, Error>) -> 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()
+20 -12
View File
@@ -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)
}
@@ -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()
}