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

[#6372] Fixed nullable constraint bug for columns during auto migration #7269

Merged
merged 10 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
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 @@ -524,8 +524,8 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy

// check nullable
if nullable, ok := columnType.Nullable(); ok && nullable == field.NotNull {
// not primary key & database is nullable
if !field.PrimaryKey && nullable {
// not primary key & current database is non-nullable(to be nullable)
if !field.PrimaryKey && !nullable {
alterColumn = true
}
}
Expand Down
18 changes: 16 additions & 2 deletions tests/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ func TestSmartMigrateColumn(t *testing.T) {
ID uint
Name string
Salary float64
Bonus float64 `gorm:"not null"`
Stock float64
Birthday time.Time `gorm:"precision:4"`
}

Expand All @@ -157,8 +159,10 @@ func TestSmartMigrateColumn(t *testing.T) {

type UserMigrateColumn2 struct {
ID uint
Name string `gorm:"size:128"`
Salary float64 `gorm:"precision:2"`
Name string `gorm:"size:128"`
Salary float64 `gorm:"precision:2"`
Bonus float64
Stock float64 `gorm:"not null"`
Birthday time.Time `gorm:"precision:2"`
NameIgnoreMigration string `gorm:"size:100"`
}
Expand All @@ -182,6 +186,16 @@ func TestSmartMigrateColumn(t *testing.T) {
if precision, o, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 2 {
t.Fatalf("salary's precision should be 2, but got %v %v", precision, o)
}
case "bonus":
// allow to change non-nullable to nullable
if nullable, _ := columnType.Nullable(); !nullable {
t.Fatalf("bonus's nullable should be true, bug got %t", nullable)
}
case "stock":
// do not allow to change nullable to non-nullable
if nullable, _ := columnType.Nullable(); !nullable {
t.Fatalf("stock's nullable should be true, bug got %t", nullable)
}
case "birthday":
if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 2 {
t.Fatalf("birthday's precision should be 2, but got %v", precision)
Expand Down
Loading