Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import Foundationimport Crypto
/// One `NNNN_name.sql` file from the `Migrations` resource folder, with the/// same bookkeeping the Go runner recorded in `schema_migrations`: the/// version prefix, the file name and the SHA-256 of the file's bytes.struct MigrationFile: Sendable, Equatable { static let noTransactionDirective = "migrate:no-transaction"
let version: String let name: String let sql: String let checksum: String let runsOutsideTransaction: Bool
init(name: String, contents: Data) throws { guard let underscore = name.firstIndex(of: "_") ?? name.firstIndex(of: "."), !name.hasPrefix("_") else { throw MigrationError.missingVersionPrefix(name) } let version = String(name[..<underscore]) guard !version.isEmpty else { throw MigrationError.missingVersionPrefix(name) } self.version = version self.name = name self.sql = String(decoding: contents, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) self.checksum = SHA256.hash(data: contents).map { String(format: "%02x", $0) }.joined() self.runsOutsideTransaction = Self.hasNoTransactionDirective(sql) }
/// The directive must appear in a leading `--` comment, before any SQL. static func hasNoTransactionDirective(_ sql: String) -> Bool { for rawLine in sql.split(separator: "\n", omittingEmptySubsequences: false) { let line = rawLine.trimmingCharacters(in: .whitespaces) if line.isEmpty { continue } if line.hasPrefix("--") { if line.contains(noTransactionDirective) { return true } continue } return false } return false }
/// Loads every `.sql` file in a directory, sorted by version, and rejects /// duplicate versions so a file can never be skipped silently. static func load(from directory: URL) throws -> [MigrationFile] { let names = try FileManager.default.contentsOfDirectory(atPath: directory.path) .filter { $0.hasSuffix(".sql") } var files: [MigrationFile] = [] for name in names { let data = try Data(contentsOf: directory.appendingPathComponent(name)) files.append(try MigrationFile(name: name, contents: data)) } files.sort { $0.version < $1.version } var seen: [String: String] = [:] for file in files { if let previous = seen[file.version] { throw MigrationError.duplicateVersion(file.version, previous, file.name) } seen[file.version] = file.name } return files }}
enum MigrationError: Error, Equatable, Sendable { case missingVersionPrefix(String) case duplicateVersion(String, String, String) case checksumMismatch(name: String, recorded: String, file: String) case resourcesMissing}