From 4201f7bdab7826cd4523550d58a969438f6bb50b Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 23 Jun 2020 22:14:17 +0800 Subject: [PATCH] Fix create unique index when creating table, close #3081 --- migrator/migrator.go | 3 +++ tests/migrate_test.go | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/migrator/migrator.go b/migrator/migrator.go index a239c926..c8fe17ab 100644 --- a/migrator/migrator.go +++ b/migrator/migrator.go @@ -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)) } diff --git a/tests/migrate_test.go b/tests/migrate_test.go index fce4c4aa..2c593a70 100644 --- a/tests/migrate_test.go +++ b/tests/migrate_test.go @@ -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