mirror of https://github.com/go-gorm/gorm.git
fix:Issue migrating field with CURRENT_TIMESTAMP (#5906)
Co-authored-by: ningfei <accelerator314@outlook.com>
This commit is contained in:
parent
f3c6fc2533
commit
bbd2bbe521
|
@ -470,17 +470,19 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
|
|||
|
||||
// check default value
|
||||
if !field.PrimaryKey {
|
||||
currentDefaultNotNull := field.HasDefaultValue && !strings.EqualFold(field.DefaultValue, "NULL")
|
||||
dv, dvNotNull := columnType.DefaultValue()
|
||||
if dvNotNull && field.DefaultValueInterface == nil {
|
||||
if dvNotNull && !currentDefaultNotNull {
|
||||
// defalut value -> null
|
||||
alterColumn = true
|
||||
} else if !dvNotNull && field.DefaultValueInterface != nil {
|
||||
} else if !dvNotNull && currentDefaultNotNull {
|
||||
// null -> default value
|
||||
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
|
||||
// not both null
|
||||
if !(field.DefaultValueInterface == nil && !dvNotNull) {
|
||||
if currentDefaultNotNull || dvNotNull {
|
||||
alterColumn = true
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
if DB.Dialector.Name() != "mysql" {
|
||||
return
|
||||
|
|
Loading…
Reference in New Issue