AutoMigrate

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{})

    db.AutoMigrate(&User{}, &Product{}, &Order{})

    // 创建表时添加后缀
    db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

注意 AutoMigrate 会自动创建数据库外键约束,您可以在初始化时禁用此功能,例如:

  1. db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
    DisableForeignKeyConstraintWhenMigrating: true,
    })

Migrator 接口

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 不支持 ALTER COLUMNDROP COLUMN,当你试图修改表结构,GORM 将创建一个新表、复制所有数据、删除旧表、重命名新表。

一些版本的 MySQL 不支持 rename 列,索引。GORM 将基于您使用 MySQL 的版本执行不同 SQL

  1. type Migrator interface {
    // AutoMigrate
    AutoMigrate(dst ...interface{}) error

    // Database
    CurrentDatabase() string
    FullDataTypeOf(*schema.Field) clause.Expr

    // Tables
    CreateTable(dst ...interface{}) error
    DropTable(dst ...interface{}) error
    HasTable(dst interface{}) bool
    RenameTable(oldName, newName interface{}) error

    // Columns
    AddColumn(dst interface{}, field string) error
    DropColumn(dst interface{}, field string) error
    AlterColumn(dst interface{}, field string) error
    HasColumn(dst interface{}, field string) bool
    RenameColumn(dst interface{}, oldName, field string) error
    MigrateColumn(dst interface{}, field *schema.Field, columnType *sql.ColumnType) error
    ColumnTypes(dst interface{}) ([]*sql.ColumnType, error)

    // Constraints
    CreateConstraint(dst interface{}, name string) error
    DropConstraint(dst interface{}, name string) error
    HasConstraint(dst interface{}, name string) bool

    // Indexes
    CreateIndex(dst interface{}, name string) error
    DropIndex(dst interface{}, name string) error
    HasIndex(dst interface{}, name string) bool
    RenameIndex(dst interface{}, oldName, newName string) error
    }

当前数据库

返回当前使用的数据库名

  1. db.Migrator().CurrentDatabase()

  1. // 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 not
    db.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 table
    db.Migrator().RenameTable(&User{}, &UserInfo{})
    db.Migrator().RenameTable("users", "user_infos")

  1. type User struct {
    Name string
    }

    // 添加 name 字段
    db.Migrator().AddColumn(&User{}, "Name")
    // 删除 name 字段
    db.Migrator().DropColumn(&User{}, "Name")
    // 修改 name 字段
    db.Migrator().AlterColumn(&User{}, "Name")
    // 检查字段是否存在
    db.Migrator().HasColumn(&User{}, "Name")

    type User struct {
    Name string
    NewName string
    }

    // 重命名字段
    db.Migrator().RenameColumn(&User{}, "Name", "NewName")
    db.Migrator().RenameColumn(&User{}, "name", "new_name")

    // 获取字段类型
    db.Migrator().ColumnTypes(&User{}) ([]*sql.ColumnType, error)

约束

  1. type UserIndex struct {
    Name string `gorm:"check:name_checker,name <> 'jinzhu'"`
    }

    // 创建约束
    db.Migrator().CreateConstraint(&User{}, "name_checker")

    // 删除约束
    db.Migrator().DropConstraint(&User{}, "name_checker")

    // 检查约束是否存在
    db.Migrator().HasConstraint(&User{}, "name_checker")

索引

  1. type User struct {
    gorm.Model
    Name string `gorm:"size:255;index:idx_name,unique"`
    }

    // 为 Name 字段创建索引
    db.Migrator().CreateIndex(&User{}, "Name")
    db.Migrator().CreateIndex(&User{}, "idx_name")

    // 为 Name 字段删除索引
    db.Migrator().DropIndex(&User{}, "Name")
    db.Migrator().DropIndex(&User{}, "idx_name")

    // 检查索引是否存在
    db.Migrator().HasIndex(&User{}, "Name")
    db.Migrator().HasIndex(&User{}, "idx_name")

    type User struct {
    gorm.Model
    Name string `gorm:"size:255;index:idx_name,unique"`
    Name2 string `gorm:"size:255;index:idx_name_2,unique"`
    }
    // 修改索引名
    db.Migrator().RenameIndex(&User{}, "Name", "Name2")
    db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2")

约束

GORM creates constraints when auto migrating or creating table, see Constraints or Database Indexes for details

其他迁移工具

GORM 的 AutoMigrate 在大多数情况下都工作得很好,但如果您正在寻找更严格的迁移工具,GORM 提供一个通用数据库接口,可能对您有帮助。

  1. // returns `*sql.DB`
    db.DB()

Refer to Generic Interface for more details.