-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Description
According to https://gorm.io/docs/update.html#Save-All-Fields
"Save is a combination function. If save value does not contain primary key, it will execute Create, otherwise it will execute Update (with all fields)."
The library is working as described in the quote, strictly speaking. But Save is not idempotent, and I may obviously be wrong but I don't think it is intuitive or convenient.
According to this code snippet at the end of the Save function :
updateTx := tx.callbacks.Update().Execute(tx.Session(&Session{Initialized: true}))
if updateTx.Error == nil && updateTx.RowsAffected == 0 && !updateTx.DryRun && !selectedUpdate {
return tx.Create(value)
}
If I call the Save function twice with the same object (assuming this object has an ID), the second time it is called no rows will be updated (because all fields keep the same value), thus the Create function will be called and likely provoke an error since the object already exists.
Obviously, I could append a pull request to the issue, simply deleting the if and its content, which should make the Save function idempotent, but I guess this code has a reason to be there. In case everything is working as intended, I fail to see a simple, clean and convenient way to perform a "if primary key is set, update else create". I looked into FirstOrCreate with Assign but I don't understand how to use it in a generic way. Is there something I am missing?
Regards