Skip to content

Commit

Permalink
fix:Issue migrating field with CURRENT_TIMESTAMP
Browse files Browse the repository at this point in the history
  • Loading branch information
0fx committed Dec 7, 2022
1 parent d9525d4 commit bfdaf99
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
10 changes: 6 additions & 4 deletions migrator/migrator.go
Expand Up @@ -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
}
}
Expand Down
26 changes: 26 additions & 0 deletions tests/migrate_test.go
Expand Up @@ -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
Expand Down

0 comments on commit bfdaf99

Please sign in to comment.