Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
demoManito committed Aug 27, 2024
1 parent d34bcec commit 6041c66
Showing 1 changed file with 21 additions and 26 deletions.
47 changes: 21 additions & 26 deletions callbacks/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,42 +45,37 @@ func BeforeUpdate(db *gorm.DB) {
if db.Statement.Schema.BeforeUpdate {
beforeUpdateInterface, isBeforeUpdateHook = value.(BeforeUpdateInterface)
}

var (
called bool
rv reflect.Value
rvSnapshot reflect.Value
)
if isBeforeSaveHook || isBeforeUpdateHook {
called = true
// save a snapshot of the struct before the hook was called
rv = reflect.Indirect(reflect.ValueOf(value))
rvSnapshot = reflect.New(rv.Type()).Elem()
rvSnapshot.Set(rv)
if !isBeforeSaveHook && !isBeforeUpdateHook {
return false
}

// save a snapshot of the struct before the hook was called
rv := reflect.Indirect(reflect.ValueOf(value))
rvSnapshot := reflect.New(rv.Type()).Elem()
rvSnapshot.Set(rv)

if isBeforeSaveHook {
db.AddError(beforeSaveInterface.BeforeSave(tx))
}
if isBeforeUpdateHook {
db.AddError(beforeUpdateInterface.BeforeUpdate(tx))
}

if called {
for _, field := range db.Statement.Schema.Fields {
if field.PrimaryKey {
continue
}
dbFieldName, ok := field.TagSettings["COLUMN"]
if !ok {
continue
}
// compare with the snapshot and update the field if there is a difference
if !reflect.DeepEqual(rv.FieldByName(field.Name).Interface(), rvSnapshot.FieldByName(field.Name).Interface()) {
db.Statement.SetColumn(dbFieldName, rv.FieldByName(field.Name).Interface())
}
for _, field := range db.Statement.Schema.Fields {
if field.PrimaryKey {
continue
}
dbFieldName, ok := field.TagSettings["COLUMN"]
if !ok {
continue
}
// compare with the snapshot and update the field if there is a difference
if !reflect.DeepEqual(rv.FieldByName(field.Name).Interface(), rvSnapshot.FieldByName(field.Name).Interface()) {
db.Statement.SetColumn(dbFieldName, rv.FieldByName(field.Name).Interface())
}
}
return called

return true
})
}
}
Expand Down

0 comments on commit 6041c66

Please sign in to comment.