Don't overwrite existing timestamp when creating

This commit is contained in:
Jinzhu 2017-07-31 17:26:36 +08:00
parent 5b8c0dd6b9
commit 35fb16eeba
2 changed files with 42 additions and 2 deletions

View File

@ -32,8 +32,18 @@ func beforeCreateCallback(scope *Scope) {
func updateTimeStampForCreateCallback(scope *Scope) {
if !scope.HasError() {
now := NowFunc()
scope.SetColumn("CreatedAt", now)
scope.SetColumn("UpdatedAt", now)
if createdAtField, ok := scope.FieldByName("CreatedAt"); ok {
if createdAtField.IsBlank {
createdAtField.Set(now)
}
}
if updatedAtField, ok := scope.FieldByName("UpdatedAt"); ok {
if updatedAtField.IsBlank {
updatedAtField.Set(now)
}
}
}
}

View File

@ -5,6 +5,8 @@ import (
"reflect"
"testing"
"time"
"github.com/jinzhu/now"
)
func TestCreate(t *testing.T) {
@ -58,6 +60,34 @@ func TestCreate(t *testing.T) {
}
}
func TestCreateWithExistingTimestamp(t *testing.T) {
user := User{Name: "CreateUserExistingTimestamp"}
timeA := now.MustParse("2016-01-01")
user.CreatedAt = timeA
user.UpdatedAt = timeA
DB.Save(&user)
if user.CreatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) {
t.Errorf("CreatedAt should not be changed")
}
if user.UpdatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) {
t.Errorf("UpdatedAt should not be changed")
}
var newUser User
DB.First(&newUser, user.Id)
if newUser.CreatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) {
t.Errorf("CreatedAt should not be changed")
}
if newUser.UpdatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) {
t.Errorf("UpdatedAt should not be changed")
}
}
type AutoIncrementUser struct {
User
Sequence uint `gorm:"AUTO_INCREMENT"`