Skip to content

Commit

Permalink
save should be idempotent #6139 (#6149)
Browse files Browse the repository at this point in the history
  • Loading branch information
black-06 authored Mar 23, 2023
1 parent d2dd0ce commit 0c7e575
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions tests/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 0c7e575

Please sign in to comment.