From 6ed697dd0225631c19bcfc43bf8762ced235742c Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 23 Jul 2020 23:41:56 +0800 Subject: [PATCH] TestFirstOrCreateWithPrimaryKey, close #3192 --- callbacks/create.go | 10 +--------- tests/create_test.go | 19 +++++++++++++++++++ tests/go.mod | 6 +++--- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/callbacks/create.go b/callbacks/create.go index de5bf1f8..707b94c1 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -70,16 +70,8 @@ func Create(config *Config) func(db *gorm.DB) { } } } else { - allUpdated := int(db.RowsAffected) == db.Statement.ReflectValue.Len() - isZero := true - for i := 0; i < db.Statement.ReflectValue.Len(); i++ { - - if !allUpdated { - _, isZero = db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.ReflectValue.Index(i)) - } - - if isZero { + if _, isZero := db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.ReflectValue.Index(i)); isZero { db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.ReflectValue.Index(i), insertID) insertID++ } diff --git a/tests/create_test.go b/tests/create_test.go index 46cc06c6..ae6e1232 100644 --- a/tests/create_test.go +++ b/tests/create_test.go @@ -352,3 +352,22 @@ func TestOmitWithCreate(t *testing.T) { CheckUser(t, result2, user2) } + +func TestFirstOrCreateWithPrimaryKey(t *testing.T) { + company := Company{ID: 100, Name: "company100_with_primarykey"} + DB.FirstOrCreate(&company) + + if company.ID != 100 { + t.Errorf("invalid primary key after creating, got %v", company.ID) + } + + companies := []Company{ + {ID: 101, Name: "company101_with_primarykey"}, + {ID: 102, Name: "company102_with_primarykey"}, + } + DB.Create(&companies) + + if companies[0].ID != 101 || companies[1].ID != 102 { + t.Errorf("invalid primary key after creating, got %v, %v", companies[0].ID, companies[1].ID) + } +} diff --git a/tests/go.mod b/tests/go.mod index 3a5b4224..6eb6eb07 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -6,10 +6,10 @@ require ( github.com/google/uuid v1.1.1 github.com/jinzhu/now v1.1.1 github.com/lib/pq v1.6.0 - gorm.io/driver/mysql v0.2.9 - gorm.io/driver/postgres v0.2.5 + gorm.io/driver/mysql v0.3.1 + gorm.io/driver/postgres v0.2.6 gorm.io/driver/sqlite v1.0.8 - gorm.io/driver/sqlserver v0.2.4 + gorm.io/driver/sqlserver v0.2.5 gorm.io/gorm v0.2.19 )