gorm/callback_update.go

54 lines
1.5 KiB
Go
Raw Normal View History

2014-01-26 08:46:04 +04:00
package gorm
2014-01-27 07:06:13 +04:00
import (
"fmt"
"strings"
"time"
)
2014-01-26 08:46:04 +04:00
func BeforeUpdate(scope *Scope) {
scope.CallMethod("BeforeSave")
scope.CallMethod("BeforeUpdate")
}
2014-01-27 07:06:13 +04:00
func UpdateTimeStampWhenUpdate(scope *Scope) {
if !scope.HasError() {
scope.SetColumn("UpdatedAt", time.Now())
}
}
2014-01-26 08:46:04 +04:00
func Update(scope *Scope) {
if !scope.HasError() {
2014-01-27 07:06:13 +04:00
var sqls []string
for _, field := range scope.Fields() {
if field.DBName != scope.PrimaryKey() && len(field.SqlTag) > 0 && !field.IsIgnored {
sqls = append(sqls, fmt.Sprintf("%v = %v", scope.quote(field.DBName), scope.AddToVars(field.Value)))
2014-01-26 08:46:04 +04:00
}
}
2014-01-27 07:06:13 +04:00
scope.Raw(fmt.Sprintf(
"UPDATE %v SET %v %v",
scope.TableName(),
strings.Join(sqls, ", "),
scope.CombinedConditionSql(),
))
scope.Exec()
2014-01-26 08:46:04 +04:00
}
}
func AfterUpdate(scope *Scope) {
scope.CallMethod("AfterUpdate")
scope.CallMethod("AfterSave")
}
func init() {
2014-01-27 07:06:13 +04:00
DefaultCallback.Update().Register("begin_transaction", BeginTransaction)
2014-01-26 08:46:04 +04:00
DefaultCallback.Update().Register("before_update", BeforeUpdate)
DefaultCallback.Update().Register("save_before_associations", SaveBeforeAssociations)
2014-01-27 07:06:13 +04:00
DefaultCallback.Update().Register("update_time_stamp_when_update", UpdateTimeStampWhenUpdate)
2014-01-26 08:46:04 +04:00
DefaultCallback.Update().Register("update", Update)
DefaultCallback.Update().Register("save_after_associations", SaveAfterAssociations)
DefaultCallback.Update().Register("after_update", AfterUpdate)
2014-01-27 07:06:13 +04:00
DefaultCallback.Update().Register("commit_or_rollback_transaction", CommitOrRollbackTransaction)
2014-01-26 08:46:04 +04:00
}