From 56fce98cbc591916d0401f0e386679870fe01fb8 Mon Sep 17 00:00:00 2001 From: demoManito <1430482733@qq.com> Date: Sat, 16 Mar 2024 18:10:27 +0800 Subject: [PATCH] fix(create): create multiple pieces of data, primary key value is incorrectly backfilled --- callbacks/create.go | 26 +++++++++++++++++++++++++- schema/field.go | 3 +-- tests/create_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/callbacks/create.go b/callbacks/create.go index b1488b08..63806e4f 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -175,9 +175,33 @@ func Create(config *Config) func(db *gorm.DB) { break } - if _, isZero := pkField.ValueOf(db.Statement.Context, rv); isZero { + if field, isZero := pkField.ValueOf(db.Statement.Context, rv); isZero { db.AddError(pkField.Set(db.Statement.Context, rv, insertID)) insertID += pkField.AutoIncrementIncrement + } else { + // If the primary key is set, the next primary key value is incremented from that primary key + switch f := field.(type) { + case int: + insertID = int64(f) + pkField.AutoIncrementIncrement + case int8: + insertID = int64(f) + pkField.AutoIncrementIncrement + case int16: + insertID = int64(f) + pkField.AutoIncrementIncrement + case int32: + insertID = int64(f) + pkField.AutoIncrementIncrement + case int64: + insertID = f + pkField.AutoIncrementIncrement + case uint: + insertID = int64(f) + pkField.AutoIncrementIncrement + case uint8: + insertID = int64(f) + pkField.AutoIncrementIncrement + case uint16: + insertID = int64(f) + pkField.AutoIncrementIncrement + case uint32: + insertID = int64(f) + pkField.AutoIncrementIncrement + case uint64: + insertID = int64(f) + pkField.AutoIncrementIncrement + } } } } diff --git a/schema/field.go b/schema/field.go index 91e4c0ab..a5336ac4 100644 --- a/schema/field.go +++ b/schema/field.go @@ -471,8 +471,7 @@ func (field *Field) setupValuerAndSetter() { } } - fv, zero := v.Interface(), v.IsZero() - return fv, zero + return v.Interface(), v.IsZero() } } diff --git a/tests/create_test.go b/tests/create_test.go index 5e97a542..f09ca6a6 100644 --- a/tests/create_test.go +++ b/tests/create_test.go @@ -793,3 +793,30 @@ func TestCreateFromMapWithTable(t *testing.T) { t.Fatal("failed to create data from map with table, @id != id") } } + +func TestCreateWithSliceWritebackPrimaryKey(t *testing.T) { + users := []*User{ + { + Age: 20, + }, + { + Model: gorm.Model{ + ID: 100000, + }, + Age: 21, + }, + { + Age: 22, + }, + } + err := DB.Create(users).Error + if err != nil { + t.Fatal(err) + } + if users[1].ID != 100000 { + t.Errorf("users[1].ID should be 100000, but got %v", users[1].ID) + } + if users[2].ID != users[1].ID+1 { + t.Errorf("failed to write back primary key, users[2].ID should be %v, but got %v, %v", users[1].ID+1, users[2].ID, users[0].ID) + } +}