From 8936ef6a408d129331b9705980ee81bf67ba71ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 13 Oct 2021 15:31:39 +0200 Subject: [PATCH] DatabaseMigrator async methods migrate(_:) migrate(_:upTo:) --- GRDB/Migration/DatabaseMigrator.swift | 36 +++++++ Tests/GRDBCombineTests/Support.swift | 51 ++++++++++ Tests/GRDBTests/DatabaseMigratorTests.swift | 103 ++++++++++++++++++++ 3 files changed, 190 insertions(+) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 3778d1075..66357f174 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -107,6 +107,7 @@ public struct DatabaseMigrator { /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func migrate(_ writer: DatabaseWriter) throws { guard let lastMigration = _migrations.last else { return @@ -114,6 +115,23 @@ public struct DatabaseMigrator { try migrate(writer, upTo: lastMigration.identifier) } + #if swift(>=5.5) + /// 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. + /// - throws: An eventual error thrown by the registered migration blocks. + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + public func migrate(_ writer: DatabaseWriter) async throws { + guard let lastMigration = _migrations.last else { + return + } + try await migrate(writer, upTo: lastMigration.identifier) + } + #endif + /// 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. @@ -122,12 +140,30 @@ public struct DatabaseMigrator { /// where migrations should apply. /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { try writer.barrierWriteWithoutTransaction { db in try migrate(db, upTo: targetIdentifier) } } +#if swift(>=5.5) + /// 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. + /// - throws: An eventual error thrown by the registered migration blocks. + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) async throws { + try await writer.barrierWriteWithoutTransaction { db in + try migrate(db, upTo: targetIdentifier) + } + } +#endif + /// 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. diff --git a/Tests/GRDBCombineTests/Support.swift b/Tests/GRDBCombineTests/Support.swift index 49a4636db..f3e21774f 100644 --- a/Tests/GRDBCombineTests/Support.swift +++ b/Tests/GRDBCombineTests/Support.swift @@ -51,6 +51,57 @@ final class Test { } } +#if swift(>=5.5) +@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) +final class AsyncTest { + // Raise the repeatCount in order to help spotting flaky tests. + private let repeatCount: Int + private let test: (Context, Int) async throws -> () + + init(repeatCount: Int = 1, _ test: @escaping (Context) async throws -> ()) { + self.repeatCount = repeatCount + self.test = { context, _ in try await test(context) } + } + + init(repeatCount: Int, _ test: @escaping (Context, Int) async throws -> ()) { + self.repeatCount = repeatCount + self.test = test + } + + @discardableResult + func run(context: () async throws -> Context) async throws -> Self { + for i in 1...repeatCount { + try await test(context(), i) + } + return self + } + + @discardableResult + func runInTemporaryDirectory(context: (_ directoryURL: URL) async throws -> Context) async throws -> Self { + for i in 1...repeatCount { + let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent("GRDB", isDirectory: true) + .appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString, isDirectory: true) + + try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + defer { + try! FileManager.default.removeItem(at: directoryURL) + } + + try await test(context(directoryURL), i) + } + return self + } + + @discardableResult + func runAtTemporaryDatabasePath(context: (_ path: String) async throws -> Context) async throws -> Self { + try await runInTemporaryDirectory { url in + try await context(url.appendingPathComponent("db.sqlite").path) + } + } +} +#endif + #if compiler(>=5.3) @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func assertNoFailure( diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 4b396dd3d..913e59cc4 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -98,6 +98,54 @@ class DatabaseMigratorTests : GRDBTestCase { .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } +#if swift(>=5.5) + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + func testAsyncAwait_NonEmptyMigratorSync() async throws { + func test(writer: DatabaseWriter) async throws { + var migrator = DatabaseMigrator() + migrator.registerMigration("createPersons") { db in + try db.execute(sql: """ + CREATE TABLE persons ( + id INTEGER PRIMARY KEY, + name TEXT) + """) + } + migrator.registerMigration("createPets") { db in + try db.execute(sql: """ + CREATE TABLE pets ( + id INTEGER PRIMARY KEY, + masterID INTEGER NOT NULL + REFERENCES persons(id) + ON DELETE CASCADE ON UPDATE CASCADE, + name TEXT) + """) + } + + var migrator2 = migrator + migrator2.registerMigration("destroyPersons") { db in + try db.execute(sql: "DROP TABLE pets") + } + + try await migrator.migrate(writer) + try await writer.read { db in + XCTAssertTrue(try db.tableExists("persons")) + XCTAssertTrue(try db.tableExists("pets")) + } + + try await migrator2.migrate(writer) + try await writer.read { db in + XCTAssertTrue(try db.tableExists("persons")) + XCTAssertFalse(try db.tableExists("pets")) + } + } + + try await AsyncTest(test) + .run { DatabaseQueue() } + .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + } +#endif + func testNonEmptyMigratorAsync() throws { func test(writer: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -374,6 +422,61 @@ class DatabaseMigratorTests : GRDBTestCase { .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } + +#if swift(>=5.5) + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + func testAsyncAwait_MigrateUpTo() async throws { + func test(writer: DatabaseWriter) async throws { + var migrator = DatabaseMigrator() + migrator.registerMigration("a") { db in + try db.execute(sql: "CREATE TABLE a (id INTEGER PRIMARY KEY)") + } + migrator.registerMigration("b") { db in + try db.execute(sql: "CREATE TABLE b (id INTEGER PRIMARY KEY)") + } + migrator.registerMigration("c") { db in + try db.execute(sql: "CREATE TABLE c (id INTEGER PRIMARY KEY)") + } + + // one step + try await migrator.migrate(writer, upTo: "a") + try await writer.read { db in + XCTAssertTrue(try db.tableExists("a")) + XCTAssertFalse(try db.tableExists("b")) + } + + // zero step + try await migrator.migrate(writer, upTo: "a") + try await writer.read { db in + XCTAssertTrue(try db.tableExists("a")) + XCTAssertFalse(try db.tableExists("b")) + } + + // two steps + try await migrator.migrate(writer, upTo: "c") + try await writer.read { db in + XCTAssertTrue(try db.tableExists("a")) + XCTAssertTrue(try db.tableExists("b")) + XCTAssertTrue(try db.tableExists("c")) + } + + // zero step + try await migrator.migrate(writer, upTo: "c") + try await migrator.migrate(writer) + + // fatal error: undefined migration: "missing" + // try migrator.migrate(writer, upTo: "missing") + + // fatal error: database is already migrated beyond migration "b" + // try migrator.migrate(writer, upTo: "b") + } + + try await AsyncTest(test) + .run { DatabaseQueue() } + .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + } +#endif func testMigrationFailureTriggersRollback() throws { var migrator = DatabaseMigrator()