Documentation
¶
Overview ¶
Package sqlmigrate provides a database-agnostic SQL migration interface.
Backend implementations (each a separate Go module):
- pgmigrate: PostgreSQL via pgx/v5
- mymigrate: MySQL/MariaDB via go-sql-driver/mysql
- litemigrate: SQLite via database/sql
- msmigrate: SQL Server via go-mssqldb
- shmigrate: POSIX shell script generation
Index ¶
- Variables
- func Down(ctx context.Context, r Migrator, migrations []Migration, n int) ([]string, error)
- func Drop(ctx context.Context, r Migrator, migrations []Migration) ([]string, error)
- func Latest(ctx context.Context, r Migrator, migrations []Migration) ([]string, error)
- func Up(ctx context.Context, r Migrator, migrations []Migration, n int) ([]string, error)
- type AppliedMigration
- type Migration
- type Migrator
- type Status
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingUp = errors.New("missing up migration") ErrMissingDown = errors.New("missing down migration") ErrWalkFailed = errors.New("walking migrations") ErrExecFailed = errors.New("migration exec failed") ErrQueryApplied = errors.New("querying applied migrations") ErrInvalidN = errors.New("n must be positive or -1 for all") )
Sentinel errors for migration operations.
Functions ¶
func Down ¶
Down rolls back up to n applied migrations, most recent first. If n < 0, rolls back all applied. If n == 0, returns ErrInvalidN. Returns the names of rolled-back migrations.
func Drop ¶ added in v1.0.1
Drop rolls back all applied migrations. Equivalent to Down(ctx, r, migrations, -1).
Types ¶
type AppliedMigration ¶
AppliedMigration represents a migration recorded in the _migrations table.
type Migration ¶
type Migration struct {
Name string // e.g. "2026-04-05-001000_create-todos"
ID string // 8-char hex from INSERT INTO _migrations, parsed by Collect
Up string // SQL content of the .up.sql file
Down string // SQL content of the .down.sql file
}
Migration represents a paired up/down migration.
func Collect ¶
Collect reads .up.sql and .down.sql files from fsys under subpath, pairs them by basename, and returns them sorted lexicographically by name. If subpath is "" or ".", the root of fsys is used. If the up SQL contains an INSERT INTO _migrations line, the hex ID is extracted and stored in Migration.ID.
type Migrator ¶
type Migrator interface {
// ExecUp runs the up migration. For database migrators this executes
// m.Up in a transaction. For shell migrators this outputs a command
// referencing the .up.sql file.
ExecUp(ctx context.Context, m Migration) error
// ExecDown runs the down migration.
ExecDown(ctx context.Context, m Migration) error
// Applied returns all applied migrations from the _migrations table,
// sorted lexicographically by name. Returns an empty slice (not an
// error) if the migrations table or log does not exist yet.
Applied(ctx context.Context) ([]AppliedMigration, error)
}
Migrator executes migrations. Implementations handle the database-specific or output-specific details.