Retrieved article excerpt
Open article Β· Retrieved 2026-11-19T12:25:21.877083+00:00
[go-migrate's folded turquoise swift](https://github.com/Go-Gen-Ecosystem/go-migrate/blob/main/assets/go-migrate-logo.svg)
# 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](https://github.com/Go-Gen-Ecosystem/go-migrate/releases/latest)
[Integration statement coverage](https://github.com/Go-Gen-Ecosystem/go-migrate/actions/workflows/ci.yml?query=branch%3Amain)
[Go Reference](https://pkg.go.dev/github.com/go-gen-ecosystem/go-migrate)
```
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](https://github.com/Go-Gen-Ecosystem/go-migrate/blob/v1.0.1/apply.go) Β· [golang-migrate execution and recovery](https://github.com/golang-migrate/migrate/blob/v4.20.1/migrate.go) Β· [goose transactional SQL](https://github.com/pressly/goose/blob/v3.30.1/migration_sql.go)
Packaging and feature comparisons use the tagged source and build configuration. [golang-migrate release drivers](https://github.com/golang-migrate/migrate/blob/v4.20.1/Makefile) Β· [goose SQL annotations](https://github.com/pressly/goose/blob/v3.30.1/README.md) Β· [goose SQLite driver](https://github.com/pressly/goose/blob/v3.30.1/cmd/goose/driver_sqlite3.go) Β· [goose release build](https://github.com/pressly/goose/blob/v3.30.1/.goreleaser.yaml)
### 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](https://github.com/Go-Gen-Ecosystem/go-migrate/blob/v1.0.1/benchmarks/compare/compare_test.go)
| 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](https://github.com/golang-migrate/migrate/blob/v4.20.1/migration.go)
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](https://github.com/go-gen-ecosystem/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](https://github.com/Go-Gen-Ecosystem/go-migrate/blob/main/examples/sqlserver).
## Oracle Database
Use the `oracle` dialect or an `oracle://user:pass