From 3a9e91ab372120a0e35b518430255308e3d8d5ea Mon Sep 17 00:00:00 2001 From: Horacio Duran Date: Thu, 28 Sep 2017 11:48:21 -0300 Subject: [PATCH] Correct ModifyColumn SQL syntax. (#1614) * Correct ModifyColumn SQL syntax. The generated SQL for ModifyColumn was: `ALTER TABLE "tablename" MODIFY "columname" type` But should have been: `ALTER TABLE "tablename" ALTER COLUMN "columname" TYPE type` since Modify does not seem to be entirely compatible with all Engines * Test ModifyColumn * Skip ModifyColumnType test on incompatible DBs Some DB Engines don't fully support alter table so we skip when the dialect does not correspond to one of the ones that are known to support it. --- migration_test.go | 25 +++++++++++++++++++++++++ scope.go | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/migration_test.go b/migration_test.go index 9fc14fa0..3f3a5c8f 100644 --- a/migration_test.go +++ b/migration_test.go @@ -5,6 +5,7 @@ import ( "database/sql/driver" "errors" "fmt" + "os" "reflect" "testing" "time" @@ -432,3 +433,27 @@ func TestMultipleIndexes(t *testing.T) { t.Error("MultipleIndexes unique index failed") } } + +func TestModifyColumnType(t *testing.T) { + dialect := os.Getenv("GORM_DIALECT") + if dialect != "postgres" && + dialect != "mysql" && + dialect != "mssql" { + t.Skip("Skipping this because only postgres, mysql and mssql support altering a column type") + } + + type ModifyColumnType struct { + gorm.Model + Name1 string `gorm:"length:100"` + Name2 string `gorm:"length:200"` + } + DB.DropTable(&ModifyColumnType{}) + DB.CreateTable(&ModifyColumnType{}) + + name2Field, _ := DB.NewScope(&ModifyColumnType{}).FieldByName("Name2") + name2Type := DB.Dialect().DataTypeOf(name2Field.StructField) + + if err := DB.Model(&ModifyColumnType{}).ModifyColumn("name1", name2Type).Error; err != nil { + t.Errorf("No error should happen when ModifyColumn, but got %v", err) + } +} diff --git a/scope.go b/scope.go index fda7f653..51ebd5a0 100644 --- a/scope.go +++ b/scope.go @@ -1139,7 +1139,7 @@ func (scope *Scope) dropTable() *Scope { } func (scope *Scope) modifyColumn(column string, typ string) { - scope.Raw(fmt.Sprintf("ALTER TABLE %v MODIFY %v %v", scope.QuotedTableName(), scope.Quote(column), typ)).Exec() + scope.Raw(fmt.Sprintf("ALTER TABLE %v ALTER COLUMN %v TYPE %v", scope.QuotedTableName(), scope.Quote(column), typ)).Exec() } func (scope *Scope) dropColumn(column string) {