From a65912c5887f850f6262dca68ca8d0dc10ca1bcc Mon Sep 17 00:00:00 2001 From: Cr <631807682@qq.com> Date: Wed, 13 Apr 2022 15:52:07 +0800 Subject: [PATCH] fix: FirstOrCreate RowsAffected (#5250) --- finisher_api.go | 3 +++ tests/create_test.go | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/finisher_api.go b/finisher_api.go index 5e4c3c5a..d35456a6 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -326,6 +326,9 @@ func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB) { } return tx.Model(dest).Updates(assigns) + } else { + // can not use Find RowsAffected + tx.RowsAffected = 0 } } return tx diff --git a/tests/create_test.go b/tests/create_test.go index 2b23d440..3730172f 100644 --- a/tests/create_test.go +++ b/tests/create_test.go @@ -526,3 +526,17 @@ func TestCreateNilPointer(t *testing.T) { t.Fatalf("it is not ErrInvalidValue") } } + +func TestFirstOrCreateRowsAffected(t *testing.T) { + user := User{Name: "TestFirstOrCreateRowsAffected"} + + res := DB.FirstOrCreate(&user, "name = ?", user.Name) + if res.Error != nil || res.RowsAffected != 1 { + t.Fatalf("first or create rows affect err:%v rows:%d", res.Error, res.RowsAffected) + } + + res = DB.FirstOrCreate(&user, "name = ?", user.Name) + if res.Error != nil || res.RowsAffected != 0 { + t.Fatalf("first or create rows affect err:%v rows:%d", res.Error, res.RowsAffected) + } +}