SPB Git

Repository Public License

Migrator.swift 4.2 KB 81 lines swift

1import Foundation23/// One schema step. Migrations are append-only: once a version has shipped its body is frozen, and any change4/// to the schema is a new `Migration` appended to `Schema.migrations`.5public struct Migration: Sendable {6    public let version: Int7    public let name: String8    /// Table rebuilds (`CREATE new … INSERT SELECT … DROP old … RENAME`) need foreign keys off while they run.9    /// The migrator then verifies `PRAGMA foreign_key_check` before committing.10    public let disablesForeignKeys: Bool11    public let apply: @Sendable (SQLiteConnection) throws -> Void1213    public init(version: Int, name: String, disablesForeignKeys: Bool = false,14                apply: @escaping @Sendable (SQLiteConnection) throws -> Void) {15        self.version = version; self.name = name16        self.disablesForeignKeys = disablesForeignKeys; self.apply = apply17    }1819    /// A migration that is only SQL.20    public init(version: Int, name: String, sql: String) {21        self.init(version: version, name: name) { try $0.executeScript(sql) }22    }23}2425/// Applies migrations in order, each in its own transaction, and records the version in `PRAGMA user_version`26/// (part of the database header, so it commits atomically with the migration) and in `schema_migrations`.27public enum Migrator {28    public struct Outcome: Sendable, Equatable {29        public let fromVersion: Int30        public let toVersion: Int31        public var applied: [Int] { fromVersion < toVersion ? Array((fromVersion + 1)...toVersion) : [] }32    }3334    public static func currentVersion(_ connection: SQLiteConnection) throws -> Int {35        try connection.scalar("PRAGMA user_version", as: Int.self) ?? 036    }3738    /// - Parameter target: stop after this version (tests build old fixtures with it); `nil` means latest.39    @discardableResult40    public static func migrate(_ connection: SQLiteConnection, migrations: [Migration] = Schema.migrations,41                               upTo target: Int? = nil) throws -> Outcome {42        precondition(migrations.enumerated().allSatisfy { $0.element.version == $0.offset + 1 },43                     "Migration versions must be 1, 2, 3… without gaps")44        let latest = migrations.last?.version ?? 045        let start = try currentVersion(connection)46        // Never touch a database written by a newer build: an old binary cannot know what the new columns mean.47        guard start <= latest else { throw PersistenceError.databaseTooNew(found: start, supported: latest) }48        let goal = min(target ?? latest, latest)4950        for migration in migrations where migration.version > start && migration.version <= goal {51            if migration.disablesForeignKeys {52                // The pragma is a no-op inside a transaction, so it brackets the transaction.53                try connection.executeScript("PRAGMA foreign_keys = OFF")54            }55            defer {56                if migration.disablesForeignKeys { try? connection.executeScript("PRAGMA foreign_keys = ON") }57            }58            try connection.transaction {59                try connection.executeScript("""60                CREATE TABLE IF NOT EXISTS schema_migrations (61                    version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at REAL NOT NULL62                )63                """)64                try migration.apply(connection)65                if migration.disablesForeignKeys {66                    let violations = try connection.query("PRAGMA foreign_key_check")67                    guard violations.isEmpty else {68                        throw PersistenceError.invalidData(69                            "migration \(migration.version) left \(violations.count) foreign key violations")70                    }71                }72                try connection.execute("INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",73                                       [migration.version, migration.name, Date.now])74                // PRAGMA does not accept bound parameters; the value is an Int from our own list.75                try connection.executeScript("PRAGMA user_version = \(migration.version)")76            }77        }78        return Outcome(fromVersion: start, toVersion: max(start, goal))79    }80}81
Files main
Menu

Theme