AutoMigrate function compares your model definitions against the live schema and applies any missing tables, columns, and indexes. It is non-destructive by design: it never drops columns or changes existing column types.
Running AutoMigrate
Pass one or more model pointers todb.AutoMigrate. It runs the migration inside a single call.
AutoMigrate is safe to run every time your application starts. It checks the schema first and only applies changes when needed.
What AutoMigrate does
Creates missing tables
Creates missing tables
If a table for a model does not exist, AutoMigrate creates it with all columns, primary keys, unique constraints, and indexes defined in the struct.
Adds missing columns
Adds missing columns
If a column defined in the struct is absent from the existing table, AutoMigrate adds it. Existing rows receive the column’s zero value or DEFAULT.
Creates missing indexes
Creates missing indexes
Indexes defined via struct tags (e.g.,
gorm:"index", gorm:"uniqueIndex") that are not present in the database are created.Does NOT drop columns or change types
Does NOT drop columns or change types
AutoMigrate never removes columns that exist in the database but not in the struct, and it does not alter column types. Make those changes manually using the Migrator interface or raw SQL.
Migrator interface
db.Migrator() returns a Migrator that exposes the full schema management API. Use it when you need precise control over migration steps.
Table operations
Column operations
Index operations
View operations
Configuration options
DisableForeignKeyConstraintWhenMigrating
Prevent GORM from creating foreign key constraints during migration. Useful when you manage FK constraints separately or when your database user lacks the required privileges.IgnoreRelationshipsWhenMigrating
Skip processing associations duringAutoMigrate. GORM will only migrate the columns defined directly on the model, not those implied by has many, belongs to, etc.
Migration in production
Generate the SQL first
Use DryRun mode or inspect
migrator.ColumnTypes to understand what changes will be applied before running them.