fix(migrator): Tag default:'null' always causes field migration #5953 (#5954)

* fix(migrator): Tag default:'null' always causes field migration #5953

* Update migrate_test.go

* Update migrate_test.go

* Update migrate_test.go

Co-authored-by: Jinzhu <wosmvp@gmail.com>
This commit is contained in:
Haibo 2023-01-01 22:14:28 +08:00 committed by GitHub
parent da2b2861de
commit 16a272209a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 1 deletions

View File

@ -493,7 +493,7 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
// check default value
if !field.PrimaryKey {
currentDefaultNotNull := field.HasDefaultValue && !strings.EqualFold(field.DefaultValue, "NULL")
currentDefaultNotNull := field.HasDefaultValue && (field.DefaultValueInterface != nil || !strings.EqualFold(field.DefaultValue, "NULL"))
dv, dvNotNull := columnType.DefaultValue()
if dvNotNull && !currentDefaultNotNull {
// defalut value -> null

View File

@ -1204,6 +1204,72 @@ func TestMigrateSameEmbeddedFieldName(t *testing.T) {
AssertEqual(t, nil, err)
}
func TestMigrateDefaultNullString(t *testing.T) {
if DB.Dialector.Name() == "sqlserver" {
// sqlserver driver treats NULL and 'NULL' the same
t.Skip("skip sqlserver")
}
type NullModel struct {
ID uint
Content string `gorm:"default:null"`
}
type NullStringModel struct {
ID uint
Content string `gorm:"default:'null'"`
}
tableName := "null_string_model"
DB.Migrator().DropTable(tableName)
err := DB.Table(tableName).AutoMigrate(&NullModel{})
AssertEqual(t, err, nil)
// default null -> 'null'
err = DB.Table(tableName).AutoMigrate(&NullStringModel{})
AssertEqual(t, err, nil)
columnType, err := findColumnType(tableName, "content")
AssertEqual(t, err, nil)
defVal, ok := columnType.DefaultValue()
AssertEqual(t, defVal, "null")
AssertEqual(t, ok, true)
// default 'null' -> 'null'
session := DB.Session(&gorm.Session{Logger: Tracer{
Logger: DB.Config.Logger,
Test: func(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
sql, _ := fc()
if strings.HasPrefix(sql, "ALTER TABLE") {
t.Errorf("shouldn't execute: sql=%s", sql)
}
},
}})
err = session.Table(tableName).AutoMigrate(&NullStringModel{})
AssertEqual(t, err, nil)
columnType, err = findColumnType(tableName, "content")
AssertEqual(t, err, nil)
defVal, ok = columnType.DefaultValue()
AssertEqual(t, defVal, "null")
AssertEqual(t, ok, true)
// default 'null' -> null
err = DB.Table(tableName).AutoMigrate(&NullModel{})
AssertEqual(t, err, nil)
columnType, err = findColumnType(tableName, "content")
AssertEqual(t, err, nil)
defVal, ok = columnType.DefaultValue()
AssertEqual(t, defVal, "")
AssertEqual(t, ok, false)
}
func TestMigrateIgnoreRelations(t *testing.T) {
type RelationModel1 struct {
ID uint