Fix create unique index when creating table, close #3081

This commit is contained in:
Jinzhu 2020-06-23 22:14:17 +08:00
parent dd7caa9db0
commit 4201f7bdab
2 changed files with 20 additions and 0 deletions

View File

@ -175,6 +175,9 @@ func (m Migrator) CreateTable(values ...interface{}) error {
errr = tx.Migrator().CreateIndex(value, name)
}(value, idx.Name)
} else {
if idx.Class != "" {
createTableSQL += idx.Class + " "
}
createTableSQL += "INDEX ? ?,"
values = append(values, clause.Expr{SQL: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt))
}

View File

@ -62,6 +62,23 @@ func TestMigrateWithComment(t *testing.T) {
}
}
func TestMigrateWithUniqueIndex(t *testing.T) {
type UserWithUniqueIndex struct {
ID int
Name string `gorm:"size:20;index:idx_name,unique"`
Date time.Time `gorm:"index:idx_name,unique"`
}
DB.Migrator().DropTable(&UserWithUniqueIndex{})
if err := DB.AutoMigrate(&UserWithUniqueIndex{}); err != nil {
t.Fatalf("failed to migrate, got %v", err)
}
if !DB.Migrator().HasIndex(&UserWithUniqueIndex{}, "idx_name") {
t.Errorf("Failed to find created index")
}
}
func TestTable(t *testing.T) {
type TableStruct struct {
gorm.Model