const std = @import("std"); const zug = @import("root.zig"); const StatementIterator = @import("statement.zig").StatementIterator; /// Run migrations against a SQLite-shaped connection. /// /// The connection must provide: /// - `exec(sql, args) !void` /// - `rows(sql, args) !Rows` /// /// `Rows.next()` must return rows with `text(index)` and `int(index)` methods. pub fn run( allocator: std.mem.Allocator, conn: anytype, migrations: []const zug.Migration, options: zug.Options, ) !void { comptime validateConn(@TypeOf(conn)); if (options.diagnostics) |d| d.clear(); try zug.validateIdentifier(options.table_name); try ensureMigrationsTable(allocator, conn, options.table_name); try zug.validateUnique(migrations); const applied_rows = try applied(allocator, conn, options.table_name); defer zug.freeAppliedRows(allocator, applied_rows); for (migrations) |migration| { if (!options.classes.contains(migration.class)) continue; if (zug.findApplied(applied_rows, migration.id)) |row| { if (options.stop_on_dirty and row.dirty) { zug.setDiag(options, migration.id, 0, "", "migration is dirty"); return zug.Error.DirtyMigration; } if (options.check_checksum) { var checksum_buf: [16]u8 = undefined; const expected = migration.checksumHex(&checksum_buf); if (!std.mem.eql(u8, row.checksum, expected)) { zug.setDiag(options, migration.id, 0, "", "migration checksum changed"); return zug.Error.ChecksumMismatch; } } continue; } try applyOne(allocator, conn, migration, options); } } /// Mark a fixed baseline of migrations as already applied. /// /// Use this when adopting `zug` on an existing database whose schema already /// represents the provided migration slice. `baseline` is resumable: it inserts /// missing baseline rows with `INSERT OR IGNORE`, then verifies every baseline /// row is present, clean, and checksum-matching before returning. /// /// The caller chooses the baseline slice explicitly. Do not pass migrations /// appended after adoption unless they have also already been applied by other /// means. pub fn baseline( allocator: std.mem.Allocator, conn: anytype, migrations: []const zug.Migration, options: zug.BaselineOptions, ) !void { comptime validateConn(@TypeOf(conn)); if (options.diagnostics) |d| d.clear(); try zug.validateIdentifier(options.table_name); try ensureMigrationsTable(allocator, conn, options.table_name); try zug.validateUnique(migrations); for (migrations) |migration| { var checksum_buf: [16]u8 = undefined; const checksum = migration.checksumHex(&checksum_buf); try insertMigrationIgnore(allocator, conn, options.table_name, migration, checksum, false); } const applied_rows = try applied(allocator, conn, options.table_name); defer zug.freeAppliedRows(allocator, applied_rows); for (migrations) |migration| { const row = zug.findApplied(applied_rows, migration.id) orelse { setBaselineDiag(options, migration.id, "baseline migration was not recorded"); return zug.Error.BaselineIncomplete; }; if (row.dirty) { setBaselineDiag(options, migration.id, "baseline migration is dirty"); return zug.Error.DirtyMigration; } var checksum_buf: [16]u8 = undefined; const expected = migration.checksumHex(&checksum_buf); if (!std.mem.eql(u8, row.checksum, expected)) { setBaselineDiag(options, migration.id, "baseline migration checksum changed"); return zug.Error.ChecksumMismatch; } } } fn applyOne( allocator: std.mem.Allocator, conn: anytype, migration: zug.Migration, options: zug.Options, ) !void { var checksum_buf: [16]u8 = undefined; const checksum = migration.checksumHex(&checksum_buf); try insertMigration(allocator, conn, options.table_name, migration, checksum, true); errdefer markDirty(allocator, conn, options.table_name, migration.id, true) catch {}; if (migration.transactional) try conn.exec("BEGIN", .{}); errdefer if (migration.transactional) conn.exec("ROLLBACK", .{}) catch {}; var executed_body = false; var statement_index: usize = 0; if (migration.sql) |sql| { var iter = StatementIterator.init(sql); while (iter.next()) |stmt| { conn.exec(stmt, .{}) catch |err| { zug.setDiag(options, migration.id, statement_index, zug.preview(stmt), "statement failed"); return err; }; statement_index += 1; } executed_body = statement_index > 0; } if (migration.statements.len > 0) { for (migration.statements) |stmt| { const trimmed = std.mem.trim(u8, stmt, " \t\r\n"); if (trimmed.len == 0) continue; conn.exec(trimmed, .{}) catch |err| { zug.setDiag(options, migration.id, statement_index, zug.preview(trimmed), "statement failed"); return err; }; statement_index += 1; executed_body = true; } } if (!executed_body and migration.up == null) { zug.setDiag(options, migration.id, 0, "", "migration has no SQL or callback"); return zug.Error.MissingMigrationBody; } if (migration.up) |up| { try up(context(allocator, conn, migration)); } if (migration.transactional) try conn.exec("COMMIT", .{}); try markDirty(allocator, conn, options.table_name, migration.id, false); } fn ensureMigrationsTable(allocator: std.mem.Allocator, conn: anytype, table_name: []const u8) !void { const sql = try std.fmt.allocPrint(allocator, \\CREATE TABLE IF NOT EXISTS {s} ( \\ id TEXT PRIMARY KEY, \\ name TEXT NOT NULL, \\ checksum TEXT NOT NULL, \\ class TEXT NOT NULL, \\ dirty INTEGER NOT NULL DEFAULT 0, \\ applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP \\) , .{table_name}); defer allocator.free(sql); try conn.exec(sql, .{}); } fn applied(allocator: std.mem.Allocator, conn: anytype, table_name: []const u8) ![]zug.Applied { const sql = try std.fmt.allocPrint(allocator, "SELECT id, checksum, dirty FROM {s}", .{table_name}); defer allocator.free(sql); var rows = try conn.rows(sql, .{}); defer rows.deinit(); var out: std.ArrayListUnmanaged(zug.Applied) = .empty; errdefer { for (out.items) |row| { allocator.free(row.id); allocator.free(row.checksum); } out.deinit(allocator); } while (rows.next()) |row| { try out.append(allocator, .{ .id = try allocator.dupe(u8, row.text(0)), .checksum = try allocator.dupe(u8, row.text(1)), .dirty = row.int(2) != 0, }); } return try out.toOwnedSlice(allocator); } fn insertMigration( allocator: std.mem.Allocator, conn: anytype, table_name: []const u8, migration: zug.Migration, checksum: []const u8, dirty: bool, ) !void { try insertMigrationWithMode(allocator, conn, table_name, migration, checksum, dirty, .fail_on_conflict); } fn insertMigrationIgnore( allocator: std.mem.Allocator, conn: anytype, table_name: []const u8, migration: zug.Migration, checksum: []const u8, dirty: bool, ) !void { try insertMigrationWithMode(allocator, conn, table_name, migration, checksum, dirty, .ignore_conflict); } const InsertMode = enum { fail_on_conflict, ignore_conflict, }; fn insertMigrationWithMode( allocator: std.mem.Allocator, conn: anytype, table_name: []const u8, migration: zug.Migration, checksum: []const u8, dirty: bool, mode: InsertMode, ) !void { const verb = switch (mode) { .fail_on_conflict => "INSERT", .ignore_conflict => "INSERT OR IGNORE", }; const sql = try std.fmt.allocPrint( allocator, "{s} INTO {s} (id, name, checksum, class, dirty) VALUES (?, ?, ?, ?, ?)", .{ verb, table_name }, ); defer allocator.free(sql); try conn.exec(sql, .{ migration.id, migration.name, checksum, @tagName(migration.class), @as(i64, if (dirty) 1 else 0), }); } fn markDirty( allocator: std.mem.Allocator, conn: anytype, table_name: []const u8, id: []const u8, dirty: bool, ) !void { const sql = try std.fmt.allocPrint(allocator, "UPDATE {s} SET dirty = ? WHERE id = ?", .{table_name}); defer allocator.free(sql); try conn.exec(sql, .{ @as(i64, if (dirty) 1 else 0), id }); } fn setBaselineDiag(options: zug.BaselineOptions, migration_id: []const u8, message: []const u8) void { if (options.diagnostics) |d| { d.* = .{ .migration_id = migration_id, .message = message, }; } } fn context(allocator: std.mem.Allocator, conn: anytype, migration: zug.Migration) zug.Context { const Conn = @typeInfo(@TypeOf(conn)).pointer.child; return .{ .allocator = allocator, .migration = migration, .ptr = conn, .execFn = struct { fn exec(ptr: *anyopaque, sql: []const u8) !void { const typed: *Conn = @ptrCast(@alignCast(ptr)); try typed.exec(sql, .{}); } }.exec, }; } fn validateConn(comptime ConnPtr: type) void { const info = @typeInfo(ConnPtr); if (info != .pointer) @compileError("zug.sqlite.run expects a pointer to a connection"); const Conn = info.pointer.child; if (!@hasDecl(Conn, "exec")) @compileError("SQLite connection must provide exec(sql, args)"); if (!@hasDecl(Conn, "rows")) @compileError("SQLite connection must provide rows(sql, args)"); }