From 12c3df1f47c83496bf579fa04f82a437cab28b8c Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 26 Jan 2014 12:46:04 +0800 Subject: [PATCH] Add callback update --- callback_update.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 callback_update.go diff --git a/callback_update.go b/callback_update.go new file mode 100644 index 00000000..1cfe6d8d --- /dev/null +++ b/callback_update.go @@ -0,0 +1,35 @@ +package gorm + +func BeforeUpdate(scope *Scope) { + scope.CallMethod("BeforeSave") + scope.CallMethod("BeforeUpdate") +} + +func Update(scope *Scope) { + if !scope.HasError() { + var id interface{} + if scope.Dialect().SupportLastInsertId() { + if sql_result, err := scope.DB().Exec(scope.Sql, scope.SqlVars...); scope.Err(err) == nil { + id, err = sql_result.LastInsertId() + scope.Err(err) + } + } else { + scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) + } + + scope.SetColumn(scope.PrimaryKey(), id) + } +} + +func AfterUpdate(scope *Scope) { + scope.CallMethod("AfterUpdate") + scope.CallMethod("AfterSave") +} + +func init() { + DefaultCallback.Update().Register("before_update", BeforeUpdate) + DefaultCallback.Update().Register("save_before_associations", SaveBeforeAssociations) + DefaultCallback.Update().Register("update", Update) + DefaultCallback.Update().Register("save_after_associations", SaveAfterAssociations) + DefaultCallback.Update().Register("after_update", AfterUpdate) +}