go-pg-migrate
PostgreSQL schema migrations for Go, with no dependencies outside the standard library
About go-pg-migrate
go-pg-migrate
PostgreSQL schema migrations for Go, with no dependencies outside the standard library.
- Each migration commits in the same transaction as its ledger row. A failed
migration leaves neither a half-applied change nor an unrecorded one. The
exception is
NoTxmigrations, below. - An advisory lock lets any number of replicas run
Upat startup. Each migration runs once. - History is checked before anything runs. Unknown applied versions, versions
added below the applied history, and rollbacks through a migration without
Downall fail up front.Config.AllowUnknownVersionslets an older image start against a newer ledger. - A default 5 s
lock_timeoutmakes a blockedALTER TABLEfail instead of stalling every query behind it. NoTxmigrations supportCREATE INDEX CONCURRENTLY, and an interrupted one is marked dirty instead of being forgotten.- Works with any
database/sqldriver. Tested with pgx and lib/pq on PostgreSQL 14 and 18.
Requires Go 1.25 or later.
go get github.com/lawzava/go-pg-migrate/v3
Usage
import (
"context"
"database/sql"
_ "github.com/jackc/pgx/v5/stdlib"
migrate "github.com/lawzava/go-pg-migrate/v3"
)
var migrations = []migrate.Migration{
{
Version: 1,
Name: "create users",
Up: migrate.SQL(`CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT NOT NULL)`),
Down: migrate.SQL(`DROP TABLE users`),
},
{
Version: 2,
Name: "index users.name",
Up: migrate.SQL(`CREATE INDEX CONCURRENTLY users_name ON users (name)`),
Down: migrate.SQL(`DROP INDEX CONCURRENTLY users_name`),
NoTx: true,
},
}
func migrateDB(ctx context.Context, db *sql.DB) error {
m, err := migrate.New(db, migrations, migrate.Config{})
if err != nil {
return err
}
return m.Up(ctx)
}
Up and Down can be any func(ctx context.Context, db migrate.Executor) error,
so a migration can also transform data in Go.
| Method | Effect |
|---|---|
Up(ctx) | Apply every pending migration. |
UpTo(ctx, v) | Apply pending migrations up to v. Never reverts. |
Down(ctx, v) | Revert applied migrations above v. 0 reverts all. |
Status(ctx) | List versions as applied, pending, dirty, or unknown. Read-only. |
Baseline(ctx, v) | Record versions up to v as applied without running them, to adopt an existing database. |
Resolve(ctx, v, applied) | Clear a dirty version after inspecting the database. |
Config sets the ledger location (default public.migrations), LockTimeout,
StatementTimeout, AllowOutOfOrder, AllowUnknownVersions, and a
*slog.Logger. The zero value works.
Migrating at boot
An applied version that the code does not contain returns ErrUnknownVersion.
That stops a service that calls Up at startup when it runs an older image
against a newer ledger, for example after an image rollback. Set
Config.AllowUnknownVersions for such a service. Up then applies the pending
migrations it knows, leaves the unknown rows untouched, and logs them once at
warn level.
The option does not relax the other checks:
- A dirty version still returns
ErrDirty. - An unknown version still counts as applied history. A pending migration
older than it returns
ErrOutOfOrderunlessAllowOutOfOrderis also set. Downstill returnsErrUnknownVersionwhen an unknown version lies above its target, because it has noDownto run for it.
Connection poolers
Transactional migrations work through PgBouncer in transaction mode. NoTx
migrations hold a session-level lock, so they need a direct connection or
session pooling.
Writing migrations
Read docs/writing-migrations.md for the rules:
append-only history, zero-downtime patterns, and the checks to run.
docs/agents.md is a block to paste into your project's
AGENTS.md or CLAUDE.md so coding agents follow the same rules.
To test that every Down reverses its Up, run
migratetest.RoundTrip against an empty database:
func TestMigrations(t *testing.T) {
migratetest.RoundTrip(t, emptyTestDB(t), migrations, migrate.Config{})
}
Example
integration/example is a small CLI with up, up-to,
down, status (JSON), baseline, and resolve commands.
Upgrading from v2
See CHANGELOG.md. The v2 ledger table is upgraded in place on the first v3 run. To roll back to a v2 image, convert the table back with docs/downgrade-to-v2.sql.
Frequently Asked Questions
What is go-pg-migrate?
go-pg-migrate is a Database library for the Go programming language. PostgreSQL schema migrations for Go, with no dependencies outside the standard library
How do I install go-pg-migrate?
Install go-pg-migrate with the Go module system using `go get lawzava/go-pg-migrate`. Check the repository for the current installation instructions.
What category does go-pg-migrate belong to?
go-pg-migrate is listed under Database, specifically Database Schema Migration.