TestFirstOrCreateWithPrimaryKey, close #3192

This commit is contained in:
Jinzhu 2020-07-23 23:41:56 +08:00
parent 7021db3655
commit 6ed697dd02
3 changed files with 23 additions and 12 deletions

View File

@ -70,16 +70,8 @@ func Create(config *Config) func(db *gorm.DB) {
} }
} }
} else { } else {
allUpdated := int(db.RowsAffected) == db.Statement.ReflectValue.Len()
isZero := true
for i := 0; i < db.Statement.ReflectValue.Len(); i++ { for i := 0; i < db.Statement.ReflectValue.Len(); i++ {
if _, isZero := db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.ReflectValue.Index(i)); isZero {
if !allUpdated {
_, isZero = db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.ReflectValue.Index(i))
}
if isZero {
db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.ReflectValue.Index(i), insertID) db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.ReflectValue.Index(i), insertID)
insertID++ insertID++
} }

View File

@ -352,3 +352,22 @@ func TestOmitWithCreate(t *testing.T) {
CheckUser(t, result2, user2) 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)
}
}

View File

@ -6,10 +6,10 @@ require (
github.com/google/uuid v1.1.1 github.com/google/uuid v1.1.1
github.com/jinzhu/now v1.1.1 github.com/jinzhu/now v1.1.1
github.com/lib/pq v1.6.0 github.com/lib/pq v1.6.0
gorm.io/driver/mysql v0.2.9 gorm.io/driver/mysql v0.3.1
gorm.io/driver/postgres v0.2.5 gorm.io/driver/postgres v0.2.6
gorm.io/driver/sqlite v1.0.8 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 gorm.io/gorm v0.2.19
) )