DatabaseMigrator async migrations

This commit is contained in:
Gwendal Roué committed 2021-03-20 13:25:43 +01:00
1 parent edde38837e
commit c9c652dddc
5 files changed
+166 -65

No files matched your search

+16
View File
@@ -717,6 +717,22 @@ extension DatabasePool: DatabaseReader {
}
}
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
/// Updates are guaranteed an exclusive access to the database. They wait
/// until all pending writes and reads are completed. They postpone all
/// other writes and reads until they are completed.
///
/// - important: Reads executed by concurrent *database snapshots* are not
/// considered: they can run concurrently with the barrier updates.
/// - parameter updates: The updates to the database.
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
readerPool.asyncBarrier {
self.writer.sync(updates)
}
}
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
+11
View File
@@ -408,6 +408,17 @@ extension DatabaseQueue {
try writer.sync(updates)
}
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
/// Eventual concurrent database accesses are postponed until the updates
/// are completed.
///
/// - parameter updates: The updates to the database.
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
+14
View File
@@ -70,6 +70,16 @@ public protocol DatabaseWriter: DatabaseReader {
/// - throws: The error thrown by the updates.
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
/// Updates are guaranteed an exclusive access to the database. They wait
/// 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)
/// Asynchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction.
///
@@ -620,6 +630,10 @@ public final class AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
+116 -65
View File
@@ -121,72 +121,54 @@ public struct DatabaseMigrator {
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
try writer.barrierWriteWithoutTransaction { db in
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = Set(migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
needsErase = true
return .commit
}
if let lastAppliedIdentifier = migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
//
// Let's migrate a temporary database up to the same
// level, and compare the database schemas. If they
// differ, we'll erase the database.
let tmpSchema: SchemaInfo = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = writer.configuration
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
// Create the temporary database on disk, just in
// case migrations would involve a lot of data.
//
// SQLite supports temporary on-disk databases, but
// those are not guaranteed to accept the
// preparation functions provided by the user.
//
// See https://github.com/groue/GRDB.swift/issues/931
// for an issue created by such databases.
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo().globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
return try tmpDatabase.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema()
}
}()
if try db.schema() != tmpSchema {
needsErase = true
return .commit
}
}
return .commit
}
if needsErase {
try db.erase()
}
try migrate(db, upTo: targetIdentifier)
}
}
/// Iterate migrations in the same order as they were registered. If a
/// migration has not yet been applied, its block is executed in
/// a transaction.
///
/// - 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.
public func asyncMigrate(
_ writer: DatabaseWriter,
completion: @escaping (Database, Error?) -> Void)
{
if let lastMigration = migrations.last {
asyncMigrate(writer, upTo: lastMigration.identifier, completion: completion)
} else {
writer.asyncBarrierWriteWithoutTransaction { db in
completion(db, nil)
}
}
}
/// Iterate migrations in the same order as they were registered, up to the
/// provided target. If a migration has not yet been applied, its block is
/// executed in a transaction.
///
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
/// where migrations should apply.
/// - parameter targetIdentifier: The identifier of a registered migration.
/// - parameter completion: A closure that is called in a protected dispatch
/// queue that can write in the database, with the eventual
/// migration error.
public func asyncMigrate(
_ writer: DatabaseWriter,
upTo targetIdentifier: String,
completion: @escaping (Database, Error?) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { db in
do {
try migrate(db, upTo: targetIdentifier)
completion(db, nil)
} catch {
completion(db, error)
}
// Migrate to target schema
try runMigrations(db, upTo: targetIdentifier)
}
}
@@ -307,4 +289,73 @@ public struct DatabaseMigrator {
try migration.run(db)
}
}
private func migrate(_ db: Database, upTo targetIdentifier: String) throws {
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = Set(migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
needsErase = true
return .commit
}
if let lastAppliedIdentifier = migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
//
// Let's migrate a temporary database up to the same
// level, and compare the database schemas. If they
// differ, we'll erase the database.
let tmpSchema: SchemaInfo = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = db.configuration
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
// Create the temporary database on disk, just in
// case migrations would involve a lot of data.
//
// SQLite supports temporary on-disk databases, but
// those are not guaranteed to accept the
// preparation functions provided by the user.
//
// See https://github.com/groue/GRDB.swift/issues/931
// for an issue created by such databases.
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo().globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
return try tmpDatabase.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema()
}
}()
if try db.schema() != tmpSchema {
needsErase = true
return .commit
}
}
return .commit
}
if needsErase {
try db.erase()
}
}
// Migrate to target schema
try runMigrations(db, upTo: targetIdentifier)
}
}
+9
View File
@@ -129,4 +129,13 @@ final class Pool<T> {
return try barrier()
}
}
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
}
}
}