save should be idempotent #6139 (#6149)

This commit is contained in:
black-06 2023-03-23 11:18:57 +08:00 committed by GitHub
parent d2dd0ce4a7
commit 0c7e575f19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 1 deletions

View File

@ -106,7 +106,7 @@ func (db *DB) Save(value interface{}) (tx *DB) {
updateTx := tx.callbacks.Update().Execute(tx.Session(&Session{Initialized: true}))
if updateTx.Error == nil && updateTx.RowsAffected == 0 && !updateTx.DryRun && !selectedUpdate {
return tx.Create(value)
return tx.Clauses(clause.OnConflict{UpdateAll: true}).Create(value)
}
return updateTx

View File

@ -610,6 +610,25 @@ func TestUpdateFromSubQuery(t *testing.T) {
}
}
func TestIdempotentSave(t *testing.T) {
create := Company{
Name: "company_idempotent",
}
DB.Create(&create)
var company Company
if err := DB.Find(&company, "id = ?", create.ID).Error; err != nil {
t.Fatalf("failed to find created company, got err: %v", err)
}
if err := DB.Save(&company).Error; err != nil || company.ID != create.ID {
t.Errorf("failed to save company, got err: %v", err)
}
if err := DB.Save(&company).Error; err != nil || company.ID != create.ID {
t.Errorf("failed to save company, got err: %v", err)
}
}
func TestSave(t *testing.T) {
user := *GetUser("save", Config{})
DB.Create(&user)