gorm/callback_shared.go

76 lines
2.0 KiB
Go
Raw Normal View History

2014-01-26 13:10:33 +04:00
package gorm
2014-01-27 04:26:59 +04:00
import "reflect"
2014-01-26 13:10:33 +04:00
func BeginTransaction(scope *Scope) {
scope.Begin()
}
func CommitOrRollbackTransaction(scope *Scope) {
scope.CommitOrRollback()
}
2014-01-26 15:34:06 +04:00
func SaveBeforeAssociations(scope *Scope) {
2014-01-27 04:26:59 +04:00
for _, field := range scope.Fields() {
if field.BeforeAssociation && !field.IsBlank && !field.IsIgnored {
value := reflect.ValueOf(field.Value)
newDB := scope.NewDB()
if value.CanAddr() {
newDB.Save(value.Addr().Interface())
} else {
// If can't take address, then clone the value and set it back
destValue := reflect.New(reflect.ValueOf(field.Value).Type()).Elem()
for _, f := range newDB.NewScope(field.Value).Fields() {
destValue.FieldByName(f.Name).Set(reflect.ValueOf(f.Value))
}
newDB.Save(destValue.Addr().Interface())
scope.SetColumn(field.Name, destValue.Interface())
}
if len(field.foreignKey) > 0 {
scope.SetColumn(field.foreignKey, scope.PrimaryKeyValue())
}
}
}
2014-01-26 15:34:06 +04:00
}
func SaveAfterAssociations(scope *Scope) {
2014-01-27 04:26:59 +04:00
for _, field := range scope.Fields() {
if field.AfterAssociation && !field.IsBlank && !field.IsIgnored {
value := reflect.ValueOf(field.Value)
switch value.Kind() {
case reflect.Slice:
for i := 0; i < value.Len(); i++ {
newDB := scope.NewDB()
elem := value.Index(i).Addr().Interface()
if len(field.foreignKey) > 0 {
newDB.NewScope(elem).SetColumn(field.foreignKey, scope.PrimaryKeyValue())
}
newDB.Save(elem)
}
default:
newDB := scope.NewDB()
if value.CanAddr() {
newDB.NewScope(field.Value).SetColumn(field.foreignKey, scope.PrimaryKeyValue())
newDB.Save(field.Value)
} else {
destValue := reflect.New(reflect.TypeOf(field.Value)).Elem()
for _, f := range newDB.NewScope(destValue).Fields() {
destValue.FieldByName(f.Name).Set(reflect.ValueOf(f.Value))
}
elem := destValue.Addr().Interface()
newDB.NewScope(elem).SetColumn(field.foreignKey, scope.PrimaryKeyValue())
newDB.Save(elem)
scope.SetColumn(field.Name, destValue.Interface())
}
}
}
}
2014-01-26 15:34:06 +04:00
}