提交 1ab6fb03 authored 作者: mooncake's avatar mooncake

update

上级 d7fe160a
......@@ -18,7 +18,7 @@ import (
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/xerrors/xerror"
"gitlab.wanzhuangkj.com/tush/xpkg/rd/nacos"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/dxsf"
goutils "gitlab.wanzhuangkj.com/tush/xpkg/utils/go_utils"
goutils "gitlab.wanzhuangkj.com/tush/xpkg/utils/goutils"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/sliceUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
......
......@@ -232,17 +232,27 @@ func GetIDMapSliceIDs[ID xtype.Key, T IID[ID]](m map[ID][]*T) []ID {
return st.Slice()
}
func CompareSlice[ID xtype.Key, T IIDTable[ID], BizSlice ~[]*T](ids []ID, bizSlice BizSlice, errCode *errcode.Error) error {
type ICode interface {
Code() int
}
func CompareSlice[ID xtype.Key, T IIDTable[ID], BizSlice ~[]*T](ids []ID, bizSlice BizSlice, errCode error) error {
if len(ids) == 0 {
return nil
}
if len(bizSlice) < len(ids) {
if len(bizSlice) == 0 {
return xerror.NewC(errCode.Code(), errCode.Msg())
if v, ok := errCode.(*errcode.Error); ok {
return xerror.NewC(v.Code(), v.Msg())
}
return xerror.New(errCode.Error())
}
deltaIDs := SetDifference(ids, GetIDs[ID](bizSlice))
if len(deltaIDs) > 0 {
return xerror.NewC(errCode.Code(), fmt.Sprintf("%s[ids:%s]", errCode.Msg(), Join(deltaIDs, ",")))
if v, ok := errCode.(*errcode.Error); ok {
return xerror.NewC(v.Code(), fmt.Sprintf("%s[ids:%s]", v.Msg(), Join(deltaIDs, ",")))
}
return xerror.New(errCode.Error())
}
}
return nil
......
package base
import "strings"
// import "strings"
type Condition interface {
SetWhere(k string, v []interface{})
SetOr(k string, v []interface{})
SetOrder(k string)
SetJoinOn(t, on string) Condition
}
// type Condition interface {
// SetWhere(k string, v []interface{})
// SetOr(k string, v []interface{})
// SetOrder(k string)
// SetJoinOn(t, on string) Condition
// }
type GormCondition struct {
GormPublic
Join []*GormJoin
}
// type GormCondition struct {
// GormPublic
// Join []*GormJoin
// }
type GormPublic struct {
Where map[string][]interface{}
Order []string
Or map[string][]interface{}
}
// type GormPublic struct {
// Where map[string][]interface{}
// Order []string
// Or map[string][]interface{}
// }
type GormJoin struct {
Type string
JoinOn string
GormPublic
}
// type GormJoin struct {
// Type string
// JoinOn string
// GormPublic
// }
func (e *GormJoin) SetJoinOn(t, on string) Condition {
return nil
}
// func (e *GormJoin) SetJoinOn(t, on string) Condition {
// return nil
// }
func (e *GormPublic) SetWhere(k string, v []interface{}) {
if e.Where == nil {
e.Where = make(map[string][]interface{})
}
e.Where[k] = v
}
// func (e *GormPublic) SetWhere(k string, v []interface{}) {
// if e.Where == nil {
// e.Where = make(map[string][]interface{})
// }
// e.Where[k] = v
// }
func (e *GormPublic) SetOr(k string, v []interface{}) {
if e.Or == nil {
e.Or = make(map[string][]interface{})
}
e.Or[k] = v
}
// func (e *GormPublic) SetOr(k string, v []interface{}) {
// if e.Or == nil {
// e.Or = make(map[string][]interface{})
// }
// e.Or[k] = v
// }
func (e *GormPublic) SetOrder(k string) {
if e.Order == nil {
e.Order = make([]string, 0)
}
e.Order = append(e.Order, k)
}
// func (e *GormPublic) SetOrder(k string) {
// if e.Order == nil {
// e.Order = make([]string, 0)
// }
// e.Order = append(e.Order, k)
// }
func (e *GormCondition) SetJoinOn(t, on string) Condition {
if e.Join == nil {
e.Join = make([]*GormJoin, 0)
}
join := &GormJoin{
Type: t,
JoinOn: on,
GormPublic: GormPublic{},
}
e.Join = append(e.Join, join)
return join
}
// func (e *GormCondition) SetJoinOn(t, on string) Condition {
// if e.Join == nil {
// e.Join = make([]*GormJoin, 0)
// }
// join := &GormJoin{
// Type: t,
// JoinOn: on,
// GormPublic: GormPublic{},
// }
// e.Join = append(e.Join, join)
// return join
// }
type resolveSearchTag struct {
Type string
Column string
Table string
On []string
Join string
}
// type resolveSearchTag struct {
// Type string
// Column string
// Table string
// On []string
// Join string
// }
// makeTag 解析search的tag标签
func makeTag(tag string) *resolveSearchTag {
r := &resolveSearchTag{}
tags := strings.Split(tag, ";")
var ts []string
for _, t := range tags {
ts = strings.Split(t, ":")
if len(ts) == 0 {
continue
}
switch ts[0] {
case "type":
if len(ts) > 1 {
r.Type = ts[1]
}
case "column":
if len(ts) > 1 {
r.Column = ts[1]
}
case "table":
if len(ts) > 1 {
r.Table = ts[1]
}
case "on":
if len(ts) > 1 {
r.On = ts[1:]
}
case "join":
if len(ts) > 1 {
r.Join = ts[1]
}
}
}
return r
}
// // makeTag 解析search的tag标签
// func makeTag(tag string) *resolveSearchTag {
// r := &resolveSearchTag{}
// tags := strings.Split(tag, ";")
// var ts []string
// for _, t := range tags {
// ts = strings.Split(t, ":")
// if len(ts) == 0 {
// continue
// }
// switch ts[0] {
// case "type":
// if len(ts) > 1 {
// r.Type = ts[1]
// }
// case "column":
// if len(ts) > 1 {
// r.Column = ts[1]
// }
// case "table":
// if len(ts) > 1 {
// r.Table = ts[1]
// }
// case "on":
// if len(ts) > 1 {
// r.On = ts[1:]
// }
// case "join":
// if len(ts) > 1 {
// r.Join = ts[1]
// }
// }
// }
// return r
// }
package base
import (
"context"
"database/sql"
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/xerrors/xerror"
"gorm.io/gorm"
)
const (
OrderIgnoreCount = "ignore_count"
)
type IBaseDao interface {
DB() *gorm.DB
Create(ctx context.Context, m any) error
CreateTx(ctx context.Context, tx *gorm.DB, model any) error
Save(ctx context.Context, model any) error
SaveTx(ctx context.Context, tx *gorm.DB, model any) error
UpdateWhere(ctx context.Context, model any, where any, updates map[string]any) error
UpdateWhereTx(ctx context.Context, tx *gorm.DB, model any, where any, updates map[string]any) error
UpdateWhereModel(ctx context.Context, where any, updates any) error
UpdateWhereModelTx(ctx context.Context, tx *gorm.DB, where any, updates any) error
UpdateById(ctx context.Context, model any) error
UpdateByIdTx(ctx context.Context, tx *gorm.DB, model any) error
DelModel(ctx context.Context, model any) error
DelWhereTx(ctx context.Context, tx *gorm.DB, model any) error
DelWhereMap(ctx context.Context, model any, where map[string]any) error
DelWhereMapTx(ctx context.Context, tx *gorm.DB, model any, where map[string]any) error
DelIds(ctx context.Context, model any, ids any) error
DelIdsTx(ctx context.Context, tx *gorm.DB, model any, ids any) error
Get(ctx context.Context, model any, conds ...interface{}) error
GetByWhere(ctx context.Context, where any, models any) error
GetByMap(ctx context.Context, where map[string]any, models any) error
PageQuery(pageSize int, cb func(pageSize, offset int, size *int) error) error
Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) error
}
func NewDao(db *gorm.DB) *BaseDao {
return &BaseDao{
db: db,
}
}
type BaseDao struct {
db *gorm.DB
}
func (x *BaseDao) DB() *gorm.DB {
return x.db
}
func (x *BaseDao) Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) error {
err := x.DB().Transaction(fc, opts...)
if err != nil {
return xerror.New(err.Error())
}
return nil
}
func (x *BaseDao) PageQuery(pageSize int, cb func(pageSize, offset int, size *int) error) error {
pageIndex := 1
size := 0
if pageSize == 0 {
pageSize = 1000
}
for {
offset := (pageIndex - 1) * pageSize
if err := cb(pageSize, offset, &size); err != nil {
return err
}
if size == 0 || size < pageSize {
break
}
pageIndex++
}
return nil
}
/*
* 创建 结构体 m
*/
func (s *BaseDao) Create(ctx context.Context, m any) error {
if err := s.DB().WithContext(ctx).Create(m).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
func (s *BaseDao) CreateTx(ctx context.Context, tx *gorm.DB, model any) error {
if err := tx.WithContext(ctx).Create(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 更新整个模型 结构体model 注意空值
*/
func (s *BaseDao) Save(ctx context.Context, model any) error {
if err := s.DB().WithContext(ctx).Save(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
func (s *BaseDao) SaveTx(ctx context.Context, tx *gorm.DB, model any) error {
if err := tx.WithContext(ctx).Save(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 条件跟新
*/
func (s *BaseDao) UpdateWhere(ctx context.Context, model any, where any, updates map[string]any) error {
if err := s.DB().WithContext(ctx).Model(model).Where(where).Updates(updates).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
func (s *BaseDao) UpdateWhereTx(ctx context.Context, tx *gorm.DB, model any, where any, updates map[string]any) error {
if err := tx.WithContext(ctx).Model(model).Where(where).Updates(updates).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 模型更新
* 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
*/
func (s *BaseDao) UpdateWhereModel(ctx context.Context, where any, updates any) error {
if err := s.DB().WithContext(ctx).Where(where).Updates(updates).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 模型更新
* 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
*/
func (s *BaseDao) UpdateWhereModelTx(ctx context.Context, tx *gorm.DB, where any, updates any) error {
if err := tx.WithContext(ctx).Where(where).Updates(updates).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 根据模型id更新
* 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
*/
func (s *BaseDao) UpdateById(ctx context.Context, model any) error {
if err := s.DB().WithContext(ctx).Updates(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 根据模型id更新
* 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
*/
func (s *BaseDao) UpdateByIdTx(ctx context.Context, tx *gorm.DB, model any) error {
if err := tx.WithContext(ctx).Updates(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
// DelModel model id 不能为空
func (s *BaseDao) DelModel(ctx context.Context, model any) error {
if err := s.DB().WithContext(ctx).Delete(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
func (s *BaseDao) DelWhereTx(ctx context.Context, tx *gorm.DB, model any) error {
if err := tx.WithContext(ctx).Delete(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 条件删除,模型 where 为map
*/
func (s *BaseDao) DelWhereMap(ctx context.Context, model any, where map[string]any) error {
if err := s.DB().WithContext(ctx).Where(where).Delete(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
func (s *BaseDao) DelWhereMapTx(ctx context.Context, tx *gorm.DB, model any, where map[string]any) error {
if err := tx.WithContext(ctx).Where(where).Delete(model).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* id 可以是xsf.ID 也可以是[]xsf.ID
*/
func (s *BaseDao) DelIds(ctx context.Context, model any, ids any) error {
if err := s.DB().WithContext(ctx).Delete(model, ids).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
func (s *BaseDao) DelIdsTx(ctx context.Context, tx *gorm.DB, model any, ids any) error {
if err := tx.WithContext(ctx).Delete(model, ids).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 根据id获取模型
*/
func (s *BaseDao) Get(ctx context.Context, model any, conds ...interface{}) error {
if err := s.DB().WithContext(ctx).First(model, conds...).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/**
* 条件查询
* where: where 查询条件model
* models: 代表查询返回的model数组
*/
func (s *BaseDao) GetByWhere(ctx context.Context, where any, models any) error {
if err := s.DB().WithContext(ctx).Where(where).Find(models).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/**
* 列表条件查询
* where: 条件查询
* models: 代表查询返回的model数组
*/
func (s *BaseDao) GetByMap(ctx context.Context, where map[string]any, models any) error {
if err := s.DB().WithContext(ctx).Where(where).Find(models).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/**
* 条数查询
* model: 查询条件
* count: 查询条数
*/
func (s *BaseDao) Count(ctx context.Context, model any, count *int64) error {
if err := s.DB().WithContext(ctx).Model(model).Where(model).Count(count).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/**
* 条数查询
* model: 查询条件
* count: 查询条数
*/
func (s *BaseDao) CountByMap(ctx context.Context, where map[string]any, model any, count *int64) error {
if err := s.DB().WithContext(ctx).Model(model).Where(where).Count(count).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/**
* 查询
* where 实现Query接口
*/
func (s *BaseDao) Query(ctx context.Context, where Query, models any) error {
if err := s.DB().WithContext(ctx).Scopes(s.MakeCondition(where)).Find(models).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
// Page 分页查询
func (s *BaseDao) Page(ctx context.Context, where Query, models any, limit, offset int) error {
if err := s.DB().WithContext(ctx).Scopes(s.MakeCondition(where)).Limit(limit).Offset(offset).Find(models).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 分页获取
*/
func (s *BaseDao) QPage(ctx context.Context, where any, data any, total *int64, limit, offset int) error {
if err := s.DB().WithContext(ctx).Where(where).Limit(limit).Offset(offset).
Find(data).Limit(-1).Offset(-1).Count(total).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 分页获取
*/
func (s *BaseDao) QueryPage(ctx context.Context, where Query, models any, total *int64, limit, offset int) error {
if err := s.DB().WithContext(ctx).Scopes(s.MakeCondition(where)).Limit(limit).Offset(offset).
Find(models).Limit(-1).Offset(-1).Count(total).Error; err != nil {
return xerror.New(err.Error())
}
return nil
}
/*
* 分页组装
*/
func (s *BaseDao) Paginate(pageSize, pageIndex int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
offset := (pageIndex - 1) * pageSize
if offset < 0 {
offset = 0
}
return db.Offset(offset).Limit(pageSize)
}
}
/**
* chunk 查询
*/
func (s *BaseDao) Chunk(ctx context.Context, db *gorm.DB, size int, callback func(records []map[string]interface{}) error) error {
var offset int
for {
var records []map[string]interface{}
// 检索 size 条记录
if err := db.WithContext(ctx).Limit(size).Offset(offset).Find(&records).Error; err != nil {
return xerror.New(err.Error())
}
// 如果没有更多记录,则退出循环
if len(records) == 0 {
break
}
// 调用回调函数处理记录
if err := callback(records); err != nil {
return err
}
// 更新偏移量
offset += size
}
return nil
}
/**
* 查询条件组装
*/
func (s *BaseDao) MakeCondition(q Query) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
condition := &GormCondition{
GormPublic: GormPublic{},
Join: make([]*GormJoin, 0),
}
driver := "mysql"
ResolveSearchQuery(driver, q, condition, q.TableName())
for _, join := range condition.Join {
if join == nil {
continue
}
db = db.Joins(join.JoinOn)
for k, v := range join.Where {
db = db.Where(k, v...)
}
for k, v := range join.Or {
db = db.Or(k, v...)
}
for _, o := range join.Order {
db = db.Order(o)
}
}
for k, v := range condition.Where {
db = db.Where(k, v...)
}
for k, v := range condition.Or {
db = db.Or(k, v...)
}
for _, o := range condition.Order {
db = db.Order(o)
}
return db
}
}
// const (
// OrderIgnoreCount = "ignore_count"
// )
// type IBaseDao interface {
// DB() *gorm.DB
// Create(ctx context.Context, m any) error
// CreateTx(ctx context.Context, tx *gorm.DB, model any) error
// Save(ctx context.Context, model any) error
// SaveTx(ctx context.Context, tx *gorm.DB, model any) error
// UpdateWhere(ctx context.Context, model any, where any, updates map[string]any) error
// UpdateWhereTx(ctx context.Context, tx *gorm.DB, model any, where any, updates map[string]any) error
// UpdateWhereModel(ctx context.Context, where any, updates any) error
// UpdateWhereModelTx(ctx context.Context, tx *gorm.DB, where any, updates any) error
// UpdateById(ctx context.Context, model any) error
// UpdateByIdTx(ctx context.Context, tx *gorm.DB, model any) error
// DelModel(ctx context.Context, model any) error
// DelWhereTx(ctx context.Context, tx *gorm.DB, model any) error
// DelWhereMap(ctx context.Context, model any, where map[string]any) error
// DelWhereMapTx(ctx context.Context, tx *gorm.DB, model any, where map[string]any) error
// DelIds(ctx context.Context, model any, ids any) error
// DelIdsTx(ctx context.Context, tx *gorm.DB, model any, ids any) error
// Get(ctx context.Context, model any, conds ...interface{}) error
// GetByWhere(ctx context.Context, where any, models any) error
// GetByMap(ctx context.Context, where map[string]any, models any) error
// PageQuery(pageSize int, cb func(pageSize, offset int, size *int) error) error
// Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) error
// }
// func NewDao(db *gorm.DB) *BaseDao {
// return &BaseDao{
// db: db,
// }
// }
// type BaseDao struct {
// db *gorm.DB
// }
// func (x *BaseDao) DB() *gorm.DB {
// return x.db
// }
// func (x *BaseDao) Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) error {
// err := x.DB().Transaction(fc, opts...)
// if err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (x *BaseDao) PageQuery(pageSize int, cb func(pageSize, offset int, size *int) error) error {
// pageIndex := 1
// size := 0
// if pageSize == 0 {
// pageSize = 1000
// }
// for {
// offset := (pageIndex - 1) * pageSize
// if err := cb(pageSize, offset, &size); err != nil {
// return err
// }
// if size == 0 || size < pageSize {
// break
// }
// pageIndex++
// }
// return nil
// }
// /*
// * 创建 结构体 m
// */
// func (s *BaseDao) Create(ctx context.Context, m any) error {
// if err := s.DB().WithContext(ctx).Create(m).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (s *BaseDao) CreateTx(ctx context.Context, tx *gorm.DB, model any) error {
// if err := tx.WithContext(ctx).Create(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 更新整个模型 结构体model 注意空值
// */
// func (s *BaseDao) Save(ctx context.Context, model any) error {
// if err := s.DB().WithContext(ctx).Save(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (s *BaseDao) SaveTx(ctx context.Context, tx *gorm.DB, model any) error {
// if err := tx.WithContext(ctx).Save(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 条件跟新
// */
// func (s *BaseDao) UpdateWhere(ctx context.Context, model any, where any, updates map[string]any) error {
// if err := s.DB().WithContext(ctx).Model(model).Where(where).Updates(updates).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (s *BaseDao) UpdateWhereTx(ctx context.Context, tx *gorm.DB, model any, where any, updates map[string]any) error {
// if err := tx.WithContext(ctx).Model(model).Where(where).Updates(updates).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 模型更新
// * 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
// */
// func (s *BaseDao) UpdateWhereModel(ctx context.Context, where any, updates any) error {
// if err := s.DB().WithContext(ctx).Where(where).Updates(updates).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 模型更新
// * 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
// */
// func (s *BaseDao) UpdateWhereModelTx(ctx context.Context, tx *gorm.DB, where any, updates any) error {
// if err := tx.WithContext(ctx).Where(where).Updates(updates).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 根据模型id更新
// * 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
// */
// func (s *BaseDao) UpdateById(ctx context.Context, model any) error {
// if err := s.DB().WithContext(ctx).Updates(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 根据模型id更新
// * 注意!!!零值不会更新,建议使用 UpdateWhere、UpdateWhereTx
// */
// func (s *BaseDao) UpdateByIdTx(ctx context.Context, tx *gorm.DB, model any) error {
// if err := tx.WithContext(ctx).Updates(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// // DelModel model id 不能为空
// func (s *BaseDao) DelModel(ctx context.Context, model any) error {
// if err := s.DB().WithContext(ctx).Delete(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (s *BaseDao) DelWhereTx(ctx context.Context, tx *gorm.DB, model any) error {
// if err := tx.WithContext(ctx).Delete(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 条件删除,模型 where 为map
// */
// func (s *BaseDao) DelWhereMap(ctx context.Context, model any, where map[string]any) error {
// if err := s.DB().WithContext(ctx).Where(where).Delete(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (s *BaseDao) DelWhereMapTx(ctx context.Context, tx *gorm.DB, model any, where map[string]any) error {
// if err := tx.WithContext(ctx).Where(where).Delete(model).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * id 可以是xsf.ID 也可以是[]xsf.ID
// */
// func (s *BaseDao) DelIds(ctx context.Context, model any, ids any) error {
// if err := s.DB().WithContext(ctx).Delete(model, ids).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// func (s *BaseDao) DelIdsTx(ctx context.Context, tx *gorm.DB, model any, ids any) error {
// if err := tx.WithContext(ctx).Delete(model, ids).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 根据id获取模型
// */
// func (s *BaseDao) Get(ctx context.Context, model any, conds ...interface{}) error {
// if err := s.DB().WithContext(ctx).First(model, conds...).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /**
// * 条件查询
// * where: where 查询条件model
// * models: 代表查询返回的model数组
// */
// func (s *BaseDao) GetByWhere(ctx context.Context, where any, models any) error {
// if err := s.DB().WithContext(ctx).Where(where).Find(models).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /**
// * 列表条件查询
// * where: 条件查询
// * models: 代表查询返回的model数组
// */
// func (s *BaseDao) GetByMap(ctx context.Context, where map[string]any, models any) error {
// if err := s.DB().WithContext(ctx).Where(where).Find(models).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /**
// * 条数查询
// * model: 查询条件
// * count: 查询条数
// */
// func (s *BaseDao) Count(ctx context.Context, model any, count *int64) error {
// if err := s.DB().WithContext(ctx).Model(model).Where(model).Count(count).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /**
// * 条数查询
// * model: 查询条件
// * count: 查询条数
// */
// func (s *BaseDao) CountByMap(ctx context.Context, where map[string]any, model any, count *int64) error {
// if err := s.DB().WithContext(ctx).Model(model).Where(where).Count(count).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /**
// * 查询
// * where 实现Query接口
// */
// func (s *BaseDao) Query(ctx context.Context, where Query, models any) error {
// if err := s.DB().WithContext(ctx).Scopes(s.MakeCondition(where)).Find(models).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// // Page 分页查询
// func (s *BaseDao) Page(ctx context.Context, where Query, models any, limit, offset int) error {
// if err := s.DB().WithContext(ctx).Scopes(s.MakeCondition(where)).Limit(limit).Offset(offset).Find(models).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 分页获取
// */
// func (s *BaseDao) QPage(ctx context.Context, where any, data any, total *int64, limit, offset int) error {
// if err := s.DB().WithContext(ctx).Where(where).Limit(limit).Offset(offset).
// Find(data).Limit(-1).Offset(-1).Count(total).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 分页获取
// */
// func (s *BaseDao) QueryPage(ctx context.Context, where Query, models any, total *int64, limit, offset int) error {
// if err := s.DB().WithContext(ctx).Scopes(s.MakeCondition(where)).Limit(limit).Offset(offset).
// Find(models).Limit(-1).Offset(-1).Count(total).Error; err != nil {
// return xerror.New(err.Error())
// }
// return nil
// }
// /*
// * 分页组装
// */
// func (s *BaseDao) Paginate(pageSize, pageIndex int) func(db *gorm.DB) *gorm.DB {
// return func(db *gorm.DB) *gorm.DB {
// offset := (pageIndex - 1) * pageSize
// if offset < 0 {
// offset = 0
// }
// return db.Offset(offset).Limit(pageSize)
// }
// }
// /**
// * chunk 查询
// */
// func (s *BaseDao) Chunk(ctx context.Context, db *gorm.DB, size int, callback func(records []map[string]interface{}) error) error {
// var offset int
// for {
// var records []map[string]interface{}
// // 检索 size 条记录
// if err := db.WithContext(ctx).Limit(size).Offset(offset).Find(&records).Error; err != nil {
// return xerror.New(err.Error())
// }
// // 如果没有更多记录,则退出循环
// if len(records) == 0 {
// break
// }
// // 调用回调函数处理记录
// if err := callback(records); err != nil {
// return err
// }
// // 更新偏移量
// offset += size
// }
// return nil
// }
// /**
// * 查询条件组装
// */
// func (s *BaseDao) MakeCondition(q Query) func(db *gorm.DB) *gorm.DB {
// return func(db *gorm.DB) *gorm.DB {
// condition := &GormCondition{
// GormPublic: GormPublic{},
// Join: make([]*GormJoin, 0),
// }
// driver := "mysql"
// ResolveSearchQuery(driver, q, condition, q.TableName())
// for _, join := range condition.Join {
// if join == nil {
// continue
// }
// db = db.Joins(join.JoinOn)
// for k, v := range join.Where {
// db = db.Where(k, v...)
// }
// for k, v := range join.Or {
// db = db.Or(k, v...)
// }
// for _, o := range join.Order {
// db = db.Order(o)
// }
// }
// for k, v := range condition.Where {
// db = db.Where(k, v...)
// }
// for k, v := range condition.Or {
// db = db.Or(k, v...)
// }
// for _, o := range condition.Order {
// db = db.Order(o)
// }
// return db
// }
// }
package base
import (
"fmt"
"reflect"
"regexp"
"strings"
"unicode"
// /*
// * 条件查询结构体,结果体非零值字段将查询
// * @Param type
// * eq 等于(默认不填都可以)
// * like 包含
// * gt / gte 大于 / 大于等于
// * lt / lte 小于 / 小于等于
// * left / ileft :like xxx%
// * right / iright : like %xxx
// * in
// * isnull
// * order 排序 e.g. order[key]=desc order[key]=asc
// * "-" 忽略该字段
// * @Param table
// * table 不填默认取 TableName值
// * @Param column
// * column 不填以结构体字段
// * eg:
// * type ExampleQuery struct{
// * Name string `json:"name" query:"type:like;column:name;table:exampale"`
// * Status int `json:"status" query:"type:gt"`
// * }
// * func (ExampleQuery) TableName() string {
// * return "ExampleQuery"
// * }
// */
// type Query interface {
// TableName() string
// }
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/logger"
)
// const (
// // FromQueryTag tag标记
// FromQueryTag = "query"
// // Mysql 数据库标识
// Mysql = "mysql"
// // Postgres 数据库标识
// Postgres = "pgsql"
// )
/*
* 条件查询结构体,结果体非零值字段将查询
* @Param type
* eq 等于(默认不填都可以)
* like 包含
* gt / gte 大于 / 大于等于
* lt / lte 小于 / 小于等于
* left / ileft :like xxx%
* right / iright : like %xxx
* in
* isnull
* order 排序 e.g. order[key]=desc order[key]=asc
* "-" 忽略该字段
* @Param table
* table 不填默认取 TableName值
* @Param column
* column 不填以结构体字段
* eg:
* type ExampleQuery struct{
* Name string `json:"name" query:"type:like;column:name;table:exampale"`
* Status int `json:"status" query:"type:gt"`
* }
* func (ExampleQuery) TableName() string {
* return "ExampleQuery"
* }
*/
type Query interface {
TableName() string
}
// // ResolveSearchQuery 解析
// /**
// * eq 等于(默认不填都可以)
// * like 包含
// * gt / gte 大于 / 大于等于
// * lt / lte 小于 / 小于等于
// * left / ileft :like xxx%
// * right / iright : like %xxx
// * in
// * isnull
// * order 排序 e.g. order[key]=desc order[key]=asc
// */
// func ResolveSearchQuery(driver string, q any, condition Condition, pTName string) {
// qType := reflect.TypeOf(q)
// qValue := reflect.ValueOf(q)
// var tag string
// var ok bool
// var t *resolveSearchTag
// var tname string
// if cur, ok := q.(Query); ok {
// if cur.TableName() == "" {
// tname = pTName
// } else {
// tname = cur.TableName()
// }
// } else {
// tname = pTName
// }
// if qType.Kind() == reflect.Ptr {
// qType = qType.Elem()
// }
// if qType.Kind() != reflect.Struct {
// // fmt.Printf("SeachQuery field undefined tag of type %s, expect type is struct\n", qType.Name())
// return
// }
const (
// FromQueryTag tag标记
FromQueryTag = "query"
// Mysql 数据库标识
Mysql = "mysql"
// Postgres 数据库标识
Postgres = "pgsql"
)
// for i := 0; i < qType.NumField(); i++ {
// tag, ok = "", false
// tag, ok = qType.Field(i).Tag.Lookup(FromQueryTag)
// if !ok {
// //递归调用
// ResolveSearchQuery(driver, qValue.Field(i).Interface(), condition, tname)
// continue
// }
// switch tag {
// case "-":
// continue
// }
// if qValue.Field(i).IsZero() {
// continue
// }
// t = makeTag(tag)
// if t.Column == "" {
// t.Column = snakeCase(qType.Field(i).Name, false)
// }
// if t.Table == "" {
// t.Table = tname
// }
// ResolveSearchQuery 解析
/**
* eq 等于(默认不填都可以)
* like 包含
* gt / gte 大于 / 大于等于
* lt / lte 小于 / 小于等于
* left / ileft :like xxx%
* right / iright : like %xxx
* in
* isnull
* order 排序 e.g. order[key]=desc order[key]=asc
*/
func ResolveSearchQuery(driver string, q any, condition Condition, pTName string) {
qType := reflect.TypeOf(q)
qValue := reflect.ValueOf(q)
var tag string
var ok bool
var t *resolveSearchTag
var tname string
if cur, ok := q.(Query); ok {
if cur.TableName() == "" {
tname = pTName
} else {
tname = cur.TableName()
}
} else {
tname = pTName
}
if qType.Kind() == reflect.Ptr {
qType = qType.Elem()
}
if qType.Kind() != reflect.Struct {
// fmt.Printf("SeachQuery field undefined tag of type %s, expect type is struct\n", qType.Name())
return
}
// //解析 Postgres `语法不支持,单独适配
// if driver == Postgres {
// pgSql(driver, t, condition, qValue, i, tname)
// } else {
// otherSql(driver, t, condition, qValue, i, tname)
// }
// }
// }
for i := 0; i < qType.NumField(); i++ {
tag, ok = "", false
tag, ok = qType.Field(i).Tag.Lookup(FromQueryTag)
if !ok {
//递归调用
ResolveSearchQuery(driver, qValue.Field(i).Interface(), condition, tname)
continue
}
switch tag {
case "-":
continue
}
if qValue.Field(i).IsZero() {
continue
}
t = makeTag(tag)
if t.Column == "" {
t.Column = snakeCase(qType.Field(i).Name, false)
}
if t.Table == "" {
t.Table = tname
}
// type QueryTag string
//解析 Postgres `语法不支持,单独适配
if driver == Postgres {
pgSql(driver, t, condition, qValue, i, tname)
} else {
otherSql(driver, t, condition, qValue, i, tname)
}
}
}
// const (
// EQ QueryTag = "eq"
// LIKE QueryTag = "like"
// ILIKE QueryTag = "ilike"
// LEFT QueryTag = "left"
// ILEFT QueryTag = "ileft"
// RIGHT QueryTag = "right"
// IRIGHT QueryTag = "iright"
// GT QueryTag = "gt"
// GTE QueryTag = "gte"
// LT QueryTag = "lt"
// LTE QueryTag = "lte"
// IN QueryTag = "in"
// ISNULL QueryTag = "isnull"
// ISNOTNULL QueryTag = "isnotnull"
// ORDER QueryTag = "order"
// JOIN QueryTag = "join"
// )
type QueryTag string
// func pgSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) {
// if t.Type == "" {
// condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// }
// qtag := QueryTag(t.Type)
// switch qtag {
// case EQ:
// condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case ILIKE:
// condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"})
// return
// case LIKE:
// condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"})
// return
// case GT:
// condition.SetWhere(fmt.Sprintf("%s.%s > ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case GTE:
// condition.SetWhere(fmt.Sprintf("%s.%s >= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case LT:
// condition.SetWhere(fmt.Sprintf("%s.%s < ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case LTE:
// condition.SetWhere(fmt.Sprintf("%s.%s <= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case ILEFT:
// condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"})
// return
// case LEFT:
// condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"})
// return
// case IRIGHT:
// condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()})
// return
// case RIGHT:
// condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()})
// return
// case IN:
// condition.SetWhere(fmt.Sprintf("%s.%s in (?)", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case ISNULL:
// if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
// condition.SetWhere(fmt.Sprintf("%s.%s is null", t.Table, t.Column), make([]interface{}, 0))
// }
// return
// case ISNOTNULL:
// if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
// condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]interface{}, 0))
// }
// return
// case ORDER:
// switch strings.ToLower(qValue.Field(i).String()) {
// case "desc", "asc":
// condition.SetOrder(fmt.Sprintf("%s.%s %s", t.Table, t.Column, qValue.Field(i).String()))
// }
// return
// case JOIN:
// //左关联
// join := condition.SetJoinOn(t.Type, fmt.Sprintf(
// "left join %s on %s.%s = %s.%s", t.Join, t.Join, t.On[0], t.Table, t.On[1],
// ))
// ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname)
// return
// default:
// condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// }
// }
const (
EQ QueryTag = "eq"
LIKE QueryTag = "like"
ILIKE QueryTag = "ilike"
LEFT QueryTag = "left"
ILEFT QueryTag = "ileft"
RIGHT QueryTag = "right"
IRIGHT QueryTag = "iright"
GT QueryTag = "gt"
GTE QueryTag = "gte"
LT QueryTag = "lt"
LTE QueryTag = "lte"
IN QueryTag = "in"
ISNULL QueryTag = "isnull"
ISNOTNULL QueryTag = "isnotnull"
ORDER QueryTag = "order"
JOIN QueryTag = "join"
)
// func otherSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) {
// if t.Type == "" {
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// }
// qtag := QueryTag(t.Type)
// switch qtag {
// case EQ:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case GT:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` > ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case GTE:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` >= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case LT:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` < ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case LTE:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` <= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case LEFT:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"})
// return
// case LIKE:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"})
// return
// case RIGHT:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()})
// return
// case IN:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` in (?)", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// return
// case ISNULL:
// if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` is null", t.Table, t.Column), make([]interface{}, 0))
// }
// return
// case ISNOTNULL:
// if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
// condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]interface{}, 0))
// }
// return
// case ORDER:
// val := strings.TrimSpace(qValue.Field(i).String())
// if detectSQLInjection(val) {
// logger.Error("detect SQL injection", logger.String("sql order segment", val))
// return
// }
// if val != "" {
// orderColumns := strings.Split(val, ",")
// var orders []string
// for _, column := range orderColumns {
// if strings.HasPrefix(column, "-") {
// column = column[1:] + " desc"
// } else {
// column += " asc"
// }
// column = fmt.Sprintf("%s.%s", t.Table, column)
// orders = append(orders, column)
// }
// orderSegmet := strings.Join(orders, ",")
// condition.SetOrder(orderSegmet)
// } else {
// switch strings.ToLower(qValue.Field(i).String()) {
// case "desc", "asc":
// condition.SetOrder(fmt.Sprintf("`%s`.`%s` %s", t.Table, t.Column, qValue.Field(i).String()))
// }
// }
// return
// case JOIN:
// //左关联
// join := condition.SetJoinOn(t.Type, fmt.Sprintf(
// "left join `%s` on `%s`.`%s` = `%s`.`%s`",
// t.Join,
// t.Join,
// t.On[0],
// t.Table,
// t.On[1],
// ))
// ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname)
// return
// default:
// condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
// }
// }
func pgSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) {
if t.Type == "" {
condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
}
qtag := QueryTag(t.Type)
switch qtag {
case EQ:
condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case ILIKE:
condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"})
return
case LIKE:
condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"})
return
case GT:
condition.SetWhere(fmt.Sprintf("%s.%s > ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case GTE:
condition.SetWhere(fmt.Sprintf("%s.%s >= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case LT:
condition.SetWhere(fmt.Sprintf("%s.%s < ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case LTE:
condition.SetWhere(fmt.Sprintf("%s.%s <= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case ILEFT:
condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"})
return
case LEFT:
condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"})
return
case IRIGHT:
condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()})
return
case RIGHT:
condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()})
return
case IN:
condition.SetWhere(fmt.Sprintf("%s.%s in (?)", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case ISNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("%s.%s is null", t.Table, t.Column), make([]interface{}, 0))
}
return
case ISNOTNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]interface{}, 0))
}
return
case ORDER:
switch strings.ToLower(qValue.Field(i).String()) {
case "desc", "asc":
condition.SetOrder(fmt.Sprintf("%s.%s %s", t.Table, t.Column, qValue.Field(i).String()))
}
return
case JOIN:
//左关联
join := condition.SetJoinOn(t.Type, fmt.Sprintf(
"left join %s on %s.%s = %s.%s", t.Join, t.Join, t.On[0], t.Table, t.On[1],
))
ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname)
return
default:
condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
}
}
// var (
// orderReg = regexp.MustCompile(`order\[([^\]]+)\]=([^=]+)`)
// detectSQLInjectionRe = regexp.MustCompile(`['";]+|UNION|SELECT|INSERT|UPDATE|DELETE|DROP|GRANT|EXEC|CREATE|ALTER|TRUNCATE|COUNT|\*|--|\/\*|;|\+|\/`)
// )
func otherSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) {
if t.Type == "" {
condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
}
qtag := QueryTag(t.Type)
switch qtag {
case EQ:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case GT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` > ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case GTE:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` >= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case LT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` < ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case LTE:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` <= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case LEFT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"})
return
case LIKE:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"})
return
case RIGHT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()})
return
case IN:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` in (?)", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
return
case ISNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("`%s`.`%s` is null", t.Table, t.Column), make([]interface{}, 0))
}
return
case ISNOTNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]interface{}, 0))
}
return
case ORDER:
val := strings.TrimSpace(qValue.Field(i).String())
if detectSQLInjection(val) {
logger.Error("detect SQL injection", logger.String("sql order segment", val))
return
}
if val != "" {
orderColumns := strings.Split(val, ",")
var orders []string
for _, column := range orderColumns {
if strings.HasPrefix(column, "-") {
column = column[1:] + " desc"
} else {
column += " asc"
}
column = fmt.Sprintf("%s.%s", t.Table, column)
orders = append(orders, column)
}
orderSegmet := strings.Join(orders, ",")
condition.SetOrder(orderSegmet)
} else {
switch strings.ToLower(qValue.Field(i).String()) {
case "desc", "asc":
condition.SetOrder(fmt.Sprintf("`%s`.`%s` %s", t.Table, t.Column, qValue.Field(i).String()))
}
}
return
case JOIN:
//左关联
join := condition.SetJoinOn(t.Type, fmt.Sprintf(
"left join `%s` on `%s`.`%s` = `%s`.`%s`",
t.Join,
t.Join,
t.On[0],
t.Table,
t.On[1],
))
ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname)
return
default:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()})
}
}
// func parseOrder(order string) (string, string, bool) {
// matches := orderReg.FindStringSubmatch(order)
// if len(matches) == 3 {
// column := matches[1]
// value := matches[2]
// return strings.TrimSpace(column), strings.TrimSpace(value), true
// } else {
// return "", "", false
// }
// }
var (
orderReg = regexp.MustCompile(`order\[([^\]]+)\]=([^=]+)`)
detectSQLInjectionRe = regexp.MustCompile(`['";]+|UNION|SELECT|INSERT|UPDATE|DELETE|DROP|GRANT|EXEC|CREATE|ALTER|TRUNCATE|COUNT|\*|--|\/\*|;|\+|\/`)
)
// func CameCaseToUnderscore(s string) string {
// var output []rune
// for i, r := range s {
// if i == 0 {
// output = append(output, unicode.ToLower(r))
// continue
// }
// if unicode.IsUpper(r) {
// output = append(output, '_')
// }
// output = append(output, unicode.ToLower(r))
// }
// return string(output)
// }
func parseOrder(order string) (string, string, bool) {
matches := orderReg.FindStringSubmatch(order)
if len(matches) == 3 {
column := matches[1]
value := matches[2]
return strings.TrimSpace(column), strings.TrimSpace(value), true
} else {
return "", "", false
}
}
// func castOrder(order string) string {
// order = strings.ToLower(order)
// switch order {
// case "desc":
// return "desc"
// case "asc":
// return "asc"
// default:
// return ""
// }
// }
func CameCaseToUnderscore(s string) string {
var output []rune
for i, r := range s {
if i == 0 {
output = append(output, unicode.ToLower(r))
continue
}
if unicode.IsUpper(r) {
output = append(output, '_')
}
output = append(output, unicode.ToLower(r))
}
return string(output)
}
// func detectSQLInjection(input string) bool {
// return detectSQLInjectionRe.MatchString(input)
// }
func castOrder(order string) string {
order = strings.ToLower(order)
switch order {
case "desc":
return "desc"
case "asc":
return "asc"
default:
return ""
}
}
func detectSQLInjection(input string) bool {
return detectSQLInjectionRe.MatchString(input)
}
/**
* 驼峰转蛇形 snake string
**/
func snakeCase(s string, allMode bool) string {
num := len(s)
data := make([]byte, 0, num*2)
for i := 0; i < num; i++ {
d := s[i]
// or通过ASCII码进行大小写的转化
// 65-90(A-Z),97-122(a-z)
//判断如果字母为大写的A-Z就在前面拼接一个_
if d >= 'A' && d <= 'Z' {
if i > 0 {
if allMode {
data = append(data, '_', d+32)
} else {
if s[i-1] >= 'A' && s[i-1] <= 'Z' {
data = append(data, d+32)
} else {
data = append(data, '_', d+32)
}
}
} else {
data = append(data, d+32)
}
} else {
data = append(data, d)
}
}
//ToLower把大写字母统一转小写
return string(data[:])
}
// /**
// * 驼峰转蛇形 snake string
// **/
// func snakeCase(s string, allMode bool) string {
// num := len(s)
// data := make([]byte, 0, num*2)
// for i := 0; i < num; i++ {
// d := s[i]
// // or通过ASCII码进行大小写的转化
// // 65-90(A-Z),97-122(a-z)
// //判断如果字母为大写的A-Z就在前面拼接一个_
// if d >= 'A' && d <= 'Z' {
// if i > 0 {
// if allMode {
// data = append(data, '_', d+32)
// } else {
// if s[i-1] >= 'A' && s[i-1] <= 'Z' {
// data = append(data, d+32)
// } else {
// data = append(data, '_', d+32)
// }
// }
// } else {
// data = append(data, d+32)
// }
// } else {
// data = append(data, d)
// }
// }
// //ToLower把大写字母统一转小写
// return string(data[:])
// }
......@@ -2,16 +2,17 @@ package xcommon
import (
"context"
vd "github.com/bytedance/go-tagexpr/v2/validator"
"net/http"
"os"
"testing"
"time"
vd "github.com/bytedance/go-tagexpr/v2/validator"
"github.com/gin-gonic/gin"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/response"
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/httpcli"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/map_utils"
maputils "gitlab.wanzhuangkj.com/tush/xpkg/utils/maputils"
)
type IValid interface {
......@@ -104,7 +105,7 @@ func (x *ControllerTester) After(t *testing.T) {
func (x *ControllerTester) CommonHttp(method, URL string, in any, reply *response.Result) error {
if method == http.MethodDelete || method == http.MethodGet {
in = map_utils.StructToMapWithJsonTag(in)
in = maputils.StructToMapWithJsonTag(in)
}
if err := x.client.NewRequest().
SetHeaders(x.Headers).
......
package biz
import (
"context"
"encoding/json"
"gitlab.wanzhuangkj.com/tush/xpkg/xcron/models"
......@@ -40,9 +39,6 @@ func (*CronJob) GetIDs(rs []*CronJob) []xsf.ID {
return sliceUtils.GetIDs(rs)
}
type CronJobOpts struct {
}
func (CronJob) NewFromModel(m *models.CronJob) *CronJob {
if m == nil {
return nil
......@@ -58,23 +54,3 @@ func (x *CronJob) ToModel() *models.CronJob {
}
return &x.CronJob
}
func (x CronJob) Valid(ctx context.Context, cronJob *CronJob, opts *CronJobOpts) error {
if cronJob == nil {
return nil
}
if opts == nil {
opts = &CronJobOpts{}
}
return nil
}
func (x CronJob) ValidSlice(ctx context.Context, cronJobBizSlice []*CronJob, opts *CronJobOpts) error {
if len(cronJobBizSlice) == 0 {
return nil
}
if opts == nil {
opts = &CronJobOpts{}
}
return nil
}
package biz
import (
"context"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/setUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/sliceUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
......@@ -28,9 +26,6 @@ func (x *CronJobLog) GetJobIDs(rs []*CronJobLog) []xsf.ID {
return set.Slice()
}
type CronJobLogOpts struct {
}
func (CronJobLog) NewFromModel(m *models.CronJobLog) *CronJobLog {
if m == nil {
return nil
......@@ -46,23 +41,3 @@ func (x *CronJobLog) ToModel() *models.CronJobLog {
}
return &x.CronJobLog
}
func (x CronJobLog) Valid(ctx context.Context, cronJobLog *CronJobLog, opts *CronJobLogOpts) error {
if cronJobLog == nil {
return nil
}
if opts == nil {
opts = &CronJobLogOpts{}
}
return nil
}
func (x CronJobLog) ValidSlice(ctx context.Context, cronJobLogBizSlice []*CronJobLog, opts *CronJobLogOpts) error {
if len(cronJobLogBizSlice) == 0 {
return nil
}
if opts == nil {
opts = &CronJobLogOpts{}
}
return nil
}
package biz
import (
"context"
"gitlab.wanzhuangkj.com/tush/xpkg/xcron/models"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/setUtils"
......@@ -28,9 +27,6 @@ func (x *CronJobRecord) GetJobIDs(rs []*CronJobRecord) []xsf.ID {
return set.Slice()
}
type CronJobRecordOpts struct {
}
func (CronJobRecord) NewFromModel(m *models.CronJobRecord) *CronJobRecord {
if m == nil {
return nil
......@@ -46,23 +42,3 @@ func (x *CronJobRecord) ToModel() *models.CronJobRecord {
}
return &x.CronJobRecord
}
func (x CronJobRecord) Valid(ctx context.Context, cronJobRecord *CronJobRecord, opts *CronJobRecordOpts) error {
if cronJobRecord == nil {
return nil
}
if opts == nil {
opts = &CronJobRecordOpts{}
}
return nil
}
func (x CronJobRecord) ValidSlice(ctx context.Context, cronJobRecordBizSlice []*CronJobRecord, opts *CronJobRecordOpts) error {
if len(cronJobRecordBizSlice) == 0 {
return nil
}
if opts == nil {
opts = &CronJobRecordOpts{}
}
return nil
}
......@@ -17,6 +17,7 @@ CREATE TABLE `cron_job_log` (
`job_id` bigint(20) unsigned NOT NULL COMMENT 'job ID eg[101]',
`info` text COLLATE utf8mb4_unicode_ci COMMENT '日志 eg[job occur error...]',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间 eg[2025-01-07 12:20:43]',
`updated_at` datetime DEFAULT NULL COMMENT '修改时间 eg[2025-01-07 12:20:43]',
PRIMARY KEY (`id`),
KEY `idx_jobid_time` (`job_id`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='定时任务日志';
......
package ecode
import "gitlab.wanzhuangkj.com/tush/xpkg/pkg/errcode"
import (
"errors"
)
var (
ErrCronJobNotFound = errcode.NewError(12001, "未查询到任务")
ErrCronJobNotFound = errors.New("未查询到任务")
)
......@@ -29,7 +29,7 @@ func newCronJobService() *cronJobService {
Service: xcommon.NewService(),
}
}
func (x *cronJobService) GetByJobCode(ctx context.Context, jobCode string, opts *biz.CronJobOpts) (*biz.CronJob, error) {
func (x *cronJobService) GetByJobCode(ctx context.Context, jobCode string) (*biz.CronJob, error) {
if jobCode == "" {
return nil, nil
}
......@@ -37,14 +37,14 @@ func (x *cronJobService) GetByJobCode(ctx context.Context, jobCode string, opts
if err != nil {
return nil, err
}
return x.ToBiz(ctx, cronJob, opts)
return x.ToBiz(ctx, cronJob)
}
func (x *cronJobService) GetNotRunning(ctx context.Context, id xsf.ID) (*models.CronJob, error) {
return dao.CronJobDao.GetNotRunning(ctx, id)
}
func (x *cronJobService) Create(ctx context.Context, req *types.CronJobCreateReq, opts *biz.CronJobOpts) (id xsf.ID, err error) {
func (x *cronJobService) Create(ctx context.Context, req *types.CronJobCreateReq) (id xsf.ID, err error) {
cronJob := &models.CronJob{}
_ = copier.Copy(cronJob, req)
if err = dao.CronJobDao.Create(ctx, cronJob); err != nil {
......@@ -53,25 +53,25 @@ func (x *cronJobService) Create(ctx context.Context, req *types.CronJobCreateReq
return cronJob.ID, nil
}
func (x *cronJobService) DeleteByID(ctx context.Context, id xsf.ID, opts *biz.CronJobOpts) error {
func (x *cronJobService) DeleteByID(ctx context.Context, id xsf.ID) error {
if id <= 0 {
return nil
}
cronJob, err := x.GetByID(ctx, id, opts)
cronJob, err := x.GetByID(ctx, id)
if err != nil {
return err
}
if cronJob == nil {
return xerror.NewC(ecode.ErrCronJobNotFound.Code(), fmt.Sprintf("未查询到%s[id:%d]", models.CronJobTool.TableName(), id))
return xerror.New(fmt.Sprintf("未查询到%s[id:%d]", models.CronJobTool.TableName(), id))
}
return dao.CronJobDao.DeleteByID(ctx, id)
}
func (x *cronJobService) DeleteByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobOpts) error {
func (x *cronJobService) DeleteByIDs(ctx context.Context, ids []xsf.ID) error {
if len(ids) == 0 {
return nil
}
cronJobs, err := x.GetSliceByIDs(ctx, ids, opts)
cronJobs, err := x.GetSliceByIDs(ctx, ids)
if err != nil {
return err
}
......@@ -82,43 +82,43 @@ func (x *cronJobService) DeleteByIDs(ctx context.Context, ids []xsf.ID, opts *bi
return dao.CronJobDao.DeleteByIDs(ctx, ids)
}
func (x *cronJobService) StartByID(ctx context.Context, id xsf.ID, opts *biz.CronJobOpts) error {
func (x *cronJobService) StartByID(ctx context.Context, id xsf.ID) error {
req := &types.CronJobUpdateByIDReq{
ID: id,
Enable: enums.CronJob_Enable_OPEN,
}
return x.UpdateByID(ctx, req, opts)
return x.UpdateByID(ctx, req)
}
func (x *cronJobService) StopByID(ctx context.Context, id xsf.ID, opts *biz.CronJobOpts) error {
func (x *cronJobService) StopByID(ctx context.Context, id xsf.ID) error {
req := &types.CronJobUpdateByIDReq{
ID: id,
Enable: enums.CronJob_Enable_CLOSE,
}
return x.UpdateByID(ctx, req, opts)
return x.UpdateByID(ctx, req)
}
func (x *cronJobService) UpdateByID(ctx context.Context, req *types.CronJobUpdateByIDReq, opts *biz.CronJobOpts) error {
func (x *cronJobService) UpdateByID(ctx context.Context, req *types.CronJobUpdateByIDReq) error {
if req.ID <= 0 {
return nil
}
cronJob, err := x.GetByID(ctx, req.ID, opts)
cronJob, err := x.GetByID(ctx, req.ID)
if err != nil {
return err
}
if cronJob == nil {
return xerror.NewC(ecode.ErrCronJobNotFound.Code(), fmt.Sprintf("未查询到%s[id:%d]", models.CronJobTool.TableName(), req.ID))
return xerror.New(fmt.Sprintf("未查询到%s[id:%d]", models.CronJobTool.TableName(), req.ID))
}
cronJobUpd := &models.CronJob{}
_ = copier.Copy(cronJobUpd, req)
return dao.CronJobDao.UpdateByID(ctx, cronJobUpd.ID, cronJobUpd)
}
func (x *cronJobService) UpdateByIDs(ctx context.Context, req *types.CronJobUpdateByIDsReq, opts *biz.CronJobOpts) error {
func (x *cronJobService) UpdateByIDs(ctx context.Context, req *types.CronJobUpdateByIDsReq) error {
if len(req.IDs) == 0 {
return nil
}
cronJobs, err := x.GetSliceByIDs(ctx, req.IDs, opts)
cronJobs, err := x.GetSliceByIDs(ctx, req.IDs)
if err != nil {
return err
}
......@@ -131,7 +131,7 @@ func (x *cronJobService) UpdateByIDs(ctx context.Context, req *types.CronJobUpda
return dao.CronJobDao.UpdateByIDs(ctx, req.IDs, cronJobUpd)
}
func (x *cronJobService) GetByID(ctx context.Context, id xsf.ID, opts *biz.CronJobOpts) (cronJobBiz *biz.CronJob, err error) {
func (x *cronJobService) GetByID(ctx context.Context, id xsf.ID) (cronJobBiz *biz.CronJob, err error) {
if id <= 0 {
return nil, nil
}
......@@ -142,10 +142,10 @@ func (x *cronJobService) GetByID(ctx context.Context, id xsf.ID, opts *biz.CronJ
if cronJob == nil {
return nil, nil
}
return x.ToBiz(ctx, cronJob, opts)
return x.ToBiz(ctx, cronJob)
}
func (x *cronJobService) GetSliceByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobOpts) ([]*biz.CronJob, error) {
func (x *cronJobService) GetSliceByIDs(ctx context.Context, ids []xsf.ID) ([]*biz.CronJob, error) {
if len(ids) == 0 {
return nil, nil
}
......@@ -156,14 +156,14 @@ func (x *cronJobService) GetSliceByIDs(ctx context.Context, ids []xsf.ID, opts *
if len(cronJobs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobs, opts)
return x.ToSliceBiz(ctx, cronJobs)
}
func (x *cronJobService) GetMapByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobOpts) (map[xsf.ID]*biz.CronJob, error) {
func (x *cronJobService) GetMapByIDs(ctx context.Context, ids []xsf.ID) (map[xsf.ID]*biz.CronJob, error) {
if len(ids) == 0 {
return nil, nil
}
cronJobBizSlice, err := x.GetSliceByIDs(ctx, ids, opts)
cronJobBizSlice, err := x.GetSliceByIDs(ctx, ids)
if err != nil {
return nil, err
}
......@@ -174,7 +174,7 @@ func (x *cronJobService) GetMapByIDs(ctx context.Context, ids []xsf.ID, opts *bi
return cronJobBizIDMap, nil
}
func (x *cronJobService) Page(ctx context.Context, req *types.CronJobPageReq, opts *biz.CronJobOpts) ([]*biz.CronJob, int64, error) {
func (x *cronJobService) Page(ctx context.Context, req *types.CronJobPageReq) ([]*biz.CronJob, int64, error) {
cronJobs, total, err := dao.CronJobDao.Page(ctx, req)
if err != nil {
return nil, 0, err
......@@ -182,13 +182,13 @@ func (x *cronJobService) Page(ctx context.Context, req *types.CronJobPageReq, op
if len(cronJobs) == 0 {
return nil, total, nil
}
cronJobBizSlice, err := x.ToSliceBiz(ctx, cronJobs, opts)
cronJobBizSlice, err := x.ToSliceBiz(ctx, cronJobs)
if err != nil {
return nil, 0, err
}
return cronJobBizSlice, total, nil
}
func (x *cronJobService) GetSliceByState(ctx context.Context, state enums.CronJob_State_Enum, opts *biz.CronJobOpts) ([]*biz.CronJob, error) {
func (x *cronJobService) GetSliceByState(ctx context.Context, state enums.CronJob_State_Enum) ([]*biz.CronJob, error) {
cronJobs, err := dao.CronJobDao.GetSliceByState(ctx, models.CronJobTool.GetOrder(), state)
if err != nil {
return nil, err
......@@ -196,10 +196,10 @@ func (x *cronJobService) GetSliceByState(ctx context.Context, state enums.CronJo
if len(cronJobs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobs, opts)
return x.ToSliceBiz(ctx, cronJobs)
}
func (x *cronJobService) GetSliceByStates(ctx context.Context, states []enums.CronJob_State_Enum, opts *biz.CronJobOpts) ([]*biz.CronJob, error) {
func (x *cronJobService) GetSliceByStates(ctx context.Context, states []enums.CronJob_State_Enum) ([]*biz.CronJob, error) {
if len(states) == 0 {
return nil, nil
}
......@@ -214,14 +214,14 @@ func (x *cronJobService) GetSliceByStates(ctx context.Context, states []enums.Cr
for _, v := range cronJobMapSlice {
cronJobs = append(cronJobs, v...)
}
return x.ToSliceBiz(ctx, cronJobs, opts)
return x.ToSliceBiz(ctx, cronJobs)
}
func (x *cronJobService) GetMapSliceByStates(ctx context.Context, states []enums.CronJob_State_Enum, opts *biz.CronJobOpts) (map[enums.CronJob_State_Enum][]*biz.CronJob, int, error) {
func (x *cronJobService) GetMapSliceByStates(ctx context.Context, states []enums.CronJob_State_Enum) (map[enums.CronJob_State_Enum][]*biz.CronJob, int, error) {
if len(states) == 0 {
return nil, 0, nil
}
cronJobBizSlice, err := x.GetSliceByStates(ctx, states, opts)
cronJobBizSlice, err := x.GetSliceByStates(ctx, states)
if err != nil {
return nil, 0, err
}
......@@ -235,7 +235,7 @@ func (x *cronJobService) GetMapSliceByStates(ctx context.Context, states []enums
return ret, len(cronJobBizSlice), nil
}
func (x *cronJobService) GetSliceByEnable(ctx context.Context, enable enums.CronJob_Enable_Enum, opts *biz.CronJobOpts) ([]*biz.CronJob, error) {
func (x *cronJobService) GetSliceByEnable(ctx context.Context, enable enums.CronJob_Enable_Enum) ([]*biz.CronJob, error) {
cronJobs, err := dao.CronJobDao.GetSliceByEnable(ctx, models.CronJobTool.GetOrder(), enable)
if err != nil {
return nil, err
......@@ -243,56 +243,26 @@ func (x *cronJobService) GetSliceByEnable(ctx context.Context, enable enums.Cron
if len(cronJobs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobs, opts)
return x.ToSliceBiz(ctx, cronJobs)
}
func (x *cronJobService) ToBiz(ctx context.Context, cronJob *models.CronJob, opts *biz.CronJobOpts) (cronJobBiz *biz.CronJob, err error) {
func (x *cronJobService) ToBiz(ctx context.Context, cronJob *models.CronJob) (cronJobBiz *biz.CronJob, err error) {
if cronJob == nil {
return nil, nil
}
cronJobBiz = biz.CronJobTool.NewFromModel(cronJob)
if err = x.Fill(ctx, cronJobBiz, opts); err != nil {
return nil, err
}
if err = biz.CronJobTool.Valid(ctx, cronJobBiz, opts); err != nil {
return nil, err
}
return cronJobBiz, nil
}
func (x *cronJobService) ToSliceBiz(ctx context.Context, cronJobs []*models.CronJob, opts *biz.CronJobOpts) (cronJobBizSlice []*biz.CronJob, err error) {
func (x *cronJobService) ToSliceBiz(ctx context.Context, cronJobs []*models.CronJob) (cronJobBizSlice []*biz.CronJob, err error) {
if len(cronJobs) == 0 {
return nil, nil
}
cronJobBizSlice = biz.CronJobTool.NewSliceFromModelsBiz(cronJobs)
if err = x.SliceFill(ctx, cronJobBizSlice, opts); err != nil {
return nil, err
}
if err = biz.CronJobTool.ValidSlice(ctx, cronJobBizSlice, opts); err != nil {
return nil, err
}
return cronJobBizSlice, nil
}
func (x *cronJobService) Fill(ctx context.Context, cronJobBiz *biz.CronJob, opts *biz.CronJobOpts) error {
if cronJobBiz == nil {
return nil
}
if opts != nil {
}
return nil
}
func (x *cronJobService) SliceFill(ctx context.Context, cronJobBizSlice []*biz.CronJob, opts *biz.CronJobOpts) error {
if len(cronJobBizSlice) == 0 {
return nil
}
if opts != nil {
}
return nil
}
func (x *cronJobService) GetAll(ctx context.Context, opts *biz.CronJobOpts) ([]*biz.CronJob, error) {
func (x *cronJobService) GetAll(ctx context.Context) ([]*biz.CronJob, error) {
cronJobs, err := dao.CronJobDao.GetAll(ctx)
if err != nil {
return nil, err
......@@ -300,5 +270,5 @@ func (x *cronJobService) GetAll(ctx context.Context, opts *biz.CronJobOpts) ([]*
if len(cronJobs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobs, opts)
return x.ToSliceBiz(ctx, cronJobs)
}
......@@ -23,7 +23,7 @@ func newCronJobLogService() *cronJobLogService {
}
}
func (x *cronJobLogService) GetByID(ctx context.Context, id xsf.ID, opts *biz.CronJobLogOpts) (cronJobLogBiz *biz.CronJobLog, err error) {
func (x *cronJobLogService) GetByID(ctx context.Context, id xsf.ID) (cronJobLogBiz *biz.CronJobLog, err error) {
if id <= 0 {
return nil, nil
}
......@@ -34,10 +34,10 @@ func (x *cronJobLogService) GetByID(ctx context.Context, id xsf.ID, opts *biz.Cr
if cronJobLog == nil {
return nil, nil
}
return x.ToBiz(ctx, cronJobLog, opts)
return x.ToBiz(ctx, cronJobLog)
}
func (x *cronJobLogService) GetSliceByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobLogOpts) ([]*biz.CronJobLog, error) {
func (x *cronJobLogService) GetSliceByIDs(ctx context.Context, ids []xsf.ID) ([]*biz.CronJobLog, error) {
if len(ids) == 0 {
return nil, nil
}
......@@ -48,14 +48,14 @@ func (x *cronJobLogService) GetSliceByIDs(ctx context.Context, ids []xsf.ID, opt
if len(cronJobLogs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobLogs, opts)
return x.ToSliceBiz(ctx, cronJobLogs)
}
func (x *cronJobLogService) GetMapByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobLogOpts) (map[xsf.ID]*biz.CronJobLog, error) {
func (x *cronJobLogService) GetMapByIDs(ctx context.Context, ids []xsf.ID) (map[xsf.ID]*biz.CronJobLog, error) {
if len(ids) == 0 {
return nil, nil
}
cronJobLogBizSlice, err := x.GetSliceByIDs(ctx, ids, opts)
cronJobLogBizSlice, err := x.GetSliceByIDs(ctx, ids)
if err != nil {
return nil, err
}
......@@ -66,7 +66,7 @@ func (x *cronJobLogService) GetMapByIDs(ctx context.Context, ids []xsf.ID, opts
return cronJobLogBizIDMap, nil
}
func (x *cronJobLogService) Page(ctx context.Context, req *types.CronJobLogPageReq, opts *biz.CronJobLogOpts) ([]*biz.CronJobLog, int64, error) {
func (x *cronJobLogService) Page(ctx context.Context, req *types.CronJobLogPageReq) ([]*biz.CronJobLog, int64, error) {
cronJobLogs, total, err := dao.CronJobLogDao.Page(ctx, req)
if err != nil {
return nil, 0, err
......@@ -74,13 +74,13 @@ func (x *cronJobLogService) Page(ctx context.Context, req *types.CronJobLogPageR
if len(cronJobLogs) == 0 {
return nil, total, nil
}
cronJobLogBizSlice, err := x.ToSliceBiz(ctx, cronJobLogs, opts)
cronJobLogBizSlice, err := x.ToSliceBiz(ctx, cronJobLogs)
if err != nil {
return nil, 0, err
}
return cronJobLogBizSlice, total, nil
}
func (x *cronJobLogService) GetSliceByJobID(ctx context.Context, jobID xsf.ID, opts *biz.CronJobLogOpts) ([]*biz.CronJobLog, error) {
func (x *cronJobLogService) GetSliceByJobID(ctx context.Context, jobID xsf.ID) ([]*biz.CronJobLog, error) {
if jobID == 0 {
return nil, nil
}
......@@ -91,10 +91,10 @@ func (x *cronJobLogService) GetSliceByJobID(ctx context.Context, jobID xsf.ID, o
if len(cronJobLogs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobLogs, opts)
return x.ToSliceBiz(ctx, cronJobLogs)
}
func (x *cronJobLogService) GetSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID, opts *biz.CronJobLogOpts) ([]*biz.CronJobLog, error) {
func (x *cronJobLogService) GetSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID) ([]*biz.CronJobLog, error) {
if len(jobIDs) == 0 {
return nil, nil
}
......@@ -105,14 +105,14 @@ func (x *cronJobLogService) GetSliceByJobIDs(ctx context.Context, jobIDs []xsf.I
if len(cronJobLogs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobLogs, opts)
return x.ToSliceBiz(ctx, cronJobLogs)
}
func (x *cronJobLogService) GetMapSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID, opts *biz.CronJobLogOpts) (map[xsf.ID][]*biz.CronJobLog, int, error) {
func (x *cronJobLogService) GetMapSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID) (map[xsf.ID][]*biz.CronJobLog, int, error) {
if len(jobIDs) == 0 {
return nil, 0, nil
}
cronJobLogBizSlice, err := x.GetSliceByJobIDs(ctx, jobIDs, opts)
cronJobLogBizSlice, err := x.GetSliceByJobIDs(ctx, jobIDs)
if err != nil {
return nil, 0, err
}
......@@ -126,53 +126,23 @@ func (x *cronJobLogService) GetMapSliceByJobIDs(ctx context.Context, jobIDs []xs
return ret, len(cronJobLogBizSlice), nil
}
func (x *cronJobLogService) ToBiz(ctx context.Context, cronJobLog *models.CronJobLog, opts *biz.CronJobLogOpts) (cronJobLogBiz *biz.CronJobLog, err error) {
func (x *cronJobLogService) ToBiz(ctx context.Context, cronJobLog *models.CronJobLog) (cronJobLogBiz *biz.CronJobLog, err error) {
if cronJobLog == nil {
return nil, nil
}
cronJobLogBiz = biz.CronJobLogTool.NewFromModel(cronJobLog)
if err = x.Fill(ctx, cronJobLogBiz, opts); err != nil {
return nil, err
}
if err = biz.CronJobLogTool.Valid(ctx, cronJobLogBiz, opts); err != nil {
return nil, err
}
return cronJobLogBiz, nil
}
func (x *cronJobLogService) ToSliceBiz(ctx context.Context, cronJobLogs []*models.CronJobLog, opts *biz.CronJobLogOpts) (cronJobLogBizSlice []*biz.CronJobLog, err error) {
func (x *cronJobLogService) ToSliceBiz(ctx context.Context, cronJobLogs []*models.CronJobLog) (cronJobLogBizSlice []*biz.CronJobLog, err error) {
if len(cronJobLogs) == 0 {
return nil, nil
}
cronJobLogBizSlice = biz.CronJobLogTool.NewSliceFromModelsBiz(cronJobLogs)
if err = x.SliceFill(ctx, cronJobLogBizSlice, opts); err != nil {
return nil, err
}
if err = biz.CronJobLogTool.ValidSlice(ctx, cronJobLogBizSlice, opts); err != nil {
return nil, err
}
return cronJobLogBizSlice, nil
}
func (x *cronJobLogService) Fill(ctx context.Context, cronJobLogBiz *biz.CronJobLog, opts *biz.CronJobLogOpts) error {
if cronJobLogBiz == nil {
return nil
}
if opts != nil {
}
return nil
}
func (x *cronJobLogService) SliceFill(ctx context.Context, cronJobLogBizSlice []*biz.CronJobLog, opts *biz.CronJobLogOpts) error {
if len(cronJobLogBizSlice) == 0 {
return nil
}
if opts != nil {
}
return nil
}
func (x *cronJobLogService) GetAll(ctx context.Context, opts *biz.CronJobLogOpts) ([]*biz.CronJobLog, error) {
func (x *cronJobLogService) GetAll(ctx context.Context) ([]*biz.CronJobLog, error) {
cronJobLogs, err := dao.CronJobLogDao.GetAll(ctx)
if err != nil {
return nil, err
......@@ -180,5 +150,5 @@ func (x *cronJobLogService) GetAll(ctx context.Context, opts *biz.CronJobLogOpts
if len(cronJobLogs) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobLogs, opts)
return x.ToSliceBiz(ctx, cronJobLogs)
}
......@@ -23,7 +23,7 @@ func newCronJobRecordService() *cronJobRecordService {
}
}
func (x *cronJobRecordService) GetByID(ctx context.Context, id xsf.ID, opts *biz.CronJobRecordOpts) (cronJobRecordBiz *biz.CronJobRecord, err error) {
func (x *cronJobRecordService) GetByID(ctx context.Context, id xsf.ID) (cronJobRecordBiz *biz.CronJobRecord, err error) {
if id <= 0 {
return nil, nil
}
......@@ -31,10 +31,10 @@ func (x *cronJobRecordService) GetByID(ctx context.Context, id xsf.ID, opts *biz
if err != nil {
return nil, err
}
return x.ToBiz(ctx, cronJobRecord, opts)
return x.ToBiz(ctx, cronJobRecord)
}
func (x *cronJobRecordService) GetSliceByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobRecordOpts) ([]*biz.CronJobRecord, error) {
func (x *cronJobRecordService) GetSliceByIDs(ctx context.Context, ids []xsf.ID) ([]*biz.CronJobRecord, error) {
if len(ids) == 0 {
return nil, nil
}
......@@ -45,14 +45,14 @@ func (x *cronJobRecordService) GetSliceByIDs(ctx context.Context, ids []xsf.ID,
if len(cronJobRecords) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobRecords, opts)
return x.ToSliceBiz(ctx, cronJobRecords)
}
func (x *cronJobRecordService) GetMapByIDs(ctx context.Context, ids []xsf.ID, opts *biz.CronJobRecordOpts) (map[xsf.ID]*biz.CronJobRecord, error) {
func (x *cronJobRecordService) GetMapByIDs(ctx context.Context, ids []xsf.ID) (map[xsf.ID]*biz.CronJobRecord, error) {
if len(ids) == 0 {
return nil, nil
}
cronJobRecordBizSlice, err := x.GetSliceByIDs(ctx, ids, opts)
cronJobRecordBizSlice, err := x.GetSliceByIDs(ctx, ids)
if err != nil {
return nil, err
}
......@@ -63,7 +63,7 @@ func (x *cronJobRecordService) GetMapByIDs(ctx context.Context, ids []xsf.ID, op
return cronJobRecordBizIDMap, nil
}
func (x *cronJobRecordService) Page(ctx context.Context, req *types.CronJobRecordPageReq, opts *biz.CronJobRecordOpts) ([]*biz.CronJobRecord, int64, error) {
func (x *cronJobRecordService) Page(ctx context.Context, req *types.CronJobRecordPageReq) ([]*biz.CronJobRecord, int64, error) {
cronJobRecords, total, err := dao.CronJobRecordDao.Page(ctx, req)
if err != nil {
return nil, 0, err
......@@ -71,13 +71,13 @@ func (x *cronJobRecordService) Page(ctx context.Context, req *types.CronJobRecor
if len(cronJobRecords) == 0 {
return nil, total, nil
}
cronJobRecordBizSlice, err := x.ToSliceBiz(ctx, cronJobRecords, opts)
cronJobRecordBizSlice, err := x.ToSliceBiz(ctx, cronJobRecords)
if err != nil {
return nil, 0, err
}
return cronJobRecordBizSlice, total, nil
}
func (x *cronJobRecordService) GetSliceByJobID(ctx context.Context, jobID xsf.ID, opts *biz.CronJobRecordOpts) ([]*biz.CronJobRecord, error) {
func (x *cronJobRecordService) GetSliceByJobID(ctx context.Context, jobID xsf.ID) ([]*biz.CronJobRecord, error) {
if jobID == 0 {
return nil, nil
}
......@@ -88,10 +88,10 @@ func (x *cronJobRecordService) GetSliceByJobID(ctx context.Context, jobID xsf.ID
if len(cronJobRecords) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobRecords, opts)
return x.ToSliceBiz(ctx, cronJobRecords)
}
func (x *cronJobRecordService) GetSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID, opts *biz.CronJobRecordOpts) ([]*biz.CronJobRecord, error) {
func (x *cronJobRecordService) GetSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID) ([]*biz.CronJobRecord, error) {
if len(jobIDs) == 0 {
return nil, nil
}
......@@ -102,14 +102,14 @@ func (x *cronJobRecordService) GetSliceByJobIDs(ctx context.Context, jobIDs []xs
if len(cronJobRecords) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobRecords, opts)
return x.ToSliceBiz(ctx, cronJobRecords)
}
func (x *cronJobRecordService) GetMapSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID, opts *biz.CronJobRecordOpts) (map[xsf.ID][]*biz.CronJobRecord, int, error) {
func (x *cronJobRecordService) GetMapSliceByJobIDs(ctx context.Context, jobIDs []xsf.ID) (map[xsf.ID][]*biz.CronJobRecord, int, error) {
if len(jobIDs) == 0 {
return nil, 0, nil
}
cronJobRecordBizSlice, err := x.GetSliceByJobIDs(ctx, jobIDs, opts)
cronJobRecordBizSlice, err := x.GetSliceByJobIDs(ctx, jobIDs)
if err != nil {
return nil, 0, err
}
......@@ -123,53 +123,23 @@ func (x *cronJobRecordService) GetMapSliceByJobIDs(ctx context.Context, jobIDs [
return ret, len(cronJobRecordBizSlice), nil
}
func (x *cronJobRecordService) ToBiz(ctx context.Context, cronJobRecord *models.CronJobRecord, opts *biz.CronJobRecordOpts) (cronJobRecordBiz *biz.CronJobRecord, err error) {
func (x *cronJobRecordService) ToBiz(ctx context.Context, cronJobRecord *models.CronJobRecord) (cronJobRecordBiz *biz.CronJobRecord, err error) {
if cronJobRecord == nil {
return nil, nil
}
cronJobRecordBiz = biz.CronJobRecordTool.NewFromModel(cronJobRecord)
if err = x.Fill(ctx, cronJobRecordBiz, opts); err != nil {
return nil, err
}
if err = biz.CronJobRecordTool.Valid(ctx, cronJobRecordBiz, opts); err != nil {
return nil, err
}
return cronJobRecordBiz, nil
}
func (x *cronJobRecordService) ToSliceBiz(ctx context.Context, cronJobRecords []*models.CronJobRecord, opts *biz.CronJobRecordOpts) (cronJobRecordBizSlice []*biz.CronJobRecord, err error) {
func (x *cronJobRecordService) ToSliceBiz(ctx context.Context, cronJobRecords []*models.CronJobRecord) (cronJobRecordBizSlice []*biz.CronJobRecord, err error) {
if len(cronJobRecords) == 0 {
return nil, nil
}
cronJobRecordBizSlice = biz.CronJobRecordTool.NewSliceFromModelsBiz(cronJobRecords)
if err = x.SliceFill(ctx, cronJobRecordBizSlice, opts); err != nil {
return nil, err
}
if err = biz.CronJobRecordTool.ValidSlice(ctx, cronJobRecordBizSlice, opts); err != nil {
return nil, err
}
return cronJobRecordBizSlice, nil
}
func (x *cronJobRecordService) Fill(ctx context.Context, cronJobRecordBiz *biz.CronJobRecord, opts *biz.CronJobRecordOpts) error {
if cronJobRecordBiz == nil {
return nil
}
if opts != nil {
}
return nil
}
func (x *cronJobRecordService) SliceFill(ctx context.Context, cronJobRecordBizSlice []*biz.CronJobRecord, opts *biz.CronJobRecordOpts) error {
if len(cronJobRecordBizSlice) == 0 {
return nil
}
if opts != nil {
}
return nil
}
func (x *cronJobRecordService) GetAll(ctx context.Context, opts *biz.CronJobRecordOpts) ([]*biz.CronJobRecord, error) {
func (x *cronJobRecordService) GetAll(ctx context.Context) ([]*biz.CronJobRecord, error) {
cronJobRecords, err := dao.CronJobRecordDao.GetAll(ctx)
if err != nil {
return nil, err
......@@ -177,5 +147,5 @@ func (x *cronJobRecordService) GetAll(ctx context.Context, opts *biz.CronJobReco
if len(cronJobRecords) == 0 {
return nil, nil
}
return x.ToSliceBiz(ctx, cronJobRecords, opts)
return x.ToSliceBiz(ctx, cronJobRecords)
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论