Entity: Return the error if an update statement has failed #4504 #4505

Signed-off-by: Michael Mayer <michael@photoprism.app>
This commit is contained in:
Michael Mayer
2024-09-12 13:19:34 +02:00
parent a542e15ae8
commit be00bcf0b3

View File

@@ -4,12 +4,13 @@ import (
"fmt"
)
// Update updates an existing record in the database.
// Update updates the values of an existing database record.
func Update(m interface{}, keyNames ...string) (err error) {
// Unscoped so soft-deleted records can still be updated.
// Use an unscoped *gorm.DB connection, so that
// soft-deleted database records can also be updated.
db := UnscopedDb()
// New entity?
// Return if the record has not been created yet.
if db.NewRecord(m) {
return fmt.Errorf("new record")
}
@@ -17,20 +18,23 @@ func Update(m interface{}, keyNames ...string) (err error) {
// Extract interface slice with all values including zero.
values, keys, err := ModelValues(m, keyNames...)
// Has keys and values?
// Check if the number of keys matches the number of values.
if err != nil {
return err
} else if len(keys) != len(keyNames) {
return fmt.Errorf("record keys missing")
}
// Update values.
// Execute update statement.
result := db.Model(m).Updates(values)
// Successful?
if result.Error != nil {
// Return an error if the update has failed.
if err = result.Error; err != nil {
return err
} else if result.RowsAffected > 1 {
}
// Verify number of updated rows.
if result.RowsAffected > 1 {
log.Debugf("entity: updated statement affected more than one record - you may have found a bug")
return nil
} else if result.RowsAffected == 1 {
@@ -39,5 +43,5 @@ func Update(m interface{}, keyNames ...string) (err error) {
return fmt.Errorf("record not found")
}
return err
return nil
}