Auto Migration
Automatically migrate your schema, to keep your schema up to date.
NOTE: AutoMigrate will create tables, missing foreign keys, constraints, columns and indexes. It will change existing column’s type if its size, precision, nullable changed. It WON’T delete unused columns to protect your data.
db.AutoMigrate(&User{})db.AutoMigrate(&User{}, &Product{}, &Order{})// Add table suffix when creating tablesdb.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
NOTE AutoMigrate creates database foreign key constraints automatically, you can disable this feature during initialization, for example:
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true,})
Migrator Interface
GORM provides a migrator interface, which contains unified API interfaces for each database that could be used to build your database-independent migrations, for example:
SQLite doesn’t support ALTER COLUMN, DROP COLUMN, GORM will create a new table as the one you are trying to change, copy all data, drop the old table, rename the new table
MySQL doesn’t support rename column, index for some versions, GORM will perform different SQL based on the MySQL version you are using
type Migrator interface {// AutoMigrateAutoMigrate(dst ...interface{}) error// DatabaseCurrentDatabase() stringFullDataTypeOf(*schema.Field) clause.Expr// TablesCreateTable(dst ...interface{}) errorDropTable(dst ...interface{}) errorHasTable(dst interface{}) boolRenameTable(oldName, newName interface{}) errorGetTables() (tableList []string, err error)// ColumnsAddColumn(dst interface{}, field string) errorDropColumn(dst interface{}, field string) errorAlterColumn(dst interface{}, field string) errorMigrateColumn(dst interface{}, field *schema.Field, columnType ColumnType) errorHasColumn(dst interface{}, field string) boolRenameColumn(dst interface{}, oldName, field string) errorColumnTypes(dst interface{}) ([]ColumnType, error)// ConstraintsCreateConstraint(dst interface{}, name string) errorDropConstraint(dst interface{}, name string) errorHasConstraint(dst interface{}, name string) bool// IndexesCreateIndex(dst interface{}, name string) errorDropIndex(dst interface{}, name string) errorHasIndex(dst interface{}, name string) boolRenameIndex(dst interface{}, oldName, newName string) error}
CurrentDatabase
Returns current using database name
db.Migrator().CurrentDatabase()
Tables
// Create table for `User`db.Migrator().CreateTable(&User{})// Append "ENGINE=InnoDB" to the creating table SQL for `User`db.Set("gorm:table_options", "ENGINE=InnoDB").Migrator().CreateTable(&User{})// Check table for `User` exists or notdb.Migrator().HasTable(&User{})db.Migrator().HasTable("users")// Drop table if exists (will ignore or delete foreign key constraints when dropping)db.Migrator().DropTable(&User{})db.Migrator().DropTable("users")// Rename old table to new tabledb.Migrator().RenameTable(&User{}, &UserInfo{})db.Migrator().RenameTable("users", "user_infos")
Columns
type User struct {Name string}// Add name fielddb.Migrator().AddColumn(&User{}, "Name")// Drop name fielddb.Migrator().DropColumn(&User{}, "Name")// Alter name fielddb.Migrator().AlterColumn(&User{}, "Name")// Check column existsdb.Migrator().HasColumn(&User{}, "Name")type User struct {Name stringNewName string}// Rename column to new namedb.Migrator().RenameColumn(&User{}, "Name", "NewName")db.Migrator().RenameColumn(&User{}, "name", "new_name")// ColumnTypesdb.Migrator().ColumnTypes(&User{}) ([]gorm.ColumnType, error)type ColumnType interface {Name() stringDatabaseTypeName() string // varcharColumnType() (columnType string, ok bool) // varchar(64)PrimaryKey() (isPrimaryKey bool, ok bool)AutoIncrement() (isAutoIncrement bool, ok bool)Length() (length int64, ok bool)DecimalSize() (precision int64, scale int64, ok bool)Nullable() (nullable bool, ok bool)Unique() (unique bool, ok bool)ScanType() reflect.TypeComment() (value string, ok bool)DefaultValue() (value string, ok bool)}
Constraints
type UserIndex struct {Name string `gorm:"check:name_checker,name <> 'jinzhu'"`}// Create constraintdb.Migrator().CreateConstraint(&User{}, "name_checker")// Drop constraintdb.Migrator().DropConstraint(&User{}, "name_checker")// Check constraint existsdb.Migrator().HasConstraint(&User{}, "name_checker")
Create foreign keys for relations
type User struct {gorm.ModelCreditCards []CreditCard}type CreditCard struct {gorm.ModelNumber stringUserID uint}// create database foreign key for user & credit_cardsdb.Migrator().CreateConstraint(&User{}, "CreditCards")db.Migrator().CreateConstraint(&User{}, "fk_users_credit_cards")// ALTER TABLE `credit_cards` ADD CONSTRAINT `fk_users_credit_cards` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)// check database foreign key for user & credit_cards exists or notdb.Migrator().HasConstraint(&User{}, "CreditCards")db.Migrator().HasConstraint(&User{}, "fk_users_credit_cards")// drop database foreign key for user & credit_cardsdb.Migrator().DropConstraint(&User{}, "CreditCards")db.Migrator().DropConstraint(&User{}, "fk_users_credit_cards")
Indexes
type User struct {gorm.ModelName string `gorm:"size:255;index:idx_name,unique"`}// Create index for Name fielddb.Migrator().CreateIndex(&User{}, "Name")db.Migrator().CreateIndex(&User{}, "idx_name")// Drop index for Name fielddb.Migrator().DropIndex(&User{}, "Name")db.Migrator().DropIndex(&User{}, "idx_name")// Check Index existsdb.Migrator().HasIndex(&User{}, "Name")db.Migrator().HasIndex(&User{}, "idx_name")type User struct {gorm.ModelName string `gorm:"size:255;index:idx_name,unique"`Name2 string `gorm:"size:255;index:idx_name_2,unique"`}// Rename index namedb.Migrator().RenameIndex(&User{}, "Name", "Name2")db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2")
Constraints
GORM creates constraints when auto migrating or creating table, see Constraints or Database Indexes for details
Other Migration Tools
GORM’s AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you.
// returns `*sql.DB`db.DB()
Refer to Generic Interface for more details.