87 lines
2.1 KiB
Go
87 lines
2.1 KiB
Go
package model
|
||
|
||
import (
|
||
"context"
|
||
"strings"
|
||
"time"
|
||
"tyc-server/common/globalkey"
|
||
|
||
"github.com/Masterminds/squirrel"
|
||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||
)
|
||
|
||
var _ QueryModel = (*customQueryModel)(nil)
|
||
|
||
type (
|
||
// QueryModel is an interface to be customized, add more methods here,
|
||
// and implement the added methods in customQueryModel.
|
||
QueryModel interface {
|
||
queryModel
|
||
DeleteBefore(ctx context.Context, before time.Time, conditions ...squirrel.SelectBuilder) (int64, error)
|
||
}
|
||
|
||
customQueryModel struct {
|
||
*defaultQueryModel
|
||
}
|
||
)
|
||
|
||
// NewQueryModel returns a model for the database table.
|
||
func NewQueryModel(conn sqlx.SqlConn, c cache.CacheConf) QueryModel {
|
||
return &customQueryModel{
|
||
defaultQueryModel: newQueryModel(conn, c),
|
||
}
|
||
}
|
||
func (m *customQueryModel) DeleteBefore(ctx context.Context, before time.Time, conditions ...squirrel.SelectBuilder) (int64, error) {
|
||
var affected int64 = 0
|
||
|
||
// 使用事务处理批量删除
|
||
err := m.defaultQueryModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
|
||
// 创建基本的删除条件
|
||
deleteBuilder := squirrel.Delete(m.defaultQueryModel.table).
|
||
Where("create_time < ?", before.Format("2006-01-02 15:04:05")).
|
||
Where("del_state = ?", globalkey.DelStateNo)
|
||
|
||
// 如果提供了额外的查询条件,合并到删除条件中
|
||
if len(conditions) > 0 {
|
||
// 获取Where条件
|
||
whereSQL, whereArgs, err := conditions[0].Where("1=0").ToSql()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
// 解析出where子句,去掉"SELECT * FROM xxx WHERE"部分
|
||
whereParts := whereSQL[strings.LastIndex(whereSQL, "WHERE")+6:]
|
||
|
||
if len(whereParts) > 0 && len(whereArgs) > 0 {
|
||
deleteBuilder = deleteBuilder.Where(whereParts, whereArgs...)
|
||
}
|
||
}
|
||
|
||
// 生成SQL
|
||
query, args, err := deleteBuilder.ToSql()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
result, err := session.ExecCtx(ctx, query, args...)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
rows, err := result.RowsAffected()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
affected = rows
|
||
return nil
|
||
})
|
||
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
|
||
return affected, nil
|
||
}
|