Migrations
AutoMigrate, granular schema operations, and versioned Go and SQL migrations guarded by a lock table.
db.Migrator() returns a migration runner over the session's pool
(fusion.go:373). It supports two styles: schemaless AutoMigrate that keeps
tables in sync with your structs, and versioned Go or SQL migrations recorded
in a lock table.
m, err := db.Migrator()Optional migrator.Option arguments customize the runner — see
Options below.
AutoMigrate
AutoMigrate(ctx, values...) walks each model: parse the schema, check
HasTable, create the table if missing, otherwise diff the live columns
against the parsed schema and add missing columns and indexes
(migrator/migrator.go:403).
if err := m.AutoMigrate(ctx, &User{}); err != nil {
panic(err)
}The diff also catches type drift: when an existing column's type is no
longer compatible with the declared one, AlterColumn runs where the
dialect supports it (migrator/migrator.go:471-481).
Many-to-many junction tables
Models declaring many2many relations get their junction tables created
automatically: two columns typed after the related tables' primary keys,
both part of a composite primary key, so a duplicate pair cannot be inserted
at the storage layer (migrator/migrator.go:485-524).
SQLite table rebuilds
SQLite rejects non-constant defaults (CURRENT_TIMESTAMP, now()) in
ALTER TABLE ADD COLUMN. When AutoMigrate must add such a column to an
existing table, it rebuilds the table instead: create the new table with the
full desired schema under a temporary name, copy the surviving rows across,
drop the original, and rename — all inside one transaction, with indexes
recreated after (migrator/migrator.go:333-382). Existing rows receive the
default through the copy step.
type migUserV3 struct {
ID int64 `fusion:"pk,autoincrement"`
Name string `fusion:"notnull"`
CreatedAt time.Time `fusion:"default:CURRENT_TIMESTAMP"`
}if err := m.AutoMigrate(ctx, &migUserV3{}); err != nil {
t.Fatalf("AutoMigrate v3: %v", err)
}
// pre-rebuild rows survive with created_at backfilledAssumes single-writer DDL
AutoMigrate is metadata and diff based; it assumes one writer at a time.
Destructive changes (dropping columns) are not part of the diff — use the
granular operations or versioned migrations for those.
Granular operations
For hand-rolled schema work, the Migrator exposes individual operations,
each gated on the dialect's feature flags:
| Operation | What it does |
|---|---|
HasTable(ctx, name) | Existence check via information_schema (PG) or sqlite_master (migrator/migrator.go:190). |
CreateTable(ctx, model) | CREATE TABLE from the parsed schema, plus declared indexes (migrator/migrator.go:206). |
ColumnTypes(ctx, name) | Lists existing columns: name, type, nullability, primary key, default (migrator/migrator.go:262). |
AddColumn(ctx, table, field) | ALTER TABLE ... ADD COLUMN (migrator/migrator.go:306). |
DropColumn(ctx, table, column) | ALTER TABLE ... DROP COLUMN (migrator/migrator.go:385). |
AlterColumn(ctx, table, field) | ALTER COLUMN TYPE where the dialect supports it (migrator/migrator.go:392). |
Versioned migrations
For ordered, recorded schema changes, register migrator.Migration values —
each a version, a name, and Up/Down functions over the raw *sql.DB
(migrator/migrator.go:34):
m, err := db.Migrator(migrator.WithTableName("app_migrations"))
m.Register(migrator.Migration{
Version: 1,
Name: "create_widgets",
Up: func(pool *sql.DB) error {
_, err := pool.Exec(`CREATE TABLE widgets (id INTEGER PRIMARY KEY)`)
return err
},
Down: func(pool *sql.DB) error {
_, err := pool.Exec(`DROP TABLE widgets`)
return err
},
})
if err := m.Up(ctx); err != nil {
panic(err)
}Register(migrations...)accepts versions in any order and keeps them sorted (migrator/migrator.go:621).Up(ctx)applies every migration not yet recorded, marking each in the lock table after success (migrator/migrator.go:629).Down(ctx, steps)rolls back the most recently appliedstepsmigrations, removing their rows (migrator/migrator.go:651).Migrate(ctx, version, up, down)registers one migration and applies it immediately (migrator/migrator.go:686).
Applied versions live in a lock table named fusion_migrations by default —
version BIGINT PRIMARY KEY, name, applied_at — created on first use
(migrator/migrator.go:565).
SQL file migrations
Prefer plain SQL? LoadSQLFiles(dir) reads numbered files named
N_name.up.sql and N_name.down.sql and returns ready Migration values,
sorted by version; non-matching files are ignored
(migrator/migrator.go:691-744).
// 1_init.up.sql: CREATE TABLE sql_widgets (id INTEGER PRIMARY KEY);
// 1_init.down.sql: DROP TABLE sql_widgets;
migrations, err := migrator.LoadSQLFiles("migrations")
m.Register(migrations...)
if err := m.Up(ctx); err != nil {
panic(err)
}Options
db.Migrator(opts...) accepts migrator.Option functions
(migrator/migrator.go:42):
| Option | Effect |
|---|---|
WithTableName(name) | Overrides the version lock table name (default fusion_migrations). |
WithMarkAppliedOnSuccess(enabled) | Controls whether successful migrations are recorded in the lock table. |
WithCacheInvalidator(fn) | Registers fn to run after AutoMigrate DDL. |
Prepared-statement invalidation
DDL can invalidate prepared statements sitting on a stale schema — the
GORM #7255 class of bug. db.Migrator() detects the prepared-statement
wrapper on the session and registers an invalidator automatically: after any
AutoMigrate DDL, the entire statement cache is dropped and later statements
prepare fresh (fusion.go:378-394). Statements still held by in-flight
callers close on their release (prepared_stmt.go:211). See
Prepared statements.