Dead simple in-app migration system.
go get github.com/struct0x/migrate
In your module, declare migrations
package users
import "github.com/struct0x/migrate"
var StoreMigrations = migrate.Migrations{
ModuleName: "users",
Migrations: []migrate.Migration{
{
Name: "001_create_users",
SQL: `CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL
)`,
},
{
Name: "002_add_email",
SQL: `ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''`,
},
},
}At startup, pass all module groups together:
package main
func main() {
// ...
if err := migrate.Migrate(ctx, db, migrate.Postgres,
users.StoreMigrations,
payments.StoreMigrations,
licensing.StoreMigrations,
); err != nil {
return fmt.Errorf("migrate: %w", err)
}
}| Dialect | Var |
|---|---|
| SQLite | migrate.SQLite |
| PostgreSQL | migrate.Postgres |
| MySQL | migrate.MySQL |
| Option | Description |
|---|---|
WithLogger(*slog.Logger) |
Sets the logger used to print what migrations were run. |
- Idempotent — safe to call on every startup
- Concurrent-safe — multiple processes can call Migrate simultaneously
- Each migration runs exactly once
- A failed migration is rolled back and returns an error; subsequent migrations in the group are not applied
MIT License