fix:Issue migrating field with CURRENT_TIMESTAMP (#5906)

Co-authored-by: ningfei <accelerator314@outlook.com>
This commit is contained in:
Ning 2022-12-24 11:02:11 +08:00 committed by GitHub
parent f3c6fc2533
commit bbd2bbe521
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 4 deletions

View File

@ -470,17 +470,19 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
// check default value // check default value
if !field.PrimaryKey { if !field.PrimaryKey {
currentDefaultNotNull := field.HasDefaultValue && !strings.EqualFold(field.DefaultValue, "NULL")
dv, dvNotNull := columnType.DefaultValue() dv, dvNotNull := columnType.DefaultValue()
if dvNotNull && field.DefaultValueInterface == nil { if dvNotNull && !currentDefaultNotNull {
// defalut value -> null // defalut value -> null
alterColumn = true alterColumn = true
} else if !dvNotNull && field.DefaultValueInterface != nil { } else if !dvNotNull && currentDefaultNotNull {
// null -> default value // null -> default value
alterColumn = true alterColumn = true
} else if dv != field.DefaultValue { } else if (field.GORMDataType != schema.Time && dv != field.DefaultValue) ||
(field.GORMDataType == schema.Time && !strings.EqualFold(strings.TrimSuffix(dv, "()"), strings.TrimSuffix(field.DefaultValue, "()"))) {
// default value not equal // default value not equal
// not both null // not both null
if !(field.DefaultValueInterface == nil && !dvNotNull) { if currentDefaultNotNull || dvNotNull {
alterColumn = true alterColumn = true
} }
} }

View File

@ -757,6 +757,32 @@ func TestPrimarykeyID(t *testing.T) {
} }
} }
func TestCurrentTimestamp(t *testing.T) {
if DB.Dialector.Name() != "mysql" {
return
}
type CurrentTimestampTest struct {
ID string `gorm:"primary_key"`
TimeAt *time.Time `gorm:"type:datetime;not null;default:CURRENT_TIMESTAMP;unique"`
}
var err error
err = DB.Migrator().DropTable(&CurrentTimestampTest{})
if err != nil {
t.Errorf("DropTable err:%v", err)
}
err = DB.AutoMigrate(&CurrentTimestampTest{})
if err != nil {
t.Fatalf("AutoMigrate err:%v", err)
}
err = DB.AutoMigrate(&CurrentTimestampTest{})
if err != nil {
t.Fatalf("AutoMigrate err:%v", err)
}
AssertEqual(t, true, DB.Migrator().HasIndex(&CurrentTimestampTest{}, "time_at"))
AssertEqual(t, false, DB.Migrator().HasIndex(&CurrentTimestampTest{}, "time_at_2"))
}
func TestUniqueColumn(t *testing.T) { func TestUniqueColumn(t *testing.T) {
if DB.Dialector.Name() != "mysql" { if DB.Dialector.Name() != "mysql" {
return return