migrate

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

README

go-migrate's folded turquoise swift

go-migrate

Run versioned SQL migrations from a standalone CLI, or embed the runner in a Go application. go-migrate supports PostgreSQL, MySQL/MariaDB, SQLite, SQL Server, Oracle Database and IBM Db2 LUW. Preview the SQL, then require its plan ID at deployment to check the plan, database and schema under the migration lock.

Latest release Integration statement coverage Go Reference

go install github.com/go-gen-ecosystem/go-migrate/cmd/gomigrate@latest

Why go-migrate

The table compares built-in capabilities in three pinned releases. A dash means we found no built-in equivalent for that row.

Capability go-migrate v1.0.1 golang-migrate v4.20.1 goose v3.30.1
Versioned SQL migrations Yes Yes Yes
SQL and registered Go functions in one version sequence Library or custom binary — Library or custom binary
Apply missing versions out of order Opt-in — Opt-in
Substitution inside SQL Configured placeholders — Opt-in ENVSUB
Read migrations directly from Amazon S3 in the stock CLI — Yes —
SQLite without CGO on Linux amd64 Stock build Custom build with the sqlite driver Stock build
Detect edits to applied versioned Up SQL by checksum Yes — —
Repeat SQL when its checksum changes Yes — Unversioned mode reruns files without a checksum check
Migration selection Contexts, labels, preconditions and rollback tags Target version or step count Provider can exclude versions or filenames
Named SQL callbacks around an Up run Yes — —
Require a reviewed SQL plan bound to the database and schema --expect-plan — —
Offline SQL risk linting Rules vary by dialect — validate checks migration structure
Cross-process locking Engine-specific, including a file lock for disk-backed SQLite Native locks on PostgreSQL, MySQL and SQL Server. SQLite guard is per driver instance Opt-in provider locks, including PostgreSQL and MySQL
Automation CLI JSON results, error codes and bundled MCP server Typed library errors and logger interface Typed provider results, partial errors and structured logging

For transactional SQL migrations on PostgreSQL, SQLite and SQL Server, go-migrate and goose can commit the change and its history row in the same transaction. golang-migrate records a dirty version, executes the migration, then marks the version clean separately. Its force V command lets an operator set the version and clear dirty state after checking the database. go-migrate execution · golang-migrate execution and recovery · goose transactional SQL

Packaging and feature comparisons use the tagged source and build configuration. golang-migrate release drivers · goose SQL annotations · goose SQLite driver · goose release build

SQLite allocations per 100 migrations

Each operation constructs a library runner and applies 100 migrations to a fresh SQLite database. Each migration creates a table and inserts one row. All three use the same SQL bodies and pure-Go driver (modernc.org/sqlite v1.62.0), with WAL and synchronous=OFF. The table shows medians of six samples per configuration on Linux/amd64, Go 1.26.11, Intel Core Ultra 9 285HX. B/op is cumulative Go heap allocation per batch. Benchmark source

Library configuration Allocated per batch Allocations per batch
go-migrate v1.0.1, default 727.8 KiB 10,873.5
golang-migrate v4.20.1, default 10.66 MiB 9,420
goose v3.30.1, default 1.14 MiB 8,547
golang-migrate v4.20.1, 4 KiB buffer 892.2 KiB 9,361

At defaults, go-migrate allocated the fewest bytes and goose made the fewest allocations. The golang-migrate result was sensitive to its 100,000-byte buffer per migration. The fourth row changes only that setting. Larger SQL files, remote sources and durable storage are different workloads. golang-migrate buffer implementation

Samples and reproduction

Each column lists bytes allocated per batch for the six samples, in execution order.

Sample go-migrate golang-migrate goose golang-migrate, 4 KiB
1 754,551 11,181,571 1,194,601 918,816
2 744,524 11,180,188 1,194,292 911,948
3 747,631 11,182,817 1,194,418 913,354
4 742,457 11,181,530 1,194,792 916,509
5 743,558 11,180,337 1,194,205 913,784
6 745,914 11,180,937 1,194,240 912,850

Start in a disposable checkout of v1.0.1. Go 1.26.11 needs to refresh the tagged benchmark module's go.mod and go.sum, which is why the command uses -mod=mod.

cd benchmarks/compare
GOWORK=off CGO_ENABLED=0 GOTOOLCHAIN=go1.26.11 go test -mod=mod -run '^$' -bench '^BenchmarkUp100_' -benchmem -count=6 .

For the fourth row, add these lines at the start of BenchmarkUp100_GolangMigrate in that checkout and repeat the command with -bench '^BenchmarkUp100_GolangMigrate$'.

old := gm.DefaultBufferSize
gm.DefaultBufferSize = 4096
defer func() { gm.DefaultBufferSize = old }()

Quick start

gomigrate init                       # .gomigrate.yaml + migrations/
gomigrate create add_users           # migrations/20261116120000_add_users.sql
gomigrate lint                       # risky SQL? (no database needed)
gomigrate up --sql                   # dry run: the exact SQL that would run, and its plan ID
gomigrate up --expect-plan <id>      # apply exactly the reviewed plan, or fail with plan_changed
gomigrate status                     # table; -o json for scripts
gomigrate down                       # roll back the last one (--steps, --to, --to-tag, --all)
-- +migrate Up
CREATE TABLE users (id INTEGER PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE);

-- +migrate Down
DROP TABLE users;

Library

//go:embed migrations
var migrations embed.FS

dir, _ := fs.Sub(migrations, "migrations")
m, err := migrate.New(db, "postgres", migrate.WithFS(dir)) // malformed files fail here, not mid-run
if err != nil {
	return err
}
_, err = m.Up(ctx)
  • Migrator methods:
    • apply and roll back: Up, UpTo, Down(ctx, migrate.DownTarget{Steps: 1}) (or To: "3", or Tag: "v1"), Redo;
    • read-only: Plan, PlanDown, PlanRepair, PlanID, Statements, Callbacks, Status, Validate, Lint, Migrations;
    • history administration: Repair(ctx, migrate.RepairTarget{Migration: "3", Action: migrate.RepairClearFailed}), MarkApplied, Baseline, Tag. To accept deliberate checksum drift, use migrate.RepairAcceptChecksum for that version. Bare Repair(ctx) returns ErrInvalidArgument and changes nothing.
  • Approved plans: m.Up(ctx, migrate.ExpectPlan(id)) runs only if the plan, computed again under the lock, still has the ID that was reviewed; otherwise it fails with ErrPlanChanged and runs nothing.
  • Options:
    • WithFS, WithGoMigrations, WithTable, WithLockWait;
    • WithLogger (halolog);
    • WithPlaceholders, WithContexts, WithLabels, WithBaselineOnMigrate;
    • WithAllowOutOfOrder, WithAllowMissing, WithHooks, WithInstalledBy.
  • Without a database: migrate.Lint(dialect, opts...) analyzes migrations with no connection.
  • Errors: every error works with errors.Is, and migrate.ErrorCodes(err) gives stable codes.
  • Concurrency: a Migrator is immutable after New and safe for concurrent use.

