From c9c652dddc423f29b1bb274f350ea7bc1069cdec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Mar 2021 13:25:43 +0100 Subject: [PATCH] DatabaseMigrator async migrations --- GRDB/Core/DatabasePool.swift | 16 +++ GRDB/Core/DatabaseQueue.swift | 11 ++ GRDB/Core/DatabaseWriter.swift | 14 ++ GRDB/Migration/DatabaseMigrator.swift | 181 +++++++++++++++++--------- GRDB/Utils/Pool.swift | 9 ++ 5 files changed, 166 insertions(+), 65 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index ea0ca970c..798a28c71 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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. /// diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index af826f5a3..3da2ec8d7 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -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. /// diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index ac3dcc8f5..caf66bbf3 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -70,6 +70,16 @@ public protocol DatabaseWriter: DatabaseReader { /// - throws: The error thrown by the updates. func barrierWriteWithoutTransaction(_ 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( _ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 5de3d6f81..d816bf2e8 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -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) + } } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index c7b12c0de..c611bb242 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -129,4 +129,13 @@ final class Pool { 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() + } + } }