2014-01-26 08:41:37 +04:00
|
|
|
package gorm
|
|
|
|
|
2016-11-04 19:41:31 +03:00
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
)
|
2014-01-26 08:41:37 +04:00
|
|
|
|
2016-01-17 15:51:11 +03:00
|
|
|
// Define callbacks for deleting
|
2016-01-17 11:28:32 +03:00
|
|
|
func init() {
|
2016-03-05 14:22:29 +03:00
|
|
|
DefaultCallback.Delete().Register("gorm:begin_transaction", beginTransactionCallback)
|
|
|
|
DefaultCallback.Delete().Register("gorm:before_delete", beforeDeleteCallback)
|
|
|
|
DefaultCallback.Delete().Register("gorm:delete", deleteCallback)
|
|
|
|
DefaultCallback.Delete().Register("gorm:after_delete", afterDeleteCallback)
|
|
|
|
DefaultCallback.Delete().Register("gorm:commit_or_rollback_transaction", commitOrRollbackTransactionCallback)
|
2016-01-17 11:28:32 +03:00
|
|
|
}
|
|
|
|
|
2016-01-17 15:51:11 +03:00
|
|
|
// beforeDeleteCallback will invoke `BeforeDelete` method before deleting
|
2016-01-17 10:30:42 +03:00
|
|
|
func beforeDeleteCallback(scope *Scope) {
|
2016-11-04 19:41:31 +03:00
|
|
|
if scope.DB().HasBlockGlobalUpdate() && !scope.hasConditions() {
|
|
|
|
scope.Err(errors.New("Missing WHERE clause while deleting"))
|
|
|
|
return
|
|
|
|
}
|
2016-01-17 11:14:14 +03:00
|
|
|
if !scope.HasError() {
|
|
|
|
scope.CallMethod("BeforeDelete")
|
|
|
|
}
|
2014-01-26 08:41:37 +04:00
|
|
|
}
|
|
|
|
|
2016-01-17 15:51:11 +03:00
|
|
|
// deleteCallback used to delete data from database or set deleted_at to current time (when using with soft delete)
|
2016-01-17 10:30:42 +03:00
|
|
|
func deleteCallback(scope *Scope) {
|
2014-01-26 15:34:06 +04:00
|
|
|
if !scope.HasError() {
|
2016-02-15 14:36:48 +03:00
|
|
|
var extraOption string
|
|
|
|
if str, ok := scope.Get("gorm:delete_option"); ok {
|
|
|
|
extraOption = fmt.Sprint(str)
|
|
|
|
}
|
|
|
|
|
2015-03-12 10:01:59 +03:00
|
|
|
if !scope.Search.Unscoped && scope.HasColumn("DeletedAt") {
|
2016-02-15 14:36:48 +03:00
|
|
|
scope.Raw(fmt.Sprintf(
|
|
|
|
"UPDATE %v SET deleted_at=%v%v%v",
|
|
|
|
scope.QuotedTableName(),
|
|
|
|
scope.AddToVars(NowFunc()),
|
|
|
|
addExtraSpaceIfExist(scope.CombinedConditionSql()),
|
|
|
|
addExtraSpaceIfExist(extraOption),
|
|
|
|
)).Exec()
|
2014-01-26 15:34:06 +04:00
|
|
|
} else {
|
2016-02-15 14:36:48 +03:00
|
|
|
scope.Raw(fmt.Sprintf(
|
|
|
|
"DELETE FROM %v%v%v",
|
|
|
|
scope.QuotedTableName(),
|
|
|
|
addExtraSpaceIfExist(scope.CombinedConditionSql()),
|
|
|
|
addExtraSpaceIfExist(extraOption),
|
|
|
|
)).Exec()
|
2014-01-26 15:34:06 +04:00
|
|
|
}
|
2014-01-26 08:41:37 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-17 15:51:11 +03:00
|
|
|
// afterDeleteCallback will invoke `AfterDelete` method after deleting
|
2016-01-17 10:30:42 +03:00
|
|
|
func afterDeleteCallback(scope *Scope) {
|
2016-01-17 11:14:14 +03:00
|
|
|
if !scope.HasError() {
|
|
|
|
scope.CallMethod("AfterDelete")
|
|
|
|
}
|
2014-01-26 08:41:37 +04:00
|
|
|
}
|