Use when managing database schema changes, such as creating or modifying tables, columns, and indexes, to keep the database schema synchronized with application models.
Automatically migrate your schema, to keep your schema up to date.
db.AutoMigrate(&User{})
db.AutoMigrate(&User{}, &Product{}, &Order{})
NOTE: AutoMigrate will create tables, missing foreign keys, constraints, columns and indexes. It will change existing column's type if its size, precision changed. It WON'T delete unused columns to protect your data.
GORM provides a migrator interface, which contains unified API interfaces for each database.
// Create table for `User`
db.Migrator().CreateTable(&User{})
// Check table for `User` exists or not
db.Migrator().HasTable(&User{})
// Drop table if exists
db.Migrator().DropTable(&User{})
// Rename old table to new table
db.Migrator().RenameTable(&User{}, &UserInfo{})
AutoMigrate can make unexpected changes. Always generate the SQL in a development environment and review it before running it in production.AutoMigrate will not delete columns or tables. For these changes, you need to use the Migrator interface or write raw SQL.AutoMigrate can lock tables. For zero-downtime, you need a more advanced migration strategy (e.g., using a tool like Flyway or Liquibase, or performing multi-step manual migrations).AutoMigrate only handles schema changes. If you need to transform data as part of a migration, you will need to write custom migration scripts.// Add name field
db.Migrator().AddColumn(&User{}, "Name")
// Drop name field
db.Migrator().DropColumn(&User{}, "Name")
// Alter name field
db.Migrator().AlterColumn(&User{}, "Name")
// Check column exists
db.Migrator().HasColumn(&User{}, "Name")
// Rename column to new name
db.Migrator().RenameColumn(&User{}, "Name", "NewName")