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.
This commit is contained in:
Horacio Duran 2017-09-28 11:48:21 -03:00 committed by Jinzhu
parent b1885a643b
commit 3a9e91ab37
2 changed files with 26 additions and 1 deletions

View File

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

View File

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