mirror of https://github.com/go-gorm/gorm.git
Don't overwrite existing timestamp when creating
This commit is contained in:
parent
5b8c0dd6b9
commit
35fb16eeba
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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"`
|
||||
|
|
Loading…
Reference in New Issue