mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
Merge branch 'development' into dev/barrierMigrations
# Conflicts: # GRDB/Migration/DatabaseMigrator.swift
This commit is contained in:
commit
f5019eeb60
5 files changed
+287
-40
No files matched your search
@@ -66,6 +66,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
### New
|
||||
|
||||
- [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again
|
||||
- [#710](https://github.com/groue/GRDB.swift/pull/710): Check if all migrations have been applied
|
||||
- [#712](https://github.com/groue/GRDB.swift/pull/712) by [@pakko972](https://github.com/pakko972): Automatic iOS memory management
|
||||
- [#713](https://github.com/groue/GRDB.swift/pull/713): Enhance DatabaseMigrator isolation
|
||||
|
||||
|
||||
@@ -48,8 +48,10 @@ Since several processes may open the database at the same time, protect the crea
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let dbPool = try DatabasePool(path: databaseURL.path)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator.
|
||||
try migrator.migrate(dbPool)
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
@@ -58,7 +60,8 @@ Since several processes may open the database at the same time, protect the crea
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database was not created yet.
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
@@ -81,7 +84,15 @@ Since several processes may open the database at the same time, protect the crea
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
return try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is correct, for example
|
||||
// with a DatabaseMigrator.
|
||||
if try migrator.hasCompletedMigrations(in: dbPool) {
|
||||
return dbPool
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
|
||||
@@ -117,8 +117,8 @@ public struct DatabaseMigrator {
|
||||
/// migration has not yet been applied, its block is executed in
|
||||
/// a transaction.
|
||||
///
|
||||
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
|
||||
/// migrations should apply.
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ writer: DatabaseWriter) throws {
|
||||
guard let lastMigration = migrations.last else {
|
||||
@@ -131,9 +131,9 @@ public struct DatabaseMigrator {
|
||||
/// provided target. If a migration has not yet been applied, its block is
|
||||
/// executed in a transaction.
|
||||
///
|
||||
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
|
||||
/// migrations should apply.
|
||||
/// - targetIdentifier: The identifier of a registered migration.
|
||||
/// - 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.
|
||||
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
|
||||
try writer.barrierWriteWithoutTransaction { db in
|
||||
@@ -175,13 +175,67 @@ public struct DatabaseMigrator {
|
||||
}
|
||||
|
||||
/// Returns the set of applied migration identifiers.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
|
||||
/// - parameter targetIdentifier: The identifier of a registered migration.
|
||||
/// - throws: An eventual database error.
|
||||
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String> {
|
||||
return try reader.read(appliedIdentifiers)
|
||||
}
|
||||
|
||||
/// Returns true if all migrations are applied.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
|
||||
/// - throws: An eventual database error.
|
||||
public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool {
|
||||
guard let lastMigration = migrations.last else {
|
||||
return true
|
||||
}
|
||||
return try hasCompletedMigrations(in: reader, through: lastMigration.identifier)
|
||||
}
|
||||
|
||||
/// Returns true if all migrations up to the provided target are applied,
|
||||
/// and maybe further.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
|
||||
/// - parameter targetIdentifier: The identifier of a registered migration.
|
||||
/// - throws: An eventual database error.
|
||||
public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool {
|
||||
return try reader.read { db in
|
||||
return try appliedIdentifiers(db)
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
let unappliedMigrations = self.unappliedMigrations(
|
||||
upTo: targetIdentifier,
|
||||
appliedIdentifiers: appliedIdentifiers)
|
||||
return unappliedMigrations.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Returns the identifier of the last migration for which all predecessors
|
||||
/// have been applied.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
|
||||
/// - returns: An eventual migration identifier.
|
||||
/// - throws: An eventual database error.
|
||||
public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? {
|
||||
return try reader.read { db in
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
if appliedIdentifiers.isEmpty {
|
||||
return nil
|
||||
}
|
||||
let lastAppliedIdentifier = migrations
|
||||
.last { appliedIdentifiers.contains($0.identifier) }!
|
||||
.identifier
|
||||
let unappliedMigrations = self.unappliedMigrations(
|
||||
upTo: lastAppliedIdentifier,
|
||||
appliedIdentifiers: appliedIdentifiers)
|
||||
if unappliedMigrations.isEmpty {
|
||||
return lastAppliedIdentifier
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
private mutating func registerMigration(_ migration: Migration) {
|
||||
@@ -199,14 +253,14 @@ public struct DatabaseMigrator {
|
||||
return []
|
||||
}
|
||||
return try Set(String.fetchAll(db, sql: "SELECT identifier FROM grdb_migrations"))
|
||||
.intersection(migrations.map { $0.identifier })
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
|
||||
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
|
||||
|
||||
var prefixMigrations: [Migration] = []
|
||||
/// Returns unapplied migration identifier,
|
||||
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: Set<String>) -> [Migration] {
|
||||
var expectedMigrations: [Migration] = []
|
||||
for migration in migrations {
|
||||
prefixMigrations.append(migration)
|
||||
expectedMigrations.append(migration)
|
||||
if migration.identifier == targetIdentifier {
|
||||
break
|
||||
}
|
||||
@@ -214,19 +268,29 @@ public struct DatabaseMigrator {
|
||||
|
||||
// targetIdentifier must refer to a registered migration
|
||||
GRDBPrecondition(
|
||||
prefixMigrations.last?.identifier == targetIdentifier,
|
||||
expectedMigrations.last?.identifier == targetIdentifier,
|
||||
"undefined migration: \(String(reflecting: targetIdentifier))")
|
||||
|
||||
// Subsequent migration must not be applied
|
||||
return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) }
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
|
||||
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
|
||||
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
if prefixMigrations.count < migrations.count {
|
||||
let nextIdentifier = migrations[prefixMigrations.count].identifier
|
||||
GRDBPrecondition(
|
||||
!appliedIdentifiers.contains(nextIdentifier),
|
||||
"database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
|
||||
|
||||
// Subsequent migration must not be applied
|
||||
if let index = migrations.firstIndex(where: { $0.identifier == targetIdentifier }),
|
||||
migrations[(index + 1)...].contains(where: { appliedIdentifiers.contains($0.identifier) })
|
||||
{
|
||||
fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
|
||||
}
|
||||
|
||||
for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) {
|
||||
let unappliedMigrations = self.unappliedMigrations(
|
||||
upTo: targetIdentifier,
|
||||
appliedIdentifiers: appliedIdentifiers)
|
||||
|
||||
for migration in unappliedMigrations {
|
||||
try migration.run(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4931,24 +4931,35 @@ You migrate the database up to the latest version with the `migrate(_:)` method:
|
||||
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
|
||||
```
|
||||
|
||||
To migrate a database up to a specific version, use `migrate(_:upTo:)`:
|
||||
Migrate a database up to a specific version:
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
```
|
||||
|
||||
Migrations can only run forward:
|
||||
|
||||
```swift
|
||||
// Migrations can only run forward:
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
try migrator.migrate(dbQueue, upTo: "v1")
|
||||
// fatal error: database is already migrated beyond migration "v1"
|
||||
// ^ fatal error: database is already migrated beyond migration "v1"
|
||||
```
|
||||
|
||||
Check if a migration has been applied:
|
||||
Check if consecutive migrations have been applied:
|
||||
|
||||
```swift
|
||||
let appliedMigrations = try migrator.appliedMigrations(in: dbQueue)
|
||||
if try migrator.hasCompletedMigrations(in: dbQueue) {
|
||||
// All migrations have been applied, up to the last one.
|
||||
}
|
||||
if try migrator.hasCompletedMigrations(in: dbQueue, through: "v2") {
|
||||
// All migrations have been applied up to "v2", and maybe further.
|
||||
}
|
||||
if try migrator.lastCompletedMigration(in: dbQueue) == "v2" {
|
||||
// All migrations have been applied up to "v2", and no further.
|
||||
}
|
||||
```
|
||||
|
||||
Check which migrations have been applied:
|
||||
|
||||
```swift
|
||||
let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) // Set<String>
|
||||
if appliedMigrations.contains("v2") {
|
||||
// "v2" migration has been applied
|
||||
}
|
||||
|
||||
@@ -7,6 +7,12 @@ import XCTest
|
||||
|
||||
class DatabaseMigratorTests : GRDBTestCase {
|
||||
|
||||
func testEmptyMigrator() throws {
|
||||
let migrator = DatabaseMigrator()
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
func testMigratorDatabaseQueue() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -290,6 +296,15 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
|
||||
func testAppliedMigrations() throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// No migration
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
|
||||
}
|
||||
|
||||
// One migration
|
||||
|
||||
migrator.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
@@ -297,22 +312,167 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
t.column("score", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"])
|
||||
}
|
||||
|
||||
// Two migrations
|
||||
|
||||
migrator.registerMigration("2") { db in
|
||||
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
|
||||
}
|
||||
|
||||
// Apply migrator
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
|
||||
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"])
|
||||
|
||||
try migrator.migrate(dbQueue, upTo: "2")
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"])
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"])
|
||||
try migrator.migrate(dbQueue, upTo: "2")
|
||||
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"])
|
||||
}
|
||||
}
|
||||
|
||||
func testHasCompletedMigrations() throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// No migration
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue))
|
||||
}
|
||||
|
||||
// One migration
|
||||
|
||||
migrator.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue))
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue))
|
||||
}
|
||||
|
||||
// Two migrations
|
||||
|
||||
migrator.registerMigration("2") { db in
|
||||
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
|
||||
}
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2"))
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue))
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2"))
|
||||
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue))
|
||||
try migrator.migrate(dbQueue, upTo: "2")
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "2"))
|
||||
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue))
|
||||
}
|
||||
}
|
||||
|
||||
func testLastCompletedMigration() throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// No migration
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue))
|
||||
}
|
||||
|
||||
// One migration
|
||||
|
||||
migrator.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue))
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1")
|
||||
}
|
||||
|
||||
// Two migrations
|
||||
|
||||
migrator.registerMigration("2") { db in
|
||||
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
|
||||
}
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue))
|
||||
try migrator.migrate(dbQueue, upTo: "1")
|
||||
try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1")
|
||||
try migrator.migrate(dbQueue, upTo: "2")
|
||||
try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "2")
|
||||
}
|
||||
}
|
||||
|
||||
func testMergedMigrators() throws {
|
||||
// Migrate a database
|
||||
var oldMigrator = DatabaseMigrator()
|
||||
oldMigrator.registerMigration("1", migrate: { _ in })
|
||||
oldMigrator.registerMigration("3", migrate: { _ in })
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try oldMigrator.migrate(dbQueue)
|
||||
|
||||
try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"])
|
||||
try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue))
|
||||
try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "3"))
|
||||
try XCTAssertEqual(oldMigrator.lastCompletedMigration(in: dbQueue), "3")
|
||||
|
||||
// A source code merge inserts a migration between "1" and "3"
|
||||
var newMigrator = DatabaseMigrator()
|
||||
newMigrator.registerMigration("1", migrate: { _ in })
|
||||
newMigrator.registerMigration("2", migrate: { _ in })
|
||||
newMigrator.registerMigration("3", migrate: { _ in })
|
||||
|
||||
try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "3"])
|
||||
try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue))
|
||||
try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue, through: "2"))
|
||||
try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue, through: "3"))
|
||||
try XCTAssertNil(newMigrator.lastCompletedMigration(in: dbQueue))
|
||||
|
||||
// The new source code migrates the database
|
||||
try newMigrator.migrate(dbQueue)
|
||||
|
||||
try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"])
|
||||
try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue))
|
||||
try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "3"))
|
||||
try XCTAssertEqual(oldMigrator.lastCompletedMigration(in: dbQueue), "3")
|
||||
|
||||
try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "2", "3"])
|
||||
try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue))
|
||||
try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "1"))
|
||||
try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "2"))
|
||||
try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "3"))
|
||||
try XCTAssertEqual(newMigrator.lastCompletedMigration(in: dbQueue), "3")
|
||||
}
|
||||
|
||||
func testEraseDatabaseOnSchemaChange() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
|
||||
Reference in new issue
Block a user