Skip to content

Fix AutoMigrate, alterColumn The previous modifications were ignored #7380

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions migrator/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,9 +549,9 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
case schema.Bool:
v1, _ := strconv.ParseBool(dv)
v2, _ := strconv.ParseBool(field.DefaultValue)
alterColumn = v1 != v2
alterColumn = alterColumn || (v1 != v2)
default:
alterColumn = dv != field.DefaultValue
alterColumn = alterColumn || (dv != field.DefaultValue)
}
}
}
Expand Down
39 changes: 39 additions & 0 deletions tests/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,45 @@ func TestMigrateColumns(t *testing.T) {
}
}

func TestMigrateColumnUpdateSize(t *testing.T) {

sqlite := DB.Dialector.Name() == "sqlite"

type UpdateColumnSizeStruct struct {
gorm.Model
Name string `gorm:"column:name;default:'';size:16"`
}

_ = DB.Migrator().DropTable(&UpdateColumnSizeStruct{})

if err := DB.AutoMigrate(&UpdateColumnSizeStruct{}); err != nil {
t.Errorf("Failed to migrate, got %v", err)
}

type UpdateColumnSizeStruct2 struct {
gorm.Model
Name string `gorm:"column:name;default:'';size:100"` // size change 16 -> 100
}

if err := DB.Table("update_column_size_structs").AutoMigrate(&UpdateColumnSizeStruct2{}); err != nil {
t.Fatalf("no error should happened when auto migrate column, but got %v", err)
}

if columnTypes, err := DB.Migrator().ColumnTypes(&UpdateColumnSizeStruct{}); err != nil {
t.Fatalf("no error should returns for ColumnTypes")
} else {

for _, columnType := range columnTypes {
if columnType.Name() == "name" {
if length, ok := columnType.Length(); !sqlite && (!ok || length != 100) {
t.Fatalf("column name length should be correct, name: %v, length: %v, expects: %v, column: %#v",
columnType.Name(), length, 100, columnType)
}
}
}
}
}

func TestMigrateConstraint(t *testing.T) {
names := []string{"Account", "fk_users_account", "Pets", "fk_users_pets", "Company", "fk_users_company", "Team", "fk_users_team", "Languages", "fk_users_languages"}

Expand Down
Loading