small migration runner for zig
Files
README.md

zug #

small SQLite migration runner for Zig 0.16.

zug is deliberately narrow: it applies ordered migrations, records what happened in the database, and stops when the database is in an unsafe state. it does not try to be an ORM, schema planner, query builder, or database client.

const zug = @import("zug");

try zug.sqlite.run(allocator, &conn, &migrations, .{
    .classes = zug.Classes.startup_only,
});

goals #

  • SQLite-first migrations for Zig 0.16
  • embedded SQL via @embedFile
  • checksum validation for already-applied migrations
  • dirty-state tracking so failed migrations block later ones
  • optional Zig callback migrations for cases SQL cannot express cleanly
  • a small SQLite-shaped connection boundary so applications keep ownership of connections
  • optional migration class filtering for applications that need separate migration phases

non-goals #

  • ORM/query builder
  • schema diffing
  • automatic down migrations
  • database driver ownership
  • remote database operational policy
  • deploy orchestration

status #

alpha. zug proper is SQLite-first.

zug is used in production by Zig services that run migrations against Turso through application-owned adapters:

  • pub-search adopted zug with 10 historical baseline migrations, avoided re-running expensive full-table backfills, and reduced schema initialization from roughly 5 minutes to under 1 second.
  • typeahead adopted zug for an ingester schema with FTS5 trigger maintenance, using explicit migration statements for trigger bodies with internal semicolons.

migration records #

zug creates a migration table named zug_migrations by default:

CREATE TABLE IF NOT EXISTS zug_migrations (
  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
);

An applied migration is treated as immutable. If its checksum changes, zug returns ChecksumMismatch. If a migration fails after it is marked dirty, future runs return DirtyMigration until the application repairs or resets the state explicitly.

migration bodies #

For simple SQL files, set .sql to a semicolon-separated script:

.{ .id = "001_initial", .sql = @embedFile("001_initial.sql") }

zug splits .sql on semicolons while ignoring semicolons inside single-quoted strings and comments. This is a convenience splitter, not a full SQL parser. Do not use .sql for trigger bodies, procedural blocks, functions, or other SQL forms that contain semicolons inside one logical statement.

For those cases, pass explicit statements:

.{ .id = "002_triggers", .statements = &.{
    \\CREATE TRIGGER actors_ai AFTER INSERT ON actors BEGIN
    \\  INSERT INTO actors_fts(rowid, handle)
    \\  VALUES (new.rowid, new.handle);
    \\END;
} }

Each entry in .statements is executed exactly as one statement, without splitting.

baselines #

When adopting zug on an existing database, the database may already represent some historical migrations. Use zug.sqlite.baseline to mark an explicit slice of migrations as already applied without running their SQL:

const baseline_count = 10; // frozen at the adoption point

if (try existingAppSchema(&conn)) {
    try zug.sqlite.baseline(allocator, &conn, migrations[0..baseline_count], .{});
}

try zug.sqlite.run(allocator, &conn, &migrations, .{});

baseline creates the migration table if needed, inserts missing baseline rows with INSERT OR IGNORE, then verifies every baseline row is present, clean, and checksum-matching before returning. This makes the operation resumable after a partial failure while still refusing corrupted or dirty history. If a row still cannot be verified after seeding, baseline returns BaselineIncomplete.

The caller chooses when to baseline. zug does not inspect application tables or decide whether a database is "fresh" or "existing"; that predicate belongs to the application. Keep the baseline slice fixed after adoption so later migrations still run normally on old restored databases.

On every call, baseline attempts INSERT OR IGNORE for each baseline migration before verification. That keeps the operation simple and resumable: a partially completed baseline can be retried without first inspecting which rows landed. The steady-state cost is one table create-if-needed, one insert-or-ignore attempt per baseline migration, and one read of the migration table for verification. run then performs its normal read of the migration table. This is intentional; the APIs stay independent and ownership of cached row state does not leak across calls.

connection contract #

Applications keep ownership of their database client. zug.sqlite.run accepts any pointer whose child type provides:

pub fn exec(self: *Conn, sql: []const u8, args: anytype) !void;
pub fn rows(self: *Conn, sql: []const u8, args: anytype) !Rows;

Rows must provide next() ?Row and deinit(), and each row must provide text(index) []const u8 and int(index) i64.

Adapters should be prepared for the argument shapes zug binds today:

  • u8 string slices and string-like values for ids, names, checksums, and class tags
  • i64 for the dirty flag

In Zig 0.16, string literals and @tagName(enum_value) are not always exact []const u8 values; they may be pointer-to-array string types such as *const [N:0]u8. Adapter tests should include those shapes rather than only pre-coerced slices.

transactions #

Migrations are non-transactional by default. If a migration sets .transactional = true, zug wraps it with BEGIN, ROLLBACK, and COMMIT through the same exec method used for normal migration statements.

That requires the underlying connection to preserve transaction state across separate exec calls. Plain SQLite connections usually do. HTTP or pipeline database clients may not if each exec uses a separate remote connection. For those clients, leave migrations non-transactional and rely on zug's dirty state to stop after a partial failure.

migration classes #

Migrations default to .startup. Applications may mark some migrations as .maintenance and choose which classes to run:

try zug.sqlite.run(allocator, &conn, &migrations, .{
    .classes = zug.Classes.startup_only,
});

This is only a filter. zug does not assign operational meaning to a class.

tests #

zig build test
zig build smoke
zig build sqlite-integration

the smoke test uses an in-memory SQLite-shaped connection, so it does not need sqlite or network access. the SQLite integration test uses zqlite as a lazy development dependency.

prior art #

zug borrows conservative migration-runner behavior from established tools:

  • golang-migrate: strict dirty-state handling and small database drivers
  • sqlx migrate: applied migration checksums and embedded migrations
  • refinery: embedded SQL/code migrations
  • goose: SQL migrations plus host-language migration functions
  • zmig: Zig 0.16 SQLite migration runner with embedded migrations

see docs/prior-art.md.

license #

MIT. see LICENSE.