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.
1. db.AutoMigrate(&User{})
3. db.AutoMigrate(&User{}, &Product{}, &Order{})
5. // Add table suffix when creating tables
6. db.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:
1. db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
2. DisableForeignKeyConstraintWhenMigrating: true,
3. })
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
1. type Migrator interface {
2. // AutoMigrate
3. AutoMigrate(dst ...interface{}) error
5. // Database
6. CurrentDatabase() string
7. FullDataTypeOf(*schema.Field) clause.Expr
9. // Tables
10. CreateTable(dst ...interface{}) error
11. DropTable(dst ...interface{}) error
12. HasTable(dst interface{}) bool
13. RenameTable(oldName, newName interface{}) error
14. GetTables() (tableList []string, err error)
16. // Columns
17. AddColumn(dst interface{}, field string) error
18. DropColumn(dst interface{}, field string) error
19. AlterColumn(dst interface{}, field string) error
20. MigrateColumn(dst interface{}, field *schema.Field, columnType ColumnType) error
21. HasColumn(dst interface{}, field string) bool
22. RenameColumn(dst interface{}, oldName, field string) error
23. ColumnTypes(dst interface{}) ([]ColumnType, error)
25. // Constraints
26. CreateConstraint(dst interface{}, name string) error
27. DropConstraint(dst interface{}, name string) error
28. HasConstraint(dst interface{}, name string) bool
30. // Indexes
31. CreateIndex(dst interface{}, name string) error
32. DropIndex(dst interface{}, name string) error
33. HasIndex(dst interface{}, name string) bool
34. RenameIndex(dst interface{}, oldName, newName string) error
35. }
CurrentDatabase
Returns current using database name
1. db.Migrator().CurrentDatabase()
Tables
1. // Create table for `User`
2. db.Migrator().CreateTable(&User{})
4. // Append "ENGINE=InnoDB" to the creating table SQL for `User`
5. db.Set("gorm:table_options", "ENGINE=InnoDB").Migrator().CreateTable(&User{})
7. // Check table for `User` exists or not
8. db.Migrator().HasTable(&User{})
9. db.Migrator().HasTable("users")
11. // Drop table if exists (will ignore or delete foreign key constraints when dropping)
12. db.Migrator().DropTable(&User{})
13. db.Migrator().DropTable("users")
15. // Rename old table to new table
16. db.Migrator().RenameTable(&User{}, &UserInfo{})
17. db.Migrator().RenameTable("users", "user_infos")
Columns
1. type User struct {
2. Name string
3. }
5. // Add name field
6. db.Migrator().AddColumn(&User{}, "Name")
7. // Drop name field
8. db.Migrator().DropColumn(&User{}, "Name")
9. // Alter name field
10. db.Migrator().AlterColumn(&User{}, "Name")
11. // Check column exists
12. db.Migrator().HasColumn(&User{}, "Name")
14. type User struct {
15. Name string
16. NewName string
17. }
19. // Rename column to new name
20. db.Migrator().RenameColumn(&User{}, "Name", "NewName")
21. db.Migrator().RenameColumn(&User{}, "name", "new_name")
23. // ColumnTypes
24. db.Migrator().ColumnTypes(&User{}) ([]gorm.ColumnType, error)
26. type ColumnType interface {
27. Name() string
28. DatabaseTypeName() string // varchar
29. ColumnType() (columnType string, ok bool) // varchar(64)
30. PrimaryKey() (isPrimaryKey bool, ok bool)
31. AutoIncrement() (isAutoIncrement bool, ok bool)
32. Length() (length int64, ok bool)
33. DecimalSize() (precision int64, scale int64, ok bool)
34. Nullable() (nullable bool, ok bool)
35. Unique() (unique bool, ok bool)
36. ScanType() reflect.Type
37. Comment() (value string, ok bool)
38. DefaultValue() (value string, ok bool)
39. }
Constraints
1. type UserIndex struct {
2. Name string `gorm:"check:name_checker,name <> 'jinzhu'"`
3. }
5. // Create constraint
6. db.Migrator().CreateConstraint(&User{}, "name_checker")
8. // Drop constraint
9. db.Migrator().DropConstraint(&User{}, "name_checker")
11. // Check constraint exists
12. db.Migrator().HasConstraint(&User{}, "name_checker")
Create foreign keys for relations
1. type User struct {
2. gorm.Model
3. CreditCards []CreditCard
4. }
6. type CreditCard struct {
7. gorm.Model
8. Number string
9. UserID uint
10. }
12. // create database foreign key for user & credit_cards
13. db.Migrator().CreateConstraint(&User{}, "CreditCards")
14. db.Migrator().CreateConstraint(&User{}, "fk_users_credit_cards")
15. // ALTER TABLE `credit_cards` ADD CONSTRAINT `fk_users_credit_cards` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
17. // check database foreign key for user & credit_cards exists or not
18. db.Migrator().HasConstraint(&User{}, "CreditCards")
19. db.Migrator().HasConstraint(&User{}, "fk_users_credit_cards")
21. // drop database foreign key for user & credit_cards
22. db.Migrator().DropConstraint(&User{}, "CreditCards")
23. db.Migrator().DropConstraint(&User{}, "fk_users_credit_cards")
Indexes
1. type User struct {
2. gorm.Model
3. Name string `gorm:"size:255;index:idx_name,unique"`
4. }
6. // Create index for Name field
7. db.Migrator().CreateIndex(&User{}, "Name")
8. db.Migrator().CreateIndex(&User{}, "idx_name")
10. // Drop index for Name field
11. db.Migrator().DropIndex(&User{}, "Name")
12. db.Migrator().DropIndex(&User{}, "idx_name")
14. // Check Index exists
15. db.Migrator().HasIndex(&User{}, "Name")
16. db.Migrator().HasIndex(&User{}, "idx_name")
18. type User struct {
19. gorm.Model
20. Name string `gorm:"size:255;index:idx_name,unique"`
21. Name2 string `gorm:"size:255;index:idx_name_2,unique"`
22. }
23. // Rename index name
24. db.Migrator().RenameIndex(&User{}, "Name", "Name2")
25. 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.
1. // returns `*sql.DB`
2. db.DB()
Refer to Generic Interface for more details.
