From 2202e99cbf0f43c35315fe4d17b87ac81f0f2d23 Mon Sep 17 00:00:00 2001 From: s-takehana Date: Sun, 18 Jul 2021 12:47:44 +0900 Subject: [PATCH] Fix create index with comments in MySQL (#4521) * Fix create index with comments in MySQL * Fix tests --- migrator/migrator.go | 8 ++++++++ tests/migrate_test.go | 29 ++++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/migrator/migrator.go b/migrator/migrator.go index 03ffdd02..7c7405b3 100644 --- a/migrator/migrator.go +++ b/migrator/migrator.go @@ -195,6 +195,10 @@ func (m Migrator) CreateTable(values ...interface{}) error { } createTableSQL += "INDEX ? ?" + if idx.Comment != "" { + createTableSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment) + } + if idx.Option != "" { createTableSQL += " " + idx.Option } @@ -601,6 +605,10 @@ func (m Migrator) CreateIndex(value interface{}, name string) error { createIndexSQL += " USING " + idx.Type } + if idx.Comment != "" { + createIndexSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment) + } + if idx.Option != "" { createIndexSQL += " " + idx.Option } diff --git a/tests/migrate_test.go b/tests/migrate_test.go index 4da3856f..599ca850 100644 --- a/tests/migrate_test.go +++ b/tests/migrate_test.go @@ -142,17 +142,36 @@ func TestSmartMigrateColumn(t *testing.T) { } -func TestMigrateWithComment(t *testing.T) { - type UserWithComment struct { +func TestMigrateWithColumnComment(t *testing.T) { + type UserWithColumnComment struct { gorm.Model - Name string `gorm:"size:111;index:,comment:这是一个index;comment:this is a 字段"` + Name string `gorm:"size:111;comment:this is a 字段"` } - if err := DB.Migrator().DropTable(&UserWithComment{}); err != nil { + if err := DB.Migrator().DropTable(&UserWithColumnComment{}); err != nil { t.Fatalf("Failed to drop table, got error %v", err) } - if err := DB.AutoMigrate(&UserWithComment{}); err != nil { + if err := DB.AutoMigrate(&UserWithColumnComment{}); err != nil { + t.Fatalf("Failed to auto migrate, but got error %v", err) + } +} + +func TestMigrateWithIndexComment(t *testing.T) { + if DB.Dialector.Name() != "mysql" { + t.Skip() + } + + type UserWithIndexComment struct { + gorm.Model + Name string `gorm:"size:111;index:,comment:这是一个index"` + } + + if err := DB.Migrator().DropTable(&UserWithIndexComment{}); err != nil { + t.Fatalf("Failed to drop table, got error %v", err) + } + + if err := DB.AutoMigrate(&UserWithIndexComment{}); err != nil { t.Fatalf("Failed to auto migrate, but got error %v", err) } }