Migration files

File Meaning
001_users.sql, V1.2__index.sql Versioned SQL with -- +migrate Up and Down markers. Also accepts goose Up, Down, StatementBegin, StatementEnd and NO TRANSACTION annotations.
2024…_seed.up.sql + .down.sql versioned pair (golang-migrate layout)
R__views.sql repeatable: re-applied whenever it changes, and after rollbacks
beforeMigrate.sql, afterEachMigrate__x.sql, … SQL callbacks (Flyway names)

Directives:

-- +migrate Up notransaction                   -- e.g. CREATE INDEX CONCURRENTLY
-- +migrate Context dev,test                   -- run only with --context dev or test
-- +migrate Labels billing                     -- run only with --label billing
-- +migrate DBMS postgres                      -- run only on PostgreSQL
-- +migrate RunAlways                          -- repeatable: run on every up
-- +migrate Precondition onFail=MARK_RAN expect=0 SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'legacy'
-- +migrate Lint ignore=drop-table             -- accept a reviewed lint finding
-- +migrate StatementBegin / StatementEnd      -- keep a block as one statement

Supporting rules:

  • Placeholders: ${name} is replaced from --placeholder name=value or the placeholders: config. Built-ins are ${migrate:dialect}, ${migrate:table} and ${migrate:user}.
  • Versions compare numerically: 9 < 10, 1.9 < 1.10, 001 == 1 == 1.0.
  • SQL checksums cover the Up section. They normalize line endings, a leading BOM and insignificant whitespace outside literals, and preserve statement-block boundaries.
  • Preconditions: HALT fails the run, MARK_RAN records the migration without running it, and CONTINUE leaves it pending. Plans flag such migrations as conditional.
  • Callbacks appear in --sql plans (they run even when nothing is pending), are covered by the plan ID and are linted.

SQL Server

Use sqlserver as the dialect or a sqlserver:// URL in GOMIGRATE_DSN. A library caller opens its *sql.DB using the sqlserver driver registered by github.com/microsoft/go-mssqldb. The CLI includes that driver and remains CGO-free. Choose the target database with the URL's database parameter or the YAML database.name field. The CLI enables TLS and verifies the server certificate by default. Supply driver TLS options via the URL or database.params. A disposable local fixture with a self-signed certificate can set trustservercertificate=true.

Each migration direction runs as a T-SQL batch by default. Put GO on its own line to begin a new batch. A trailing -- comment is allowed. GO inside a quoted identifier, string, or block comment stays in the SQL. Use separate batches when a statement such as CREATE PROCEDURE must be first in its batch. GO N repetition and SQLCMD commands such as :r are outside the supported script format. StatementBegin/StatementEnd can also set explicit batch boundaries. The text dry run prints GO between batches and the JSON plan lists the exact payload of each batch.

SQL Server 2022 is the conformance target. The migration login needs access to the configured history schema and permission to create and modify history and application objects there. An unqualified history table uses the login's default schema. See the SQL Server example.

Oracle Database

Use the oracle dialect or an oracle://user:password@host:port/service URL in GOMIGRATE_DSN. The YAML database.name field identifies the Oracle service. The CLI bundles Oracle's native-Go oracledb driver and uses password authentication. The driver requires Go 1.26.9 and keeps the CLI CGO-free. Library callers can register and open oracledb themselves through database/sql. The driver is distributed under the Universal Permissive License 1.0.

The CLI selects TCPS on port 2484 by default and requests certificate-chain and server-identity verification. Set wallet_location or ssl_server_cert_dn as needed through the URL or database.params. An isolated Oracle Free test instance can use protocol=tcp to connect on port 1521. The conformance fixture uses password authentication over TCP on a private network. It targets Oracle AI Database 26ai Free and connects to the FREEPDB1 service.

A history table with no explicit schema uses the session's initial current schema. The tool folds ordinary configured identifiers to uppercase as Oracle does for unquoted names. The migration user needs permission to create and modify its history and application objects and an EXECUTE grant on SYS.DBMS_LOCK. Oracle releases the migration lock when the physical session ends. Use a driver configuration that fails the run on session loss.

Ordinary SQL uses semicolon separators. Wrap Oracle PL/SQL blocks and stored routines in -- +migrate StatementBegin and -- +migrate StatementEnd. Keep the final END; and omit the SQL*Plus slash command. Oracle q'[...]' and nq'[...]' literals can contain semicolons and newlines. See the Oracle example.

IBM Db2 LUW

Use the db2 dialect or a db2://user:password@host:port/database URL in GOMIGRATE_DSN. The CLI bundles the independent, MIT-licensed go-db2 driver and remains CGO-free. Library callers can register the db2 driver and supply a database/sql pool. The conformance target is IBM Db2 Community Edition 12.1.5.0 on Linux x86-64 with the default database collation.

The CLI enables certificate-verified TLS and defaults to port 50001. Provide the instance's TLS listener port and ssl_ca if you use a private CA (tls and ssl_ca can also be set in database.params). An isolated fixture can opt in to unencrypted TCP with tls=false&allow_plaintext_auth=true. The CLI supports username and password authentication.

Db2 history identifiers use uppercase names for ordinary unquoted identifiers. An unqualified history table uses the initial current schema. The migration login needs permission to create and modify its history and application objects and EXECUTE on the SYSIBMADM.DBMS_LOCK module. Use Db2 LUW 12.1.3 or newer with the Db2 native DBMS_LOCK module installed. Regular schema migrations run in a transaction. Use notransaction for statements that cannot run in one. Wrap Db2 SQL PL routines or compound statements in StatementBegin and StatementEnd. Keep the semicolons inside the block and omit CLP terminators such as @. See the Db2 example.

