I started go-migrate in 2023 as the migration layer of my private Go framework. I am releasing these layers separately. HaloLog handles structured logging. This tutorial uses the migration library to ship two versions in one binary and check their installation order.
An illustrative release. A SQL checksum can identify an edit to version 1. The executable and its source review identify the Go implementation of version 2. Evidence
Start with this file at migrations/0001_users.sql:
-- +migrate Up
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users (id, email) VALUES (1, 'ADA@EXAMPLE.COM');
-- +migrate Down
DROP TABLE users;
This complete package adds a Go migration after that SQL migration:
package migrations
import (
"context"
"database/sql"
"embed"
"io/fs"
migrate "github.com/go-gen-ecosystem/go-migrate"
)
//go:embed migrations/*.sql
var files embed.FS
func Apply(ctx context.Context, db *sql.DB) error {
dir, err := fs.Sub(files, "migrations")
if err != nil {
return err
}
m, err := migrate.New(db, "sqlite", migrate.WithFS(dir),
migrate.WithGoMigrations(migrate.GoMigration{
Version: "2", Description: "normalize emails",
Up: func(ctx context.Context, ex migrate.Executor) error {
_, err := ex.ExecContext(ctx,
"UPDATE users SET email = LOWER(email)")
return err
},
}))
if err != nil {
return err
}
_, err = m.Up(ctx)
return err
}
SQL and Go migrations share one numeric version ordering: SQL version 1 runs before Go version 2. Canonically equivalent versions cannot coexist. The Go function receives the library’s Executor; use it for database work. This example deliberately omits Down, so version 2 is irreversible. Go function bodies have no stored checksum: keep their deployed versions immutable through your release process.
Observed on SQLite. We called the example twice against the same database. After each call there was one user, with ada@example.com. History contained exactly two successful entries, in order: SQL version 1, then Go version 2. The second call left both the row count and history unchanged. This demonstrates the behavior for the seeded address. Real email policies may handle the local part differently.
To check the result on your copy, run these queries after each call to Apply.
SELECT id, email FROM users ORDER BY id;
SELECT installed_rank, version, success FROM gomigrate_history ORDER BY installed_rank;
Sources: embedded sources and registration; GoMigration and Executor.
I maintain go-migrate. I used AI to help draft this tutorial.

Top comments (0)