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
2014-01-27 06:47:37 +04:00
value = reflect.New(reflect.ValueOf(field.Value).Type()).Elem()
2014-01-27 04:26:59 +04:00
for _, f := range newDB.NewScope(field.Value).Fields() {
2014-01-27 06:47:37 +04:00
value.FieldByName(f.Name).Set(reflect.ValueOf(f.Value))
2014-01-27 04:26:59 +04:00
}
2014-01-27 06:47:37 +04:00
newDB.Save(value.Addr().Interface())
scope.SetColumn(field.Name, value.Interface())
2014-01-27 04:26:59 +04:00
}
2014-01-27 06:47:37 +04:00
if len(field.ForeignKey) > 0 {
scope.SetColumn(field.ForeignKey, newDB.NewScope(value.Interface()).PrimaryKeyValue())
2014-01-27 04:26:59 +04:00
}
}
}
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()
2014-01-27 06:47:37 +04:00
if len(field.ForeignKey) > 0 {
newDB.NewScope(elem).SetColumn(field.ForeignKey, scope.PrimaryKeyValue())
2014-01-27 04:26:59 +04:00
}
newDB.Save(elem)
}
default:
newDB := scope.NewDB()
if value.CanAddr() {
2014-01-27 06:47:37 +04:00
newDB.NewScope(field.Value).SetColumn(field.ForeignKey, scope.PrimaryKeyValue())
2014-01-27 04:26:59 +04:00
newDB.Save(field.Value)
} else {
destValue := reflect.New(reflect.TypeOf(field.Value)).Elem()
2014-01-27 06:47:37 +04:00
for _, f := range newDB.NewScope(field.Value).Fields() {
2014-01-27 04:26:59 +04:00
destValue.FieldByName(f.Name).Set(reflect.ValueOf(f.Value))
}
elem := destValue.Addr().Interface()
2014-01-27 06:47:37 +04:00
newDB.NewScope(elem).SetColumn(field.ForeignKey, scope.PrimaryKeyValue())
2014-01-27 04:26:59 +04:00
newDB.Save(elem)
scope.SetColumn(field.Name, destValue.Interface())
}
}
}
}
2014-01-26 15:34:06 +04:00
}