Safety model

  • Locking: a cross-process lock scoped to the configured migration history.
    • PostgreSQL and MySQL: pg_advisory_lock / GET_LOCK, which the server releases if the process dies.
    • SQL Server: a session-owned sp_getapplock per database. Distinct history tables in the same database share that lock so aliases of a table under a case-insensitive or accent-insensitive collation cannot bypass it.
    • Oracle: an exclusive DBMS_LOCK session lock per schema and history table that survives Oracle DDL commits.
    • Db2: a numeric SYSIBMADM.DBMS_LOCK session lock derived from the schema and history table. Db2 keeps the lock across commits and releases it when the session ends. Histories that hash to the same ID serialize.
    • SQLite: a run-lifetime OS lock on <database>.gomigrate-<history-table>.lock beside the database file, with a fenced lease row. The containing directory must allow creation of that coordination file, and each migrator must be able to open it. Keep the file in place while any migrator might use it. In-memory SQLite databases coordinate within the process.
    • After a SQLite process exits, the OS lock is released and an abandoned lease can be reclaimed once it expires. Drain older versions before rolling out the SQLite lock change so all running migrators use the same coordination protocol.
    • Ten replicas can run up at boot, and each migration still runs exactly once.
  • One connection per run.
    • All statements run on the lock's connection, so one-connection pools work.
    • If the session is lost, the run fails instead of continuing unprotected.
    • History writes use the schema selected before the run. SQL Server also qualifies them with the starting database, so SET search_path or USE in a migration cannot redirect history writes.
    • Session-lock connections are discarded afterwards, never returned to the pool.
  • Atomicity.
    • PostgreSQL, SQLite, SQL Server and Db2 normally commit each migration with its history row. Mark SQL Server statements that require autocommit, such as CREATE DATABASE, with notransaction.
    • MySQL, Oracle, and migrations marked notransaction commit a dirty row first. Oracle DDL commits implicitly. A partial failure blocks further runs. Restore the schema by hand, then use repair MIGRATION --clear-failed if you undid the change, or mark-applied VERSION if you completed the versioned migration.
    • Run-level SQL callbacks (beforeMigrate, afterMigrate, afterMigrateError) run on the same session as the migrations, outside their transactions. Before the first callback runs, go-migrate commits a recovery marker. It clears the marker only after the whole run succeeds. An interrupted run can leave committed callback effects even if no migrations were pending. While the marker remains, status reports callback_recovery_required separately from migration rows, and validate, up, down and redo report that recovery is required. Successful runs can run the callbacks again on the next up.
  • Validation before execution: drift, missing and out-of-order migrations, unknown targets, the baseline floor and irreversible rollbacks are all checked before any SQL runs.
  • Approval binds execution to the target: CLI and MCP plan IDs cover the resolved database, history table, active schema or search path, and the exact plan (including callbacks and any automatic baseline). --expect-plan (CLI) and plan_id (MCP) check the approval under the migration lock before changing history or running migration SQL. Reissue IDs from older releases. Library callers can opt into the same check with PlanWithID or PlanDownWithID and ExpectTargetPlan; PlanID and ExpectPlan still check plan content only.
  • Approval scope: IDs use metadata from the live session and the configured network route. A PostgreSQL restart requires a fresh plan. SQLite binds canonical file paths and ordered attachment names; it cannot detect a file replaced at the same path. Re-plan after replacing a file. In-memory or temporary SQLite targets cannot receive a target-bound ID.
  • Read-only means read-only: status, validate, lint and dry runs never create tables.
  • No connection secrets in output: DSNs and passwords never appear in errors or logs. Placeholder values do appear in --sql plans and SQL excerpts, as they are part of the SQL; do not put secrets in placeholders.

Lint

gomigrate lint needs no database. Its findings, with the rule IDs:

Severity Rule IDs
error add-not-null-without-default, concurrently-in-transaction, sqlite-unsupported-alter
warning index-not-concurrent, column-type-change, foreign-key-not-valid, check-not-valid, set-not-null, rename, drop-table, drop-schema, drop-column, truncate, unbounded-write, full-table-rewrite
info missing-lock-timeout, irreversible

How it works:

  • Rules know the dialect.
  • ALTER TABLE is split into its actions, so ADD a int DEFAULT 0, ADD b int NOT NULL is judged per column.
  • Serial, identity and generated columns count as defaulted; quoted and schema-qualified names are matched.
  • They ignore text inside strings and comments.
  • They skip tables created in the same migration.
  • -o github turns findings into pull-request annotations.
  • --fail-on error|warning|info|never exits with code 3.

AI agents (MCP)

claude mcp add gomigrate -- gomigrate mcp
  • Read-only tools: status, validate, plan (with SQL) and lint.
  • create_migration: writes a migration file and validates and lints it. Use the typed no_transaction and sequential inputs. Embedded -- +migrate and -- +goose directives are rejected.

By default, apply and rollback can preview a plan. In the operator's trusted environment, preview the intended change against the intended database (for example, gomigrate -o json up --sql). Review the SQL, callbacks and destination, then pass that preview's plan_id to a new MCP server using the same configuration and the corresponding operation:

gomigrate mcp --approve-apply "$REVIEWED_PLAN_ID"
gomigrate mcp --approve-rollback "$REVIEWED_ROLLBACK_PLAN_ID"

The client must supply confirm: true and the matching plan_id. A matching request consumes the grant before it opens a database connection, even if the attempt fails or is cancelled. The runner also checks the current target and plan under the migration lock. Overriding lint errors requires both the operator's --allow-lint-errors on an apply grant and the client's allow_lint_errors: true.

The launcher controls who can grant approval. Keep its configuration and database credentials outside the agent's control and record the review there if you need an audit of the approver. Each process start issues a new grant, so use a one-shot launch for execution. Keep the persistent planning server free of approval flags. After an interrupted attempt, inspect the database and review a fresh plan before launching again.

CI/CD

# Pull requests: annotate risky SQL, fail on errors
- uses: go-gen-ecosystem/go-migrate@v1
  with: { command: lint, driver: postgres }

# Deploy: show the plan, then apply exactly that plan
- uses: go-gen-ecosystem/go-migrate@v1
  with: { command: up --sql, dsn: "${{ secrets.DATABASE_URL }}" }
- uses: go-gen-ecosystem/go-migrate@v1
  with: { command: "up --expect-plan ${{ vars.APPROVED_PLAN_ID }}", dsn: "${{ secrets.DATABASE_URL }}" }
  • JSON envelope: every command accepts -o json and prints one envelope, {ok, command, data | error{code, codes, message}}. A run that fails part-way still reports what it applied in data.
  • Exit codes:
Code Meaning
0 ok
1 error
2 pending migrations (status --fail-on-pending)
3 lint findings at the --fail-on level
  • Container image: docker build -t gomigrate . produces a 27 MB distroless image.

Configuration

.gomigrate.yaml, where values may use ${ENV} or ${ENV:-default}:

