2022-04-05 11:40:53 +02:00
|
|
|
package entity
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Update updates an existing record in the database.
|
|
|
|
func Update(m interface{}, keyNames ...string) (err error) {
|
2022-04-16 12:39:47 +02:00
|
|
|
// Unscoped so soft-deleted records can still be updated.
|
|
|
|
db := UnscopedDb()
|
|
|
|
|
2022-04-05 11:40:53 +02:00
|
|
|
// New entity?
|
2022-04-16 12:39:47 +02:00
|
|
|
if db.NewRecord(m) {
|
2022-04-05 11:40:53 +02:00
|
|
|
return fmt.Errorf("new record")
|
|
|
|
}
|
|
|
|
|
2022-04-16 12:39:47 +02:00
|
|
|
// Extract interface slice with all values including zero.
|
2022-04-05 11:40:53 +02:00
|
|
|
values, keys, err := ModelValues(m, keyNames...)
|
|
|
|
|
|
|
|
// Has keys and values?
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
} else if len(keys) != len(keyNames) {
|
|
|
|
return fmt.Errorf("record keys missing")
|
|
|
|
}
|
|
|
|
|
2022-04-16 12:39:47 +02:00
|
|
|
// Update values.
|
|
|
|
result := db.Model(m).Updates(values)
|
2022-04-05 11:40:53 +02:00
|
|
|
|
|
|
|
// Successful?
|
2022-04-16 12:39:47 +02:00
|
|
|
if result.Error != nil {
|
2022-04-05 11:40:53 +02:00
|
|
|
return err
|
2022-04-16 12:39:47 +02:00
|
|
|
} else if result.RowsAffected > 1 {
|
2023-07-15 15:17:41 +02:00
|
|
|
log.Debugf("entity: updated statement affected more than one record - you may have found a bug")
|
2022-04-05 11:40:53 +02:00
|
|
|
return nil
|
2022-04-16 12:39:47 +02:00
|
|
|
} else if result.RowsAffected == 1 {
|
2022-04-05 11:40:53 +02:00
|
|
|
return nil
|
|
|
|
} else if Count(m, keyNames, keys) != 1 {
|
|
|
|
return fmt.Errorf("record not found")
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|