callback_delete.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package gorm
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. // Define callbacks for deleting
  7. func init() {
  8. DefaultCallback.Delete().Register("gorm:begin_transaction", beginTransactionCallback)
  9. DefaultCallback.Delete().Register("gorm:before_delete", beforeDeleteCallback)
  10. DefaultCallback.Delete().Register("gorm:delete", deleteCallback)
  11. DefaultCallback.Delete().Register("gorm:after_delete", afterDeleteCallback)
  12. DefaultCallback.Delete().Register("gorm:commit_or_rollback_transaction", commitOrRollbackTransactionCallback)
  13. }
  14. // beforeDeleteCallback will invoke `BeforeDelete` method before deleting
  15. func beforeDeleteCallback(scope *Scope) {
  16. if scope.DB().HasBlockGlobalUpdate() && !scope.hasConditions() {
  17. scope.Err(errors.New("Missing WHERE clause while deleting"))
  18. return
  19. }
  20. if !scope.HasError() {
  21. scope.CallMethod("BeforeDelete")
  22. }
  23. }
  24. // deleteCallback used to delete data from database or set deleted_at to current time (when using with soft delete)
  25. func deleteCallback(scope *Scope) {
  26. if !scope.HasError() {
  27. var extraOption string
  28. if str, ok := scope.Get("gorm:delete_option"); ok {
  29. extraOption = fmt.Sprint(str)
  30. }
  31. deletedAtField, hasDeletedAtField := scope.FieldByName("DeletedAt")
  32. if !scope.Search.Unscoped && hasDeletedAtField {
  33. scope.Raw(fmt.Sprintf(
  34. "UPDATE %v SET %v=%v%v%v",
  35. scope.QuotedTableName(),
  36. scope.Quote(deletedAtField.DBName),
  37. scope.AddToVars(NowFunc()),
  38. addExtraSpaceIfExist(scope.CombinedConditionSql()),
  39. addExtraSpaceIfExist(extraOption),
  40. )).Exec()
  41. } else {
  42. scope.Raw(fmt.Sprintf(
  43. "DELETE FROM %v%v%v",
  44. scope.QuotedTableName(),
  45. addExtraSpaceIfExist(scope.CombinedConditionSql()),
  46. addExtraSpaceIfExist(extraOption),
  47. )).Exec()
  48. }
  49. }
  50. }
  51. // afterDeleteCallback will invoke `AfterDelete` method after deleting
  52. func afterDeleteCallback(scope *Scope) {
  53. if !scope.HasError() {
  54. scope.CallMethod("AfterDelete")
  55. }
  56. }