callback_delete.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. if !scope.Search.Unscoped && scope.HasColumn("DeletedAt") {
  32. scope.Raw(fmt.Sprintf(
  33. "UPDATE %v SET deleted_at=%v%v%v",
  34. scope.QuotedTableName(),
  35. scope.AddToVars(NowFunc()),
  36. addExtraSpaceIfExist(scope.CombinedConditionSql()),
  37. addExtraSpaceIfExist(extraOption),
  38. )).Exec()
  39. } else {
  40. scope.Raw(fmt.Sprintf(
  41. "DELETE FROM %v%v%v",
  42. scope.QuotedTableName(),
  43. addExtraSpaceIfExist(scope.CombinedConditionSql()),
  44. addExtraSpaceIfExist(extraOption),
  45. )).Exec()
  46. }
  47. }
  48. }
  49. // afterDeleteCallback will invoke `AfterDelete` method after deleting
  50. func afterDeleteCallback(scope *Scope) {
  51. if !scope.HasError() {
  52. scope.CallMethod("AfterDelete")
  53. }
  54. }