import Foundation import 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[.. 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 }