Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix : fail to alter existing boolean column from smallint with default value to boolean in postgres (#180) #181

Merged
merged 12 commits into from
May 28, 2023
Merged
34 changes: 27 additions & 7 deletions migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,7 @@ func (m Migrator) AlterColumn(value interface{}, field string) error {
return err
}
} else {
if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? TYPE ?"+m.genUsingExpression(fileType.SQL, fieldColumnType.DatabaseTypeName()),
m.CurrentTable(stmt), clause.Column{Name: field.DBName}, fileType, clause.Column{Name: field.DBName}, fileType).Error; err != nil {
if err := m.ModifyColumn(value, field, fileType, fieldColumnType); err != nil {
return err
}
}
Expand Down Expand Up @@ -375,14 +374,35 @@ func (m Migrator) AlterColumn(value interface{}, field string) error {
return nil
}

func (m Migrator) genUsingExpression(targetType, sourceType string) string {
if targetType == "boolean" {
switch sourceType {
func (m Migrator) ModifyColumn(value interface{}, field *schema.Field, targetType clause.Expr, existingColumn *migrator.ColumnType) error {
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
alterSQL := "ALTER TABLE ? ALTER COLUMN ? TYPE ? USING ?::?"
isUncastableDefaultValue := false

if targetType.SQL == "boolean" {
switch existingColumn.DatabaseTypeName() {
case "int2", "int8", "numeric":
return " USING ?::INT::?"
alterSQL = "ALTER TABLE ? ALTER COLUMN ? TYPE ? USING ?::int::?"
}
isUncastableDefaultValue = true
}
return " USING ?::?"

return m.RunWithValue(value, func(stmt *gorm.Statement) error {
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
if dv, _ := existingColumn.DefaultValue(); dv != "" && isUncastableDefaultValue {
if err := m.DropDefaultValue(value, field); err != nil {
return err
}
}
if err := m.DB.Exec(alterSQL, m.CurrentTable(stmt), clause.Column{Name: field.DBName}, targetType, clause.Column{Name: field.DBName}, targetType).Error; err != nil {
return err
}
return nil
})
}

func (m Migrator) DropDefaultValue(value interface{}, field *schema.Field) error {
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
return m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? DROP DEFAULT", m.CurrentTable(stmt), clause.Column{Name: field.DBName}).Error
})
}

func (m Migrator) HasConstraint(value interface{}, name string) bool {
Expand Down