database:
  driver: postgres            # inferred from the DSN when omitted
  dsn: ${DATABASE_URL}        # or host, port, name, user, password, sslmode, params
migrations:
  dir: migrations
  table: gomigrate_history    # or schema.table
  lock_timeout: 5m
  contexts: [prod]
  placeholders: { owner: app_owner }
  baseline_on_migrate: ""     # e.g. "5" to adopt an existing schema
  allow_out_of_order: false
  allow_missing: false

Settings are applied in this order of precedence:

  1. flags;
  2. GOMIGRATE_DSN / GOMIGRATE_DRIVER;
  3. DATABASE_URL;
  4. the config file;
  5. defaults.

Additional rules:

  • A DSN that overrides the file brings its own driver.
  • An explicit --config must exist, and DATABASE_URL never retargets it.
  • Prefer the environment over --dsn for credentials, because command lines are visible to other processes.

Commands

Command Purpose
init write a config and migrations/
create NAME [--seq] [--pair] create a migration
lint [--fail-on LEVEL] static risk analysis
up [--to V] [--dry-run | --sql] [--expect-plan ID] apply pending migrations
down [--steps N | --to V | --to-tag T | --all] [--dry-run | --sql] [--expect-plan ID] roll back
redo roll back and re-apply the last migration
status [--fail-on-pending] show state; doubles as a CI gate
validate check drift, missing, out-of-order and failed migrations, and callback recovery
repair MIGRATION (--clear-failed | --accept-checksum) [--dry-run] preview or change one history row
mark-applied V record V as applied without running it
baseline --version V adopt an existing database
tag NAME tag the current version
mcp serve AI agents over the Model Context Protocol

repair 42 --clear-failed removes version 42's failed history row after you undo its partial changes. For a failed repeatable, pass the label from status, for example repair 'R__refresh views' --clear-failed. For run-level callbacks, inspect which effects committed and reconcile them so that it is safe to run the callbacks again. Preview the marker removal with repair C:run-callbacks --clear-failed --dry-run, then omit --dry-run to remove only that marker. Repair any failed migrations separately. After a connection loss during finalization, check status and callback effects before retrying: the database may already have committed the marker removal. repair 42 --accept-checksum accepts drift for version 42 only; prefer restoring the applied file and writing a new migration. Changed repeatables run again on up rather than accepting a checksum through repair. Add --dry-run to preview the selected row and, for checksum changes, compare its stored and proposed checksums. Repair rechecks the selected row under the migration lock and updates history in a transaction. It runs no migration SQL.

Global flags:

Purpose Flags
Connection --config, --dsn, --driver
Migrations --dir, --table, --context, --label, --placeholder, --baseline-on-migrate
Output -o text|json
Logging --log-level, --log-format

Development

make check             # lint + tests + govulncheck
make test-race         # race detector (needs cgo)
make test-integration  # conformance on real PostgreSQL 17 and MySQL 8.4 (Docker)
make bench             # benchmarks; see also benchmarks/compare

To include SQL Server in the normal suite, set GOMIGRATE_TEST_SQLSERVER_DSN to an isolated test instance with permission to create and drop disposable databases, then run go test ./.... Set GOMIGRATE_TEST_SQLSERVER_SELF_SIGNED=1 for a self-signed fixture to also verify the default certificate rejection. Repository owners can enable the SQL Server Developer Edition CI job by setting GOMIGRATE_CI_SQLSERVER_ACCEPT_EULA to Y after accepting Microsoft's license terms for that CI service.

Set GOMIGRATE_TEST_ORACLE_DSN to include Oracle in go test ./.... Use an isolated Oracle Database Free PDB with a fixture administrator that can create and drop disposable users and grant EXECUTE on SYS.DBMS_LOCK. Test users receive only the schema privileges needed by the suite and are dropped after each case.

Set GOMIGRATE_TEST_DB2_DSN to an isolated Db2 fixture administrator URL that can create and drop temporary schemas and flush the fixture's dynamic package cache. The fixture needs the SYSTOOLSPACE tablespace for SYSPROC.ADMIN_DROP_SCHEMA. Set GOMIGRATE_TEST_DB2_APP_DSN to the low-privilege migration user's URL on the same database. To also run the TLS rejection checks, use a fixture certificate signed by its own CA and set GOMIGRATE_TEST_DB2_TLS_MISMATCH_HOST to an alias that resolves to the fixture and is absent from its certificate.

Licensed under Apache-2.0.

Documentation

Overview

Package migrate applies versioned SQL and Go migrations to PostgreSQL, MySQL/MariaDB, SQLite, SQL Server, Oracle Database, and IBM Db2 LUW.

A Migrator is built once from a *sql.DB and a migration source and is then immutable and safe for concurrent use. Runs that change the database (Up, Down, Repair, Baseline) hold a cross-process lock: a session advisory lock on PostgreSQL, MySQL, SQL Server, Oracle, and Db2 and a run-lifetime file lock with a lease on SQLite. In-memory SQLite databases coordinate within the process. Transactional migrations and their history row commit together. A failed nontransactional migration leaves a "dirty" row that blocks further runs. Restore the schema by hand before clearing that row with Repair or completing it with MarkApplied.

The package itself imports no SQL driver; register the one you use, e.g.

import _ "github.com/jackc/pgx/v5/stdlib" // "pgx"
import _ "github.com/go-sql-driver/mysql" // "mysql"
import _ "github.com/microsoft/go-mssqldb" // "sqlserver"
import _ "github.com/oracle/go-oracledb/v26/oracle" // "oracledb"
import _ "github.com/go-db2/go-db2"                // "db2"
import _ "modernc.org/sqlite"             // "sqlite", pure Go
Example

Apply the example migrations to an in-memory SQLite database. In an application, pass an embed.FS (via fs.Sub) instead of os.DirFS.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"

	migrate "github.com/go-gen-ecosystem/go-migrate"
	_ "modernc.org/sqlite"
)

func main() {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(1) // one shared in-memory database

	m, err := migrate.New(db, "sqlite", migrate.WithFS(os.DirFS("examples/migrations")))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	res, err := m.Up(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, a := range res.Applied {
		fmt.Println("applied", a.Source)
	}

	st, err := m.Status(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("current version:", st.Current, "pending:", st.Pending)

	plan, err := m.PlanDown(ctx, migrate.DownTarget{Steps: 1})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("down 1 would revert:", plan[0].Version)
	if err := db.Close(); err != nil {
		log.Fatal(err)
	}

}
Output:
applied 0001_create_users.sql
applied 0002_create_posts.up.sql | 0002_create_posts.down.sql
applied 0003_add_users_active.sql
applied R__user_post_counts.sql
current version: 3 pending: 0
down 1 would revert: 3

Index

Examples

Constants

View Source
const (
	// DefaultTable is the default history table. It is deliberately distinct
	// from golang-migrate's schema_migrations so both tools can coexist.
	DefaultTable = "gomigrate_history"
	// DefaultLockWait is how long a run waits for another to finish.
	DefaultLockWait = 5 * time.Minute
)

Defaults.

View Source
const RunCallbacksRepairKey = "C:run-callbacks"

RunCallbacksRepairKey is the repair target for an interrupted run-level SQL callback sequence. It is reserved and cannot be a migration version.

Variables

View Source
var (
	// ErrDirty means a non-transactional migration or run-level callback may
	// have changed the database. For a migration, bring the schema by hand to
	// either side, then use Repair with RepairClearFailed or MarkApplied.
	ErrDirty = errors.New("database is dirty: a migration failed part-way; " + dirtyGuidance)
	// ErrCallbackRecoveryRequired also matches ErrDirty. Inspect the callback
	// effects, then clear RunCallbacksRepairKey only when another run is safe.
	ErrCallbackRecoveryRequired error = callbackRecoveryError{}
	// ErrCommitOutcomeUnknown means a migration transaction may have committed
	// even though Commit returned an error. The migration and its history change
	// share that outcome. Inspect them on the writable database and make a
	// fresh plan before retrying.
	ErrCommitOutcomeUnknown = errors.New("transaction commit outcome unknown; reconnect to the writable database, inspect the schema and migration history, and generate a fresh plan before retrying")
	// ErrBelowBaseline means a rollback target lies below the baseline,
	// which cannot be rolled back.
	ErrBelowBaseline = errors.New("target version is below the baseline")
	// ErrChecksumMismatch means an applied migration file was edited.
	ErrChecksumMismatch = errors.New("applied migration was modified")
	// ErrMissingMigration means the database has a version that no longer
	// exists in the migration source.
	ErrMissingMigration = errors.New("applied migration is missing from the source")
	// ErrOutOfOrder means a pending migration has a lower version than the
	// latest applied one; enable WithAllowOutOfOrder to apply it anyway.
	ErrOutOfOrder = errors.New("pending migration is older than the latest applied version")
	// ErrTransactionControl means a migration that runs in a transaction
	// contains BEGIN/COMMIT/ROLLBACK; mark it "-- +migrate Up notransaction".
	ErrTransactionControl = errors.New("transaction control statement in a transactional migration (use notransaction)")
	// ErrUnresolvedPlaceholder means an SQL file references ${name} that was
	// not provided via WithPlaceholders.
	ErrUnresolvedPlaceholder = errors.New("unresolved placeholder")
	// ErrPreconditionFailed means a migration's precondition with
	// onFail=HALT did not hold; nothing of that migration ran.
	ErrPreconditionFailed = errors.New("precondition failed")
	// ErrTagNotFound means no applied migration carries the requested tag.
	ErrTagNotFound = errors.New("tag not found")
	// ErrInvalidArgument means a caller passed invalid or conflicting arguments.
	ErrInvalidArgument = errors.New("invalid argument")
	// ErrPlanChanged means the plan to execute no longer matches the one
	// approved with ExpectPlan or ExpectTargetPlan.
	ErrPlanChanged = errors.New("plan or target changed since it was approved")
	// ErrApprovalTarget means the resolved database and schema could not be
	// identified well enough to issue a target-bound approval.
	ErrApprovalTarget = dialect.ErrApprovalTarget
	// ErrInvalidVersion means a version is not numeric (digits, optionally dot-separated).
	ErrInvalidVersion = errors.New("invalid version")
	// ErrVersionNotFound means a requested target version does not exist.
	ErrVersionNotFound = errors.New("version not found")
	// ErrIrreversible means a migration that must be rolled back has no down section.
	ErrIrreversible = errors.New("migration has no down section")
	// ErrNotEnoughApplied means Down was asked to roll back more migrations than are applied.
	ErrNotEnoughApplied = errors.New("not enough applied migrations")
	// ErrBaselineNotEmpty means Baseline was called on a database with history.
	ErrBaselineNotEmpty = errors.New("baseline requires an empty history table")
	// ErrLockTimeout means another process held the migration lock for longer than the lock wait.
	ErrLockTimeout = dialect.ErrLockTimeout
	// ErrLockLost means the migration lock expired or was taken over while held.
	ErrLockLost = dialect.ErrLockLost
)

Sentinel errors. Use errors.Is to test for them; most are wrapped with the offending version.

View Source
var (
	ErrBadPrecondition     = script.ErrBadPrecondition
	ErrBadFileName         = source.ErrBadFileName
	ErrDuplicateVersion    = source.ErrDuplicateVersion
	ErrMissingUp           = source.ErrMissingUp
	ErrEmptyUp             = source.ErrEmptyUp
	ErrUpInDownFile        = source.ErrUpInDownFile
	ErrMisplacedDirective  = source.ErrMisplacedDirective
	ErrContentBeforeMarker = script.ErrContentBeforeMarker
	ErrDuplicateMarker     = script.ErrDuplicateMarker
	ErrUnbalancedBlock     = script.ErrUnbalancedBlock
	ErrUnknownDirective    = script.ErrUnknownDirective
	ErrTSQLBatch           = script.ErrTSQLBatch
	ErrPLSQLBlock          = script.ErrPLSQLBlock
	ErrSQLPLBlock          = script.ErrSQLPLBlock
	ErrUnsupportedDialect  = dialect.ErrUnsupported
	ErrInvalidIdentifier   = dialect.ErrInvalidIdentifier
	ErrHistoryRowNotFound  = history.ErrNotFound
)

Errors from loading migrations (New) and from the database layer, re-exported so callers can test for them with errors.Is.

Functions

func ErrorCodes

func ErrorCodes(err error) []string

ErrorCodes returns the stable codes of every known error in err's tree, in a fixed order, plus "migration_failed" when a migration's SQL or Go code failed. It returns nil for nil and ["error"] for anything unrecognised.

func LintRules

func LintRules() []string

LintRules lists every lint rule ID.

Types

type Applied

type Applied struct {
	Migration
	Duration time.Duration
	// MarkedRan is true when a precondition with onFail=MARK_RAN failed: the
	// migration was recorded as applied without running.
	MarkedRan bool
}

Applied is one migration executed by a run.

type Callback

type Callback struct {
	Event      string
	Source     string
	Statements []string
}

Callback is an SQL callback file and the statements it runs, after placeholder substitution. Event is its Flyway event name.

type Direction

type Direction int

Direction is the direction a migration runs in.

const (
	Up Direction = iota
	Down
)

Migration directions.

func (Direction) String

func (d Direction) String() string

type DownTarget

type DownTarget struct {
	// Steps rolls back the last Steps applied migrations, newest first.
	Steps int
	// To rolls back every migration with a version above To ("0": all).
	To string
	// Tag rolls back every migration applied after the one tagged Tag.
	Tag string
}

DownTarget selects what a rollback undoes. Set at most one field; the zero value rolls back the most recently applied migration.

type Event

type Event struct {
	Migration Migration
	Direction Direction
	// Duration and Err are set only for the After hook.
	Duration time.Duration
	Err      error
}

Event is passed to hooks around each migration.

type Executor

type Executor interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Executor runs SQL. It is satisfied by *sql.DB, *sql.Tx and *sql.Conn. Go migrations receive a *sql.Tx on databases with transactional DDL (PostgreSQL, SQLite) unless they set NoTx; on MySQL, or with NoTx, they receive the run's *sql.Conn and follow the dirty-row protocol (see ErrDirty).

type Finding

type Finding struct {
	Rule     string
	Severity string // "error", "warning" or "info"
	Message  string
	Hint     string
	// Version is the migration's Label; Source its file. For a callback
	// file, Version is empty and Event names the callback event.
	Version string
	Source  string
	Event   string
	// Statement is the 1-based Up statement, or 0 for the whole migration.
	Statement int
	SQL       string
}

Finding is one lint result: a risky or unsupported operation in a migration. Rule IDs are stable and can be suppressed per file with "-- +migrate Lint ignore=<rule>[,<rule>]".

func Lint

func Lint(dialectName string, opts ...Option) ([]Finding, error)

Lint statically analyzes every SQL migration for dialectName without a database: long exclusive locks, table rewrites, data loss, changes that break running application versions and unsupported syntax. Use it as a CI gate or to let an AI agent review a migration before it is applied.

type GoMigration

type GoMigration struct {
	Version     string
	Description string
	Up          func(ctx context.Context, ex Executor) error
	// Down is optional; without it the migration is irreversible.
	Down func(ctx context.Context, ex Executor) error
	// NoTx runs the migration outside a transaction.
	NoTx bool
}

GoMigration is a migration written in Go, for changes SQL alone cannot express (data backfills that call application code, conditional logic).

type Hooks

type Hooks struct {
	Before func(ctx context.Context, e Event) error
	After  func(ctx context.Context, e Event)
}

Hooks are optional callbacks around each migration. Before may veto a migration by returning an error. Hooks run while the lock is held.

type Info

type Info struct {
	Migration
	State State
	// The following are set only for migrations with a history row.
	InstalledOn   time.Time
	InstalledBy   string
	ExecutionTime time.Duration
	// Tag is the release tag on this migration, if any (see Migrator.Tag).
	Tag string
}

Info is a migration together with its state and history row (if any).

type Migration

type Migration struct {
	// Version is the canonical version ("" for repeatable migrations).
	Version     string
	Description string
	Repeatable  bool
	// Source is the file name(s), or "go" for a Go migration.
	Source string
	// Checksum is the SHA-256 of the normalized file content ("" for Go).
	Checksum   string
	NoTx       bool
	Reversible bool
	// Conditional is set when the migration has preconditions: a run may
	// skip it or record it without executing its SQL.
	Conditional bool
}

Migration describes one migration known to the Migrator.

func (Migration) Label

func (m Migration) Label() string

Label names the migration in logs and output: its version, or "R__<description>" for a repeatable migration.

type MigrationError

type MigrationError struct {
	Version   string
	Direction Direction
	// Statement is the 1-based index of the failing statement, or 0 if the
	// error is not tied to a statement (for example, during Commit).
	Statement int
	// SQL is the start of the failing statement, truncated.
	SQL string
	// Dirty is true when the failure left the database in a partial state
	// (non-transactional migration); see ErrDirty.
	Dirty bool
	Err   error
}

MigrationError identifies the migration and, when relevant, the statement associated with an error.

func (*MigrationError) Error

func (e *MigrationError) Error() string

func (*MigrationError) Unwrap

func (e *MigrationError) Unwrap() []error

Unwrap returns the underlying cause (and ErrDirty when Dirty is set).

type Migrator

type Migrator struct {
	// contains filtered or unexported fields
}

Migrator applies migrations to one database. Create it with New.

Migrator is a facade: each method validates its arguments and delegates to a focused component (catalog: what exists; planner: what to do; runner and maintenance: doing it under the lock; applier: one migration at a time).

func New

func New(db *sql.DB, dialectName string, opts ...Option) (*Migrator, error)

New builds a Migrator for db. dialectName is "postgres", "mysql", "sqlite", "sqlserver", "oracle", or "db2". Common driver aliases are accepted. The migration source is loaded and validated immediately, so malformed files and duplicate versions fail here rather than mid-run.

func (*Migrator) Baseline

func (m *Migrator) Baseline(ctx context.Context, version, description string) error

Baseline marks an existing database as being at version, so migrations up to and including it are treated as already applied. It requires an empty history table.

func (*Migrator) Callbacks

func (m *Migrator) Callbacks(dir Direction) []Callback

Callbacks returns the SQL callbacks a run in direction dir executes, in order: beforeMigrate once, beforeEachMigrate and afterEachMigrate around every migration, then afterMigrate on success or afterMigrateError on failure. They run even when no migration is pending. Rollbacks run none. PlanID covers them, so an edited callback invalidates an approval.

func (*Migrator) Down

func (m *Migrator) Down(ctx context.Context, t DownTarget, opts ...RunOption) (*Result, error)

Down rolls back the migrations selected by t, newest application first. It fails before changing anything if the selection is invalid, a selected migration was edited or is irreversible, or fewer migrations are applied than requested.

func (*Migrator) Lint

func (m *Migrator) Lint() []Finding

Lint analyzes this Migrator's SQL migrations (see the package-level Lint).

func (*Migrator) MarkApplied

func (m *Migrator) MarkApplied(ctx context.Context, version string) error

MarkApplied records version as applied without running it: for a dirty row whose migration you completed by hand (see ErrDirty), or to adopt a single change that already exists in the database. It is idempotent.

func (*Migrator) Migrations

func (m *Migrator) Migrations() []Migration

Migrations returns every known migration in execution order.

func (*Migrator) Plan

func (m *Migrator) Plan(ctx context.Context, target string) ([]Migration, error)

Plan returns what Up (target == "") or UpTo(target) would apply, without applying it, including the effect of WithBaselineOnMigrate. Use it for dry runs and bind an approval to it with PlanID and ExpectPlan.

func (*Migrator) PlanDown

func (m *Migrator) PlanDown(ctx context.Context, t DownTarget) ([]Migration, error)

PlanDown returns what Down(t) would roll back, without doing it.

func (*Migrator) PlanDownWithID

func (m *Migrator) PlanDownWithID(ctx context.Context, t DownTarget) ([]Migration, string, error)

PlanDownWithID returns the rollback plan and its target-bound approval ID on one session. Use the ID with ExpectTargetPlan.

func (*Migrator) PlanID

func (m *Migrator) PlanID(dir Direction, plan []Migration) string

PlanID fingerprints a plan returned by Plan or PlanDown: its direction and each migration's identity, checksum and exact statements. Pass it to ExpectPlan so the run fails with ErrPlanChanged unless it executes exactly what was approved. It returns an empty ID for an invalid direction.

func (*Migrator) PlanRepair

func (m *Migrator) PlanRepair(ctx context.Context, target RepairTarget) (*RepairPlan, error)

PlanRepair previews the selected history repair without taking a migration lock or making any writes. Repair checks the current state again when run.

func (*Migrator) PlanWithID

func (m *Migrator) PlanWithID(ctx context.Context, target string) ([]Migration, string, error)

PlanWithID returns the dry run and its target-bound approval ID. Both the plan and target are read on one session. Use the ID with ExpectTargetPlan.

func (*Migrator) Redo

func (m *Migrator) Redo(ctx context.Context) (*Result, error)

Redo rolls back the most recently applied migration and applies it again, under a single lock so no other run can interleave. The Result lists the re-applied migration.

func (*Migrator) Repair

func (m *Migrator) Repair(ctx context.Context, targets ...RepairTarget) (*RepairResult, error)

Repair applies exactly one explicit history change. Clear a failed row only after restoring the schema by hand; if you completed the migration, use MarkApplied instead. Clear RunCallbacksRepairKey only after inspecting callback effects and making another run safe. Repair never runs SQL from migrations or callbacks. A call without exactly one target returns ErrInvalidArgument without writing history.

func (*Migrator) Statements

func (m *Migrator) Statements(mig Migration, dir Direction) []string

Statements returns the SQL that mig runs in direction dir, after placeholder substitution, exactly as it would be executed (Liquibase updateSQL). Go migrations and unknown migrations return nil.

func (*Migrator) Status

func (m *Migrator) Status(ctx context.Context) (*Status, error)

Status reports every migration's state. It is read-only: it takes no lock and never creates the history table. Pending counts what Up would apply, excluding RunAlways repeatables (they run every time and are never "behind").

func (*Migrator) Tag

func (m *Migrator) Tag(ctx context.Context, tag string) error

Tag labels the most recently applied migration with tag (for example a release name), so DownToTag can return to this point later. Tags are unique: tagging again moves the tag.

func (*Migrator) Up

func (m *Migrator) Up(ctx context.Context, opts ...RunOption) (*Result, error)

Up applies every pending migration, then any new or changed repeatable migrations. Nothing pending is not an error: the Result is simply empty.

func (*Migrator) UpTo

func (m *Migrator) UpTo(ctx context.Context, version string, opts ...RunOption) (*Result, error)

UpTo applies pending migrations up to and including version. Repeatable migrations are not run.

func (*Migrator) Validate

func (m *Migrator) Validate(ctx context.Context) error

Validate reports, without changing anything, every problem that would make Up fail: dirty rows, modified or missing applied migrations, and out-of-order pending ones. It returns nil when Up could run.

type Option

type Option func(*options)

Option configures a Migrator.

func WithAllowMissing

func WithAllowMissing(allow bool) Option

WithAllowMissing tolerates applied versions that no longer exist in the source instead of failing with ErrMissingMigration.

func WithAllowOutOfOrder

func WithAllowOutOfOrder(allow bool) Option

WithAllowOutOfOrder applies pending migrations whose version is lower than the latest applied one (useful when feature branches merge late) instead of failing with ErrOutOfOrder.

func WithApprovalEndpoint

func WithApprovalEndpoint(endpoint string) Option

WithApprovalEndpoint adds a credential-free network endpoint identifier to target-bound plan IDs. This distinguishes routes to servers with identical reported names. Use the same endpoint identifier for preview and execution. Never supply a DSN or authentication material.

func WithBaselineOnMigrate

func WithBaselineOnMigrate(version string) Option

WithBaselineOnMigrate makes Up baseline at version first when the history table is empty but the schema already contains tables (Flyway baselineOnMigrate), so an existing database can adopt go-migrate in place.

func WithContexts

func WithContexts(contexts ...string) Option

WithContexts selects the active contexts (Liquibase contexts). A migration declaring "-- +migrate Context ..." runs only if one of its contexts is active; migrations without contexts always run. Without this option every migration runs.

func WithFS

func WithFS(fsys fs.FS) Option

WithFS loads SQL migrations from fsys, e.g. os.DirFS("migrations") or an embed.FS (use fs.Sub to point at a subdirectory).

func WithGoMigrations

func WithGoMigrations(ms ...GoMigration) Option

WithGoMigrations registers migrations written in Go. Their versions share one ordering with SQL migrations and must not collide with them.

Example

Go migrations run in the same ordered sequence as SQL files.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"

	migrate "github.com/go-gen-ecosystem/go-migrate"
	_ "modernc.org/sqlite"
)

func main() {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(1)

	backfill := migrate.GoMigration{
		Version:     "4",
		Description: "seed admin user",
		Up: func(ctx context.Context, ex migrate.Executor) error {
			_, err := ex.ExecContext(ctx, "INSERT INTO users (id, email, name) VALUES (1, 'admin@example.com', 'Admin')")
			return err
		},
		Down: func(ctx context.Context, ex migrate.Executor) error {
			_, err := ex.ExecContext(ctx, "DELETE FROM users WHERE id = 1")
			return err
		},
	}
	m, err := migrate.New(db, "sqlite",
		migrate.WithFS(os.DirFS("examples/migrations")),
		migrate.WithGoMigrations(backfill))
	if err != nil {
		log.Fatal(err)
	}
	if _, err := m.Up(context.Background()); err != nil {
		log.Fatal(err)
	}
	var posts int
	if err := db.QueryRow("SELECT posts FROM user_post_counts WHERE id = 1").Scan(&posts); err != nil {
		log.Fatal(err)
	}
	fmt.Println("admin has", posts, "posts")
	if err := db.Close(); err != nil {
		log.Fatal(err)
	}
}
Output:
admin has 0 posts

func WithHooks

func WithHooks(h Hooks) Option

WithHooks installs callbacks that run around each migration.

func WithInstalledBy

func WithInstalledBy(name string) Option

WithInstalledBy sets the value recorded in installed_by (default: OS user).

func WithLabels

func WithLabels(labels ...string) Option

WithLabels selects the active labels, with the same rules as WithContexts for migrations declaring "-- +migrate Labels ...".

func WithLockWait

func WithLockWait(d time.Duration) Option

WithLockWait sets the lock acquisition budget, including reserving and setting up the session (default DefaultLockWait). Zero or negative makes one attempt using the caller's context and returns ErrLockTimeout if held.

func WithLogger

func WithLogger(l halolog.Logger) Option

WithLogger sets the halolog logger used for progress and diagnostics (default: a discarding logger). A nil logger keeps the default.

func WithPlaceholders

func WithPlaceholders(values map[string]string) Option

WithPlaceholders enables ${name} substitution in SQL migrations, callbacks and preconditions (Flyway placeholders). Built-ins ${migrate:dialect}, ${migrate:table} and ${migrate:user} are available once enabled. An unresolved ${name} is a load error. Checksums are computed before substitution, so per-environment values never look like drift.

func WithTable

func WithTable(name string) Option

WithTable sets the history table ("name" or "schema.name").

type RepairAction

type RepairAction string

RepairAction selects one type of history repair.

const (
	// RepairClearFailed removes a failed row after inspecting and reconciling
	// the database by hand.
	RepairClearFailed RepairAction = "clear-failed"
	// RepairAcceptChecksum accepts deliberate drift for an applied version.
	RepairAcceptChecksum RepairAction = "accept-checksum"
)

type RepairPlan

type RepairPlan struct {
	RepairTarget
	State                       State
	StoredChecksum, NewChecksum string
	StoredKind, NewKind         string
}

RepairPlan describes a proposed history change. Migration is the canonical history key and State is the current state. Checksum and kind fields show the existing row and, for RepairAcceptChecksum, the proposed values.

type RepairResult

type RepairResult struct {
	// RemovedFailed is 1 when the selected failed row was removed.
	RemovedFailed int64
	// Realigned contains the selected version when its checksum was realigned.
	Realigned []string
}

RepairResult reports what Repair changed.

type RepairTarget

type RepairTarget struct {
	// Migration is a version or, for RepairClearFailed, a repeatable label
	// (R__<description>) or history key (R:<description>), or RunCallbacksRepairKey.
	Migration string
	Action    RepairAction
}

RepairTarget identifies exactly one migration and action.

type Result

type Result struct {
	Direction Direction
	Applied   []Applied
}

Result reports what a run did, in execution order.

type RunOption

type RunOption func(*runOptions)

RunOption adjusts one run (Up, UpTo, Down, Redo).

func ExpectPlan

func ExpectPlan(id string) RunOption

ExpectPlan makes the run verify, under the migration lock, that it is about to execute exactly the plan identified by id (see Migrator.PlanID) and to fail with ErrPlanChanged otherwise. It binds a human's or agent's approval of a dry run to what actually runs.

func ExpectTargetPlan

func ExpectTargetPlan(id string) RunOption

ExpectTargetPlan only permits the SQL target and exact plan approved with PlanWithID or PlanDownWithID. Legacy content-only PlanID values are rejected.

type State

type State string

State is the state of a migration relative to the database.

const (
	StatePending    State = "pending"
	StateApplied    State = "applied"
	StateFailed     State = "failed"   // dirty: failed part-way, needs repair
	StateModified   State = "modified" // applied, but the file changed since
	StateMissing    State = "missing"  // applied, but no longer in the source
	StateOutdated   State = "outdated" // repeatable whose content changed
	StateBaseline   State = "baseline" // the baseline marker row
	StateBelowBase  State = "below baseline"
	StateOutOfOrder State = "out of order" // pending, older than the latest applied
	StateSkipped    State = "skipped"      // excluded by DBMS, Context or Labels
	StateMarkedRan  State = "marked ran"   // recorded by a MARK_RAN precondition, never executed
	StateRunAlways  State = "run always"   // RunAlways repeatable: re-applied on every Up
)

Migration states reported by Status.

type Status

type Status struct {
	// Current is the highest applied version ("" if none).
	Current string
	// Dirty is true when a migration or run-level SQL callback needs recovery.
	Dirty bool
	// CallbackRecoveryRequired is true when a run-level callback may have
	// changed the database. See ErrCallbackRecoveryRequired.
	CallbackRecoveryRequired bool
	// Pending counts migrations Up would apply.
	Pending    int
	Migrations []Info
}

Status is a read-only snapshot of the database's migration state.

Directories

Path Synopsis
cmd
gomigrate command
Command gomigrate applies versioned SQL and Go migrations.
Command gomigrate applies versioned SQL and Go migrations.
internal
actionrunner command
The composite action runs this file with the Go toolchain it uses to install gomigrate.
The composite action runs this file with the Go toolchain it uses to install gomigrate.
cli
Package cli implements the gomigrate command line.
Package cli implements the gomigrate command line.
config
Package config loads the gomigrate CLI configuration and opens the database it describes.
Package config loads the gomigrate CLI configuration and opens the database it describes.
dialect
Package dialect describes the SQL differences between supported databases: identifier quoting, bind placeholders, lexical rules for statement splitting, DDL transactionality, history-table DDL and migration locking.
Package dialect describes the SQL differences between supported databases: identifier quoting, bind placeholders, lexical rules for statement splitting, DDL transactionality, history-table DDL and migration locking.
history
Package history persists which migrations have been applied.
Package history persists which migrations have been applied.
lint
Package lint finds risky operations in migration SQL without a database: statements that take long exclusive locks, rewrite tables, lose data, break running application versions or are unsupported by the target dialect.
Package lint finds risky operations in migration SQL without a database: statements that take long exclusive locks, rewrite tables, lose data, break running application versions or are unsupported by the target dialect.
nativecheck command
nativecheck verifies the terminal events from a single engine's go test -json run.
nativecheck verifies the terminal events from a single engine's go test -json run.
releasecheck command
Command releasecheck verifies the source and archives used by the release workflow.
Command releasecheck verifies the source and archives used by the release workflow.
script
Package script parses migration files and splits SQL into statements.
Package script parses migration files and splits SQL into statements.
source
Package source discovers migration files in an fs.FS.
Package source discovers migration files in an fs.FS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL