Skip to content

Commit

Permalink
Don't overwrite existing timestamp when creating
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jul 31, 2017
1 parent 5b8c0dd commit 35fb16e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
14 changes: 12 additions & 2 deletions callback_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}

Expand Down
30 changes: 30 additions & 0 deletions create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"reflect"
"testing"
"time"

"github.com/jinzhu/now"
)

func TestCreate(t *testing.T) {
Expand Down Expand Up @@ -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"`
Expand Down

0 comments on commit 35fb16e

Please sign in to comment.