2022-04-10 14:38:51 +02:00
|
|
|
package entity
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2022-04-15 15:48:10 +02:00
|
|
|
"strings"
|
2022-04-10 14:38:51 +02:00
|
|
|
)
|
|
|
|
|
2022-04-15 15:48:10 +02:00
|
|
|
// Save updates a record in the database, or inserts
|
|
|
|
// if it does not exist.
|
2022-04-10 14:38:51 +02:00
|
|
|
func Save(m interface{}, keyNames ...string) (err error) {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2022-04-15 15:48:10 +02:00
|
|
|
err = fmt.Errorf("save: %s (panic)", r)
|
2022-04-10 14:38:51 +02:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2022-04-15 15:48:10 +02:00
|
|
|
// Try a regular update first.
|
2022-04-10 14:38:51 +02:00
|
|
|
if err = Update(m, keyNames...); err == nil {
|
|
|
|
return nil
|
2022-04-15 15:48:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Automatically insert/update record as needed.
|
|
|
|
if err = UnscopedDb().Save(m).Error; err == nil {
|
2022-04-10 14:38:51 +02:00
|
|
|
return nil
|
2022-04-15 15:48:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Try again if database was locked, return otherwise.
|
|
|
|
if !strings.Contains(strings.ToLower(err.Error()), "lock") {
|
2022-04-10 14:38:51 +02:00
|
|
|
return err
|
2022-04-15 15:48:10 +02:00
|
|
|
} else if err = UnscopedDb().Save(m).Error; err == nil {
|
|
|
|
return nil
|
2022-04-10 14:38:51 +02:00
|
|
|
}
|
|
|
|
|
2022-04-15 15:48:10 +02:00
|
|
|
return err
|
2022-04-10 14:38:51 +02:00
|
|
|
}
|