From de850edb4f87ab713070fcf9788d0d702a644e56 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 11 Jan 2021 19:16:47 +0800 Subject: [PATCH] Fix Change UpdatedAt to current time when doing OnConflict UpdateAll --- callbacks/create.go | 2 +- tests/update_test.go | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/callbacks/create.go b/callbacks/create.go index 634f402b..5656b861 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -281,7 +281,7 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) { } else if field.AutoUpdateTime > 0 { if _, ok := stmt.DB.InstanceGet("gorm:update_track_time"); ok { field.Set(rv, curTime) - values.Values[0][idx], _ = field.ValueOf(rv) + values.Values[i][idx], _ = field.ValueOf(rv) } } } diff --git a/tests/update_test.go b/tests/update_test.go index c6764207..5ad1bb39 100644 --- a/tests/update_test.go +++ b/tests/update_test.go @@ -156,8 +156,8 @@ func TestUpdates(t *testing.T) { t.Errorf("User2's name should be updated") } - if user2.UpdatedAt.Format(time.RFC1123) == user3.UpdatedAt.Format(time.RFC1123) { - t.Errorf("User's updated at should be changed, old %v, new %v", user2.UpdatedAt.Format(time.RFC1123), user3.UpdatedAt.Format(time.RFC1123)) + if user2.UpdatedAt.Format(time.RFC1123Z) == user3.UpdatedAt.Format(time.RFC1123Z) { + t.Errorf("User's updated at should be changed, old %v, new %v", user2.UpdatedAt.Format(time.RFC1123Z), user3.UpdatedAt.Format(time.RFC1123Z)) } // update with gorm exprs @@ -615,13 +615,28 @@ func TestSave(t *testing.T) { time.Sleep(time.Second) user1UpdatedAt := result.UpdatedAt + user2UpdatedAt := user2.UpdatedAt var users = []*User{&result, &user2} DB.Save(&users) - if user1UpdatedAt == result.UpdatedAt { + if user1UpdatedAt.Format(time.RFC1123Z) == result.UpdatedAt.Format(time.RFC1123Z) { t.Fatalf("user's updated at should be changed, expects: %+v, got: %+v", user1UpdatedAt, result.UpdatedAt) } + if user2UpdatedAt.Format(time.RFC1123Z) == user2.UpdatedAt.Format(time.RFC1123Z) { + t.Fatalf("user's updated at should be changed, expects: %+v, got: %+v", user2UpdatedAt, user2.UpdatedAt) + } + + DB.First(&result) + if user1UpdatedAt.Format(time.RFC1123Z) == result.UpdatedAt.Format(time.RFC1123Z) { + t.Fatalf("user's updated at should be changed after reload, expects: %+v, got: %+v", user1UpdatedAt, result.UpdatedAt) + } + + DB.First(&user2) + if user2UpdatedAt.Format(time.RFC1123Z) == user2.UpdatedAt.Format(time.RFC1123Z) { + t.Fatalf("user2's updated at should be changed after reload, expects: %+v, got: %+v", user2UpdatedAt, user2.UpdatedAt) + } + dryDB := DB.Session(&gorm.Session{DryRun: true}) stmt := dryDB.Save(&user).Statement if !regexp.MustCompile("WHERE .id. = [^ ]+$").MatchString(stmt.SQL.String()) {