gf/database/gdb/gdb_model_delete.go

75 lines
2.1 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb
import (
"database/sql"
"fmt"
2021-11-13 23:23:55 +08:00
"github.com/gogf/gf/v2/errors/gcode"
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gstr"
)
// Delete does "DELETE FROM ... " statement for the model.
2021-02-08 17:57:21 +08:00
// The optional parameter `where` is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) {
var ctx = m.GetCtx()
if len(where) > 0 {
return m.Where(where[0], where[1:]...).Delete()
}
defer func() {
if err == nil {
m.checkAndRemoveSelectCache(ctx)
}
}()
var (
fieldNameDelete = m.getSoftFieldNameDeleted()
conditionWhere, conditionExtra, conditionArgs = m.formatCondition(ctx, false, false)
)
// Soft deleting.
if !m.unscoped && fieldNameDelete != "" {
in := &HookUpdateInput{
internalParamHookUpdate: internalParamHookUpdate{
internalParamHook: internalParamHook{
2022-05-09 14:22:28 +08:00
link: m.getLink(true),
},
2022-03-21 14:26:56 +08:00
handler: m.hookHandler.Update,
},
2022-05-09 14:22:28 +08:00
Model: m,
Table: m.tables,
Data: fmt.Sprintf(`%s=?`, m.db.GetCore().QuoteString(fieldNameDelete)),
Condition: conditionWhere + conditionExtra,
Args: append([]interface{}{gtime.Now().String()}, conditionArgs...),
}
return in.Next(ctx)
}
conditionStr := conditionWhere + conditionExtra
if !gstr.ContainsI(conditionStr, " WHERE ") {
return nil, gerror.NewCode(
gcode.CodeMissingParameter,
"there should be WHERE condition statement for DELETE operation",
)
}
in := &HookDeleteInput{
internalParamHookDelete: internalParamHookDelete{
internalParamHook: internalParamHook{
2022-05-09 14:22:28 +08:00
link: m.getLink(true),
},
2022-03-21 14:26:56 +08:00
handler: m.hookHandler.Delete,
},
2022-05-09 14:22:28 +08:00
Model: m,
Table: m.tables,
Condition: conditionStr,
Args: conditionArgs,
}
return in.Next(ctx)
}