Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import Foundationimport Loggingimport PostgresNIO
/// Applies the SQL files in `Resources/Migrations` on startup.////// This is the Go runner, re-done: the same `schema_migrations` table with/// version, name, SHA-256 checksum and applied time; the same advisory lock so/// two instances never migrate at once; the same refusal to start when an/// applied file has changed; and the same `-- migrate:no-transaction` opt-out/// for statements such as `CREATE INDEX CONCURRENTLY`. A database the Go/// service migrated therefore comes up with nothing to apply.struct Migrator: Sendable { static let advisoryLockID: Int64 = 838_001_447
let database: Database let migrations: [MigrationFile] let logger: Logger
init(database: Database, migrations: [MigrationFile], logger: Logger) { self.database = database self.migrations = migrations self.logger = logger }
/// Loads the bundled migration files. static func bundledMigrations() throws -> [MigrationFile] { guard let directory = Bundle.module.url(forResource: "Migrations", withExtension: nil) else { throw MigrationError.resourcesMissing } return try MigrationFile.load(from: directory) }
/// Returns the names of the migrations that were applied. @discardableResult func run() async throws -> [String] { try await database.client.withConnection { connection in try await self.run(on: connection) } }
/// Lists the migrations that would run, without applying them. func pending() async throws -> [MigrationFile] { let applied = try await appliedChecksums() return migrations.filter { applied[$0.version] == nil } }
private func appliedChecksums() async throws -> [String: String] { var applied: [String: String] = [:] let rows = try await database.rows("SELECT version, checksum FROM schema_migrations") for row in rows { applied[try row.string("version")] = try row.string("checksum") } return applied }
private func run(on connection: PostgresConnection) async throws -> [String] { try await exec(connection, """ CREATE TABLE IF NOT EXISTS schema_migrations ( version TEXT PRIMARY KEY, name TEXT NOT NULL, checksum TEXT NOT NULL, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ) """) try await exec(connection, "SELECT pg_advisory_lock(\(Self.advisoryLockID))") defer { Task { try? await exec(connection, "SELECT pg_advisory_unlock(\(Self.advisoryLockID))") } }
var appliedNow: [String] = [] for migration in migrations { let rows = try await connection.query("SELECT checksum FROM schema_migrations WHERE version = \(migration.version)", logger: logger) var recorded: String? for try await row in rows { recorded = try row.decode(String.self) } if let recorded { guard recorded == migration.checksum else { throw MigrationError.checksumMismatch(name: migration.name, recorded: recorded, file: migration.checksum) } continue } logger.info("applying migration", metadata: ["name": "\(migration.name)"]) if migration.runsOutsideTransaction { try await applyOutsideTransaction(migration, on: connection) } else { try await applyInTransaction(migration, on: connection) } appliedNow.append(migration.name) } try await exec(connection, "SELECT pg_advisory_unlock(\(Self.advisoryLockID))") return appliedNow }
private func applyInTransaction(_ migration: MigrationFile, on connection: PostgresConnection) async throws { try await exec(connection, "BEGIN") do { try await exec(connection, "SET LOCAL statement_timeout = '5min'") try await exec(connection, "SET LOCAL lock_timeout = '30s'") for statement in SQLStatementSplitter.split(migration.sql) { try await exec(connection, statement) } try await record(migration, on: connection) try await exec(connection, "COMMIT") } catch { try? await exec(connection, "ROLLBACK") throw error } }
private func applyOutsideTransaction(_ migration: MigrationFile, on connection: PostgresConnection) async throws { try await exec(connection, "SET statement_timeout = '30min'") defer { Task { try? await exec(connection, "SET statement_timeout = DEFAULT") } } for statement in SQLStatementSplitter.split(migration.sql) { try await exec(connection, statement) } try await record(migration, on: connection) try await exec(connection, "SET statement_timeout = DEFAULT") }
private func record(_ migration: MigrationFile, on connection: PostgresConnection) async throws { let rows = try await connection.query( "INSERT INTO schema_migrations(version, name, checksum) VALUES (\(migration.version), \(migration.name), \(migration.checksum))", logger: logger ) for try await _ in rows {} }
private func exec(_ connection: PostgresConnection, _ sql: String) async throws { let rows = try await connection.query(PostgresQuery(unsafeSQL: sql), logger: logger) for try await _ in rows {} }}