gorm/callback_create.go

75 lines
2.0 KiB
Go
Raw Normal View History

2014-01-26 08:41:37 +04:00
package gorm
2014-01-26 15:34:06 +04:00
import (
"fmt"
"strings"
"time"
)
2014-01-26 08:41:37 +04:00
func BeforeCreate(scope *Scope) {
scope.CallMethod("BeforeSave")
scope.CallMethod("BeforeCreate")
}
2014-01-27 18:36:08 +04:00
func UpdateTimeStampWhenCreate(scope *Scope) {
2014-01-26 08:41:37 +04:00
if !scope.HasError() {
2014-01-26 17:23:53 +04:00
scope.SetColumn("CreatedAt", time.Now())
scope.SetColumn("UpdatedAt", time.Now())
2014-01-27 07:06:13 +04:00
}
}
2014-01-26 17:23:53 +04:00
2014-01-27 07:06:13 +04:00
func Create(scope *Scope) {
defer scope.Trace(time.Now())
if !scope.HasError() {
2014-01-26 15:34:06 +04:00
// set create sql
var sqls, columns []string
for _, field := range scope.Fields() {
2014-01-26 17:23:53 +04:00
if field.DBName != scope.PrimaryKey() && len(field.SqlTag) > 0 && !field.IsIgnored {
columns = append(columns, scope.quote(field.DBName))
sqls = append(sqls, scope.AddToVars(field.Value))
2014-01-26 15:34:06 +04:00
}
}
scope.Raw(fmt.Sprintf(
"INSERT INTO %v (%v) VALUES (%v) %v",
scope.TableName(),
strings.Join(columns, ","),
strings.Join(sqls, ","),
scope.Dialect().ReturningStr(scope.PrimaryKey()),
))
// execute create sql
2014-01-26 08:41:37 +04:00
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))
}
2014-01-26 15:34:06 +04:00
if !scope.HasError() {
scope.SetColumn(scope.PrimaryKey(), id)
}
2014-01-26 08:41:37 +04:00
}
}
func AfterCreate(scope *Scope) {
scope.CallMethod("AfterCreate")
scope.CallMethod("AfterSave")
}
func init() {
2014-01-26 15:34:06 +04:00
DefaultCallback.Create().Register("begin_transaction", BeginTransaction)
2014-01-26 08:41:37 +04:00
DefaultCallback.Create().Register("before_create", BeforeCreate)
DefaultCallback.Create().Register("save_before_associations", SaveBeforeAssociations)
2014-01-27 18:36:08 +04:00
DefaultCallback.Create().Register("update_time_stamp_when_create", UpdateTimeStampWhenCreate)
2014-01-26 08:41:37 +04:00
DefaultCallback.Create().Register("create", Create)
DefaultCallback.Create().Register("save_after_associations", SaveAfterAssociations)
DefaultCallback.Create().Register("after_create", AfterCreate)
2014-01-26 15:34:06 +04:00
DefaultCallback.Create().Register("commit_or_rollback_transaction", CommitOrRollbackTransaction)
2014-01-26 08:41:37 +04:00
}