Move ModifyColumn implemention to Dialect

This commit is contained in:
Jinzhu 2018-02-09 22:58:34 +08:00
parent e9309d361f
commit 89a726ce5d
6 changed files with 19 additions and 5 deletions

View File

@ -33,6 +33,8 @@ type Dialect interface {
HasTable(tableName string) bool
// HasColumn check has column or not
HasColumn(tableName string, columnName string) bool
// ModifyColumn modify column's type
ModifyColumn(tableName string, columnName string, typ string) error
// LimitAndOffsetSQL return generated SQL with Limit and Offset, as mssql has special case
LimitAndOffsetSQL(limit, offset interface{}) string

View File

@ -120,6 +120,11 @@ func (s commonDialect) HasColumn(tableName string, columnName string) bool {
return count > 0
}
func (s commonDialect) ModifyColumn(tableName string, columnName string, typ string) error {
_, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %v ALTER COLUMN %v TYPE %v", tableName, columnName, typ))
return err
}
func (s commonDialect) CurrentDatabase() (name string) {
s.db.QueryRow("SELECT DATABASE()").Scan(&name)
return

View File

@ -127,6 +127,11 @@ func (s mysql) RemoveIndex(tableName string, indexName string) error {
return err
}
func (s mysql) ModifyColumn(tableName string, columnName string, typ string) error {
_, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %v MODIFY COLUMN %v %v", tableName, columnName, typ))
return err
}
func (s mysql) LimitAndOffsetSQL(limit, offset interface{}) (sql string) {
if limit != nil {
if parsedLimit, err := strconv.ParseInt(fmt.Sprint(limit), 0, 0); err == nil && parsedLimit >= 0 {

View File

@ -140,6 +140,11 @@ func (s mssql) HasColumn(tableName string, columnName string) bool {
return count > 0
}
func (s mssql) ModifyColumn(tableName string, columnName string, typ string) error {
_, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %v ALTER COLUMN %v %v", tableName, columnName, typ))
return err
}
func (s mssql) CurrentDatabase() (name string) {
s.db.QueryRow("SELECT DB_NAME() AS [Current Database]").Scan(&name)
return

View File

@ -435,10 +435,7 @@ func TestMultipleIndexes(t *testing.T) {
}
func TestModifyColumnType(t *testing.T) {
dialect := os.Getenv("GORM_DIALECT")
if dialect != "postgres" &&
dialect != "mysql" &&
dialect != "mssql" {
if dialect := os.Getenv("GORM_DIALECT"); dialect != "postgres" && dialect != "mysql" && dialect != "mssql" {
t.Skip("Skipping this because only postgres, mysql and mssql support altering a column type")
}

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 ALTER COLUMN %v TYPE %v", scope.QuotedTableName(), scope.Quote(column), typ)).Exec()
scope.db.AddError(scope.Dialect().ModifyColumn(scope.QuotedTableName(), scope.Quote(column), typ))
}
func (scope *Scope) dropColumn(column string) {