refactor: base.repo与base.app精简优化

This commit is contained in:
meilin.huang
2024-04-29 12:29:56 +08:00
parent f2c7ef78c0
commit a5cd7caf19
14 changed files with 108 additions and 105 deletions

View File

@@ -11,7 +11,6 @@ import (
"mayfly-go/pkg/base" "mayfly-go/pkg/base"
"mayfly-go/pkg/contextx" "mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx" "mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/logx" "mayfly-go/pkg/logx"
"mayfly-go/pkg/model" "mayfly-go/pkg/model"
"mayfly-go/pkg/scheduler" "mayfly-go/pkg/scheduler"
@@ -410,13 +409,8 @@ func (app *dataSyncAppImpl) InitCronJob() {
} }
}() }()
// 修改执行状态为待执行 // 修改执行状态为待执行
updateMap := map[string]interface{}{ _ = app.UpdateByCond(context.TODO(), &entity.DataSyncTask{RunningState: entity.DataSyncTaskRunStateRunning}, &entity.DataSyncTask{RunningState: entity.DataSyncTaskRunStateReady})
"running_state": entity.DataSyncTaskRunStateReady,
}
taskParam := new(entity.DataSyncTask)
taskParam.RunningState = 1
_ = gormx.Updates(taskParam, taskParam, updateMap)
// 把所有正常任务添加到定时任务中 // 把所有正常任务添加到定时任务中
pageParam := &model.PageParam{ pageParam := &model.PageParam{

View File

@@ -11,7 +11,6 @@ import (
"mayfly-go/pkg/base" "mayfly-go/pkg/base"
"mayfly-go/pkg/cache" "mayfly-go/pkg/cache"
"mayfly-go/pkg/errorx" "mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/logx" "mayfly-go/pkg/logx"
"mayfly-go/pkg/model" "mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx" "mayfly-go/pkg/utils/collx"
@@ -74,13 +73,7 @@ func (app *dbTransferAppImpl) Delete(ctx context.Context, id uint64) error {
} }
func (app *dbTransferAppImpl) InitJob() { func (app *dbTransferAppImpl) InitJob() {
// 修改执行状态为待执行 app.UpdateByCond(context.TODO(), &entity.DbTransferTask{RunningState: entity.DbTransferTaskRunStateStop}, &entity.DbTransferTask{RunningState: entity.DbTransferTaskRunStateRunning})
updateMap := map[string]interface{}{
"running_state": entity.DbTransferTaskRunStateStop,
}
taskParam := new(entity.DbTransferTask)
taskParam.RunningState = entity.DbTransferTaskRunStateRunning
_ = gormx.Updates(taskParam, taskParam, updateMap)
} }
func (app *dbTransferAppImpl) CreateLog(ctx context.Context, taskId uint64) (uint64, error) { func (app *dbTransferAppImpl) CreateLog(ctx context.Context, taskId uint64) (uint64, error) {

View File

@@ -78,7 +78,7 @@ func (d *dbBackupRepoImpl) AddJob(ctx context.Context, jobs any) error {
return addJob[*entity.DbBackup](ctx, d.dbJobBaseImpl, jobs) return addJob[*entity.DbBackup](ctx, d.dbJobBaseImpl, jobs)
} }
func (d *dbBackupRepoImpl) UpdateEnabled(_ context.Context, jobId uint64, enabled bool) error { func (d *dbBackupRepoImpl) UpdateEnabled(ctx context.Context, jobId uint64, enabled bool) error {
cond := map[string]any{ cond := map[string]any{
"id": jobId, "id": jobId,
} }
@@ -86,10 +86,10 @@ func (d *dbBackupRepoImpl) UpdateEnabled(_ context.Context, jobId uint64, enable
if enabled { if enabled {
desc = "已启用" desc = "已启用"
} }
return d.Updates(cond, map[string]any{ return d.UpdateByCond(ctx, map[string]any{
"enabled": enabled, "enabled": enabled,
"enabled_desc": desc, "enabled_desc": desc,
}) }, cond)
} }
func (d *dbBackupRepoImpl) ListByCond(cond any, listModels any, cols ...string) error { func (d *dbBackupRepoImpl) ListByCond(cond any, listModels any, cols ...string) error {

View File

@@ -80,7 +80,7 @@ func (d *dbRestoreRepoImpl) AddJob(ctx context.Context, jobs any) error {
return addJob[*entity.DbRestore](ctx, d.dbJobBaseImpl, jobs) return addJob[*entity.DbRestore](ctx, d.dbJobBaseImpl, jobs)
} }
func (d *dbRestoreRepoImpl) UpdateEnabled(_ context.Context, jobId uint64, enabled bool) error { func (d *dbRestoreRepoImpl) UpdateEnabled(ctx context.Context, jobId uint64, enabled bool) error {
cond := map[string]any{ cond := map[string]any{
"id": jobId, "id": jobId,
} }
@@ -88,8 +88,8 @@ func (d *dbRestoreRepoImpl) UpdateEnabled(_ context.Context, jobId uint64, enabl
if enabled { if enabled {
desc = "已启用" desc = "已启用"
} }
return d.Updates(cond, map[string]any{ return d.UpdateByCond(ctx, map[string]any{
"enabled": enabled, "enabled": enabled,
"enabled_desc": desc, "enabled_desc": desc,
}) }, cond)
} }

View File

@@ -70,7 +70,7 @@ func (p *Procinst) GetTasks(rc *req.Ctx) {
instIds := collx.ArrayMap[*vo.ProcinstTask, uint64](*taskVos, func(val *vo.ProcinstTask) uint64 { return val.ProcinstId }) instIds := collx.ArrayMap[*vo.ProcinstTask, uint64](*taskVos, func(val *vo.ProcinstTask) uint64 { return val.ProcinstId })
insts := new([]*entity.Procinst) insts := new([]*entity.Procinst)
p.ProcinstApp.GetByIdIn(insts, instIds) p.ProcinstApp.GetByIds(insts, instIds)
instId2Inst := collx.ArrayToMap[*entity.Procinst, uint64](*insts, func(val *entity.Procinst) uint64 { return val.Id }) instId2Inst := collx.ArrayToMap[*entity.Procinst, uint64](*insts, func(val *entity.Procinst) uint64 { return val.Id })
// 赋值任务对应的流程实例 // 赋值任务对应的流程实例

View File

@@ -83,7 +83,7 @@ func (m *machineCmdConfAppImpl) GetCmdConfsByMachineTags(tagPaths ...string) []*
} }
var cmdConfs []*entity.MachineCmdConf var cmdConfs []*entity.MachineCmdConf
m.GetByIdIn(&cmdConfs, cmdConfIds) m.GetByIds(&cmdConfs, cmdConfIds)
for _, cmdConf := range cmdConfs { for _, cmdConf := range cmdConfs {
for _, cmd := range cmdConf.Cmds { for _, cmd := range cmdConf.Cmds {

View File

@@ -7,8 +7,8 @@ import (
"mayfly-go/internal/sys/domain/repository" "mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base" "mayfly-go/pkg/base"
"mayfly-go/pkg/errorx" "mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model" "mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"mayfly-go/pkg/utils/stringx" "mayfly-go/pkg/utils/stringx"
"strings" "strings"
"time" "time"
@@ -138,14 +138,14 @@ func (r *resourceAppImpl) Sort(ctx context.Context, sortResource *entity.Resourc
} }
// 更新零值使用map因为pid=0表示根节点 // 更新零值使用map因为pid=0表示根节点
updateMap := map[string]interface{}{ updateMap := collx.M{
"pid": sortResource.Pid, "pid": sortResource.Pid,
"weight": sortResource.Weight, "weight": sortResource.Weight,
"ui_path": newParentResourceUiPath + resourceUi, "ui_path": newParentResourceUiPath + resourceUi,
} }
condition := new(entity.Resource) condition := new(entity.Resource)
condition.Id = sortResource.Id condition.Id = sortResource.Id
return gormx.Updates(condition, condition, updateMap) return r.UpdateByCond(ctx, updateMap, condition)
} }
func (r *resourceAppImpl) checkCode(code string) error { func (r *resourceAppImpl) checkCode(code string) error {

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/sys/domain/entity" "mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository" "mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base" "mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
) )
type resourceRepoImpl struct { type resourceRepoImpl struct {
@@ -26,7 +25,7 @@ func (r *resourceRepoImpl) GetChildren(uiPath string) []entity.Resource {
func (r *resourceRepoImpl) UpdateByUiPathLike(resource *entity.Resource) error { func (r *resourceRepoImpl) UpdateByUiPathLike(resource *entity.Resource) error {
sql := "UPDATE t_sys_resource SET status=? WHERE (ui_path LIKE ?)" sql := "UPDATE t_sys_resource SET status=? WHERE (ui_path LIKE ?)"
return gormx.ExecSql(sql, resource.Status, resource.UiPath+"%") return r.ExecBySql(sql, resource.Status, resource.UiPath+"%")
} }
func (r *resourceRepoImpl) GetAccountResources(accountId uint64, toEntity any) error { func (r *resourceRepoImpl) GetAccountResources(accountId uint64, toEntity any) error {

View File

@@ -338,7 +338,7 @@ func (p *tagTreeAppImpl) RelateTagsByCodeAndType(ctx context.Context, param *Rel
} }
func (p *tagTreeAppImpl) UpdateTagName(ctx context.Context, tagType entity.TagType, tagCode string, tagName string) error { func (p *tagTreeAppImpl) UpdateTagName(ctx context.Context, tagType entity.TagType, tagCode string, tagName string) error {
return p.UpdateByCond(ctx, &entity.TagTree{Name: tagName}, model.NewCond().Eq0("type", tagType).Eq0("code", tagCode)) return p.UpdateByCond(ctx, &entity.TagTree{Name: tagName}, &entity.TagTree{Type: tagType, Code: tagCode})
} }
func (p *tagTreeAppImpl) ChangeParentTag(ctx context.Context, tagType entity.TagType, tagCode string, parentTagType entity.TagType, newParentCode string) error { func (p *tagTreeAppImpl) ChangeParentTag(ctx context.Context, tagType entity.TagType, tagCode string, parentTagType entity.TagType, newParentCode string) error {
@@ -545,7 +545,7 @@ func (p *tagTreeAppImpl) toTags(parentTags []*entity.TagTree, param *ResourceTag
} }
func (p *tagTreeAppImpl) deleteByIds(ctx context.Context, tagIds []uint64) error { func (p *tagTreeAppImpl) deleteByIds(ctx context.Context, tagIds []uint64) error {
if err := p.DeleteByCond(ctx, model.NewCond().In("id", tagIds)); err != nil { if err := p.DeleteById(ctx, tagIds...); err != nil {
return err return err
} }

View File

@@ -118,7 +118,7 @@ func (tr *tagTreeRelateAppImpl) FillTagInfo(relateType entity.TagRelateType, rel
return rt.TagId return rt.TagId
}) })
var tags []*entity.TagTree var tags []*entity.TagTree
tr.tagTreeApp.GetByIdIn(&tags, tagIds) tr.tagTreeApp.GetByIds(&tags, tagIds)
tagId2Tag := collx.ArrayToMap(tags, func(t *entity.TagTree) uint64 { tagId2Tag := collx.ArrayToMap(tags, func(t *entity.TagTree) uint64 {
return t.Id return t.Id

View File

@@ -23,26 +23,24 @@ type App[T model.ModelI] interface {
UpdateById(ctx context.Context, e T) error UpdateById(ctx context.Context, e T) error
// UpdateByCond 更新满足条件的数据 // UpdateByCond 更新满足条件的数据
// @param values 需为模型结构体指针或map(更新零值等)
// @param cond 可为*model.QueryCond也可以为普通查询model // @param cond 可为*model.QueryCond也可以为普通查询model
UpdateByCond(ctx context.Context, e T, cond any) error UpdateByCond(ctx context.Context, values any, cond any) error
// DeleteById 根据实体主键删除实体 // DeleteById 根据实体主键删除实体
DeleteById(ctx context.Context, id uint64) error DeleteById(ctx context.Context, id ...uint64) error
// DeleteByCond 根据条件进行删除 // DeleteByCond 根据条件进行删除
DeleteByCond(ctx context.Context, cond any) error DeleteByCond(ctx context.Context, cond any) error
// Updates 根据实体条件更新参数udpateFields指定字段
Updates(ctx context.Context, cond any, udpateFields map[string]any) error
// Save 保存实体实体IsCreate返回true则新增否则更新 // Save 保存实体实体IsCreate返回true则新增否则更新
Save(ctx context.Context, e T) error Save(ctx context.Context, e T) error
// GetById 根据实体id查询 // GetById 根据实体id查询
GetById(e T, id uint64, cols ...string) (T, error) GetById(e T, id uint64, cols ...string) (T, error)
// GetByIdIn 根据实体id数组查询 // GetByIds 根据实体id数组查询
GetByIdIn(list any, ids []uint64, orderBy ...string) error GetByIds(list any, ids []uint64, orderBy ...string) error
// GetByCond 根据实体条件查询实体信息(获取单个实体) // GetByCond 根据实体条件查询实体信息(获取单个实体)
GetByCond(cond any) error GetByCond(cond any) error
@@ -85,13 +83,11 @@ func (ai *AppImpl[T, R]) UpdateById(ctx context.Context, e T) error {
return ai.GetRepo().UpdateById(ctx, e) return ai.GetRepo().UpdateById(ctx, e)
} }
func (ai *AppImpl[T, R]) UpdateByCond(ctx context.Context, e T, cond any) error { // UpdateByCond 更新满足条件的数据
return ai.GetRepo().UpdateByCond(ctx, e, cond) // @param values 需为模型结构体指针或map(更新零值等)
} // @param cond 可为*model.QueryCond也可以为普通查询model
func (ai *AppImpl[T, R]) UpdateByCond(ctx context.Context, values any, cond any) error {
// 根据实体条件更新参数udpateFields指定字段 (单纯更新,不做其他业务逻辑处理) return ai.GetRepo().UpdateByCond(ctx, values, cond)
func (ai *AppImpl[T, R]) Updates(ctx context.Context, cond any, udpateFields map[string]any) error {
return ai.GetRepo().Updates(cond, udpateFields)
} }
// 保存实体实体IsCreate返回true则新增否则更新 // 保存实体实体IsCreate返回true则新增否则更新
@@ -106,8 +102,8 @@ func (ai *AppImpl[T, R]) SaveWithDb(ctx context.Context, db *gorm.DB, e T) error
} }
// 根据实体主键删除实体 (单纯删除实体,不做其他业务逻辑处理) // 根据实体主键删除实体 (单纯删除实体,不做其他业务逻辑处理)
func (ai *AppImpl[T, R]) DeleteById(ctx context.Context, id uint64) error { func (ai *AppImpl[T, R]) DeleteById(ctx context.Context, id ...uint64) error {
return ai.GetRepo().DeleteById(ctx, id) return ai.GetRepo().DeleteById(ctx, id...)
} }
// 根据指定条件删除实体 (单纯删除实体,不做其他业务逻辑处理) // 根据指定条件删除实体 (单纯删除实体,不做其他业务逻辑处理)
@@ -123,8 +119,8 @@ func (ai *AppImpl[T, R]) GetById(e T, id uint64, cols ...string) (T, error) {
return e, nil return e, nil
} }
func (ai *AppImpl[T, R]) GetByIdIn(list any, ids []uint64, orderBy ...string) error { func (ai *AppImpl[T, R]) GetByIds(list any, ids []uint64, orderBy ...string) error {
return ai.GetRepo().GetByIdIn(list, ids, orderBy...) return ai.GetRepo().GetByIds(list, ids, orderBy...)
} }
// 根据实体条件查询实体信息 // 根据实体条件查询实体信息

View File

@@ -5,6 +5,8 @@ import (
"mayfly-go/pkg/contextx" "mayfly-go/pkg/contextx"
"mayfly-go/pkg/gormx" "mayfly-go/pkg/gormx"
"mayfly-go/pkg/model" "mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"time"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -34,11 +36,13 @@ type Repo[T model.ModelI] interface {
UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T, columns ...string) error UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T, columns ...string) error
// UpdateByCond 更新满足条件的数据 // UpdateByCond 更新满足条件的数据
// @param values 需要模型结构体或map
// @param cond 条件 // @param cond 条件
UpdateByCond(ctx context.Context, e T, cond any) error UpdateByCond(ctx context.Context, values any, cond any) error
// UpdateByCondWithDb 更新满足条件的数据 // UpdateByCondWithDb 更新满足条件的数据
UpdateByCondWithDb(ctx context.Context, db *gorm.DB, e T, cond any) error // @param values 需要模型结构体或map
UpdateByCondWithDb(ctx context.Context, db *gorm.DB, values any, cond any) error
// 保存实体实体IsCreate返回true则新增否则更新 // 保存实体实体IsCreate返回true则新增否则更新
Save(ctx context.Context, e T) error Save(ctx context.Context, e T) error
@@ -48,13 +52,10 @@ type Repo[T model.ModelI] interface {
SaveWithDb(ctx context.Context, db *gorm.DB, e T) error SaveWithDb(ctx context.Context, db *gorm.DB, e T) error
// 根据实体主键删除实体 // 根据实体主键删除实体
DeleteById(ctx context.Context, id uint64) error DeleteById(ctx context.Context, id ...uint64) error
// 使用指定gorm db执行主要用于事务执行 // 使用指定gorm db执行主要用于事务执行
DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id uint64) error DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id ...uint64) error
// 根据实体条件更新参数udpateFields指定字段
Updates(cond any, udpateFields map[string]any) error
// 根据实体条件删除实体 // 根据实体条件删除实体
DeleteByCond(ctx context.Context, cond any) error DeleteByCond(ctx context.Context, cond any) error
@@ -62,11 +63,14 @@ type Repo[T model.ModelI] interface {
// 使用指定gorm db执行主要用于事务执行 // 使用指定gorm db执行主要用于事务执行
DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond any) error DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond any) error
// ExecBySql 执行原生sql
ExecBySql(sql string, params ...any) error
// 根据实体id查询 // 根据实体id查询
GetById(e T, id uint64, cols ...string) error GetById(e T, id uint64, cols ...string) error
// 根据实体id数组查询对应实体列表并将响应结果映射至list // 根据实体id数组查询对应实体列表并将响应结果映射至list
GetByIdIn(list any, ids []uint64, orderBy ...string) error GetByIds(list any, ids []uint64, orderBy ...string) error
// GetByCond 根据实体条件查询实体信息(单个结果集) // GetByCond 根据实体条件查询实体信息(单个结果集)
GetByCond(cond any) error GetByCond(cond any) error
@@ -119,37 +123,50 @@ func (br *RepoImpl[T]) BatchInsertWithDb(ctx context.Context, db *gorm.DB, es []
} }
func (br *RepoImpl[T]) UpdateById(ctx context.Context, e T, columns ...string) error { func (br *RepoImpl[T]) UpdateById(ctx context.Context, e T, columns ...string) error {
if db := contextx.GetDb(ctx); db != nil { return br.UpdateByIdWithDb(ctx, contextx.GetDb(ctx), e, columns...)
return br.UpdateByIdWithDb(ctx, db, e, columns...)
}
return gormx.UpdateById(br.fillBaseInfo(ctx, e), columns...)
} }
func (br *RepoImpl[T]) UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T, columns ...string) error { func (br *RepoImpl[T]) UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T, columns ...string) error {
if db == nil {
return gormx.UpdateById(br.fillBaseInfo(ctx, e), columns...)
}
return gormx.UpdateByIdWithDb(db, br.fillBaseInfo(ctx, e), columns...) return gormx.UpdateByIdWithDb(db, br.fillBaseInfo(ctx, e), columns...)
} }
func (br *RepoImpl[T]) UpdateByCond(ctx context.Context, e T, cond any) error { func (br *RepoImpl[T]) UpdateByCond(ctx context.Context, values any, cond any) error {
if db := contextx.GetDb(ctx); db != nil { return br.UpdateByCondWithDb(ctx, contextx.GetDb(ctx), values, cond)
return br.UpdateByCondWithDb(ctx, db, e, cond)
} }
func (br *RepoImpl[T]) UpdateByCondWithDb(ctx context.Context, db *gorm.DB, values any, cond any) error {
if e, ok := values.(T); ok {
// 先随机设置一个id让fillBaseInfo不填充create信息
e.SetId(1)
e = br.fillBaseInfo(ctx, e) e = br.fillBaseInfo(ctx, e)
// model的主键值需为空否则会带上主键条件 // model的主键值需为空否则会带上主键条件
e.SetId(0) e.SetId(0)
return gormx.UpdateByCond(e, toQueryCond(cond)) values = e
} else {
var mapValues map[string]any
// 非model实体则为map
if m, ok := values.(map[string]any); ok {
mapValues = m
} else if collxm, ok := values.(collx.M); ok {
mapValues = map[string]any(collxm)
}
if len(mapValues) > 0 {
mapValues[model.UpdateTimeColumn] = time.Now()
if la := contextx.GetLoginAccount(ctx); la != nil {
mapValues[model.ModifierColumn] = la.Username
mapValues[model.ModifierIdColumn] = la.Id
}
values = mapValues
}
} }
func (br *RepoImpl[T]) UpdateByCondWithDb(ctx context.Context, db *gorm.DB, e T, cond any) error { if db == nil {
e = br.fillBaseInfo(ctx, e) return gormx.UpdateByCond(br.GetModel(), values, toQueryCond(cond))
// model的主键值需为空否则会带上主键条件
e.SetId(0)
return gormx.UpdateByCondWithDb(db, br.fillBaseInfo(ctx, e), toQueryCond(cond))
} }
return gormx.UpdateByCondWithDb(db, br.GetModel(), values, toQueryCond(cond))
func (br *RepoImpl[T]) Updates(cond any, udpateFields map[string]any) error {
return gormx.Updates(br.GetModel(), cond, udpateFields)
} }
func (br *RepoImpl[T]) Save(ctx context.Context, e T) error { func (br *RepoImpl[T]) Save(ctx context.Context, e T) error {
@@ -166,15 +183,15 @@ func (br *RepoImpl[T]) SaveWithDb(ctx context.Context, db *gorm.DB, e T) error {
return br.UpdateByIdWithDb(ctx, db, e) return br.UpdateByIdWithDb(ctx, db, e)
} }
func (br *RepoImpl[T]) DeleteById(ctx context.Context, id uint64) error { func (br *RepoImpl[T]) DeleteById(ctx context.Context, id ...uint64) error {
if db := contextx.GetDb(ctx); db != nil { if db := contextx.GetDb(ctx); db != nil {
return br.DeleteByIdWithDb(ctx, db, id) return br.DeleteByIdWithDb(ctx, db, id...)
} }
return gormx.DeleteById(br.GetModel(), id) return gormx.DeleteById(br.GetModel(), id...)
} }
func (br *RepoImpl[T]) DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id uint64) error { func (br *RepoImpl[T]) DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id ...uint64) error {
return gormx.DeleteByIdWithDb(db, br.GetModel(), id) return gormx.DeleteByIdWithDb(db, br.GetModel(), id...)
} }
func (br *RepoImpl[T]) DeleteByCond(ctx context.Context, cond any) error { func (br *RepoImpl[T]) DeleteByCond(ctx context.Context, cond any) error {
@@ -188,6 +205,10 @@ func (br *RepoImpl[T]) DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond
return gormx.DeleteByCondWithDb(db, br.GetModel(), toQueryCond(cond)) return gormx.DeleteByCondWithDb(db, br.GetModel(), toQueryCond(cond))
} }
func (br *RepoImpl[T]) ExecBySql(sql string, params ...any) error {
return gormx.ExecSql(sql, params...)
}
func (br *RepoImpl[T]) GetById(e T, id uint64, cols ...string) error { func (br *RepoImpl[T]) GetById(e T, id uint64, cols ...string) error {
if err := gormx.GetById(e, id, cols...); err != nil { if err := gormx.GetById(e, id, cols...); err != nil {
return err return err
@@ -195,7 +216,7 @@ func (br *RepoImpl[T]) GetById(e T, id uint64, cols ...string) error {
return nil return nil
} }
func (br *RepoImpl[T]) GetByIdIn(list any, ids []uint64, orderBy ...string) error { func (br *RepoImpl[T]) GetByIds(list any, ids []uint64, orderBy ...string) error {
return br.SelectByCond(model.NewCond().In(model.IdColumn, ids).OrderBy(orderBy...), list) return br.SelectByCond(model.NewCond().In(model.IdColumn, ids).OrderBy(orderBy...), list)
} }
@@ -231,6 +252,7 @@ func (br *RepoImpl[T]) fillBaseInfo(ctx context.Context, e T) T {
return e return e
} }
// toQueryCond 统一转为*model.QueryCond
func toQueryCond(cond any) *model.QueryCond { func toQueryCond(cond any) *model.QueryCond {
if qc, ok := cond.(*model.QueryCond); ok { if qc, ok := cond.(*model.QueryCond); ok {
return qc return qc

View File

@@ -22,10 +22,10 @@ func GetById(dbModel any, id uint64, cols ...string) error {
return NewQuery(dbModel, model.NewCond().Columns(cols...).Eq(model.IdColumn, id)).GenGdb().Scopes(UndeleteScope).First(dbModel).Error return NewQuery(dbModel, model.NewCond().Columns(cols...).Eq(model.IdColumn, id)).GenGdb().Scopes(UndeleteScope).First(dbModel).Error
} }
// 获取满足model中不为空的字段值条件的单个对象。model需为指针类型需要将查询出来的值赋值给model // 根据model获取单个实体对象
// //
// 若 error不为nil则为不存在该记录 // 若 error不为nil则为不存在该记录
// @param cond 模型条件 // @param cond 查询条件
func GetByCond(dbModel any, cond *model.QueryCond) error { func GetByCond(dbModel any, cond *model.QueryCond) error {
return NewQuery(dbModel, cond).GenGdb().Scopes(UndeleteScope).First(cond.GetDest()).Error return NewQuery(dbModel, cond).GenGdb().Scopes(UndeleteScope).First(cond.GetDest()).Error
} }
@@ -37,7 +37,7 @@ func CountByCond(dbModel any, cond *model.QueryCond) int64 {
return count return count
} }
// 根据查询条件分页查询数据 // PageQuery 根据查询条件分页查询数据
// 若未指定查询列则查询列以toModels字段为准 // 若未指定查询列则查询列以toModels字段为准
func PageQuery[T any](q *Query, pageParam *model.PageParam, toModels T) (*model.PageResult[T], error) { func PageQuery[T any](q *Query, pageParam *model.PageParam, toModels T) (*model.PageResult[T], error) {
q.Undeleted() q.Undeleted()
@@ -60,7 +60,7 @@ func PageQuery[T any](q *Query, pageParam *model.PageParam, toModels T) (*model.
return &model.PageResult[T]{Total: count, List: toModels}, nil return &model.PageResult[T]{Total: count, List: toModels}, nil
} }
// 根据指定查询条件分页查询数据 // PageByCond 根据指定查询条件分页查询数据
func PageByCond[T any](dbModel any, cond *model.QueryCond, pageParam *model.PageParam, toModels T) (*model.PageResult[T], error) { func PageByCond[T any](dbModel any, cond *model.QueryCond, pageParam *model.PageParam, toModels T) (*model.PageResult[T], error) {
return PageQuery(NewQuery(dbModel, cond), pageParam, toModels) return PageQuery(NewQuery(dbModel, cond), pageParam, toModels)
} }
@@ -111,31 +111,27 @@ func UpdateByIdWithDb(db *gorm.DB, model any, columns ...string) error {
} }
// UpdateByCondWithDb 使用指定gorm.DB更新满足条件的数据(model的主键值需为空否则会带上主键条件) // UpdateByCondWithDb 使用指定gorm.DB更新满足条件的数据(model的主键值需为空否则会带上主键条件)
func UpdateByCond(dbModel any, cond *model.QueryCond) error { func UpdateByCond(dbModel any, values any, cond *model.QueryCond) error {
return UpdateByCondWithDb(global.Db, dbModel, cond) return UpdateByCondWithDb(global.Db, dbModel, values, cond)
} }
// UpdateByCondWithDb 使用指定gorm.DB更新满足条件的数据(model的主键值需为空否则会带上主键条件) // UpdateByCondWithDb 使用指定gorm.DB更新满足条件的数据(model的主键值需为空否则会带上主键条件)
func UpdateByCondWithDb(db *gorm.DB, model any, cond *model.QueryCond) error { // @values values must be a struct or map.
gormDb := db.Model(model).Select(cond.GetSelectColumns()) func UpdateByCondWithDb(db *gorm.DB, dbModel any, values any, cond *model.QueryCond) error {
gormDb := db.Model(dbModel).Select(cond.GetSelectColumns())
setGdbWhere(gormDb, cond) setGdbWhere(gormDb, cond)
return gormDb.Updates(model).Error return gormDb.Updates(values).Error
}
// 根据实体条件更新参数udpateFields指定字段
func Updates(model any, condition any, updateFields map[string]any) error {
return global.Db.Model(model).Where(condition).Updates(updateFields).Error
} }
// 根据id删除model // 根据id删除model
// @param model 数据库映射实体模型 // @param model 数据库映射实体模型
func DeleteById(model_ any, id uint64) error { func DeleteById(model_ any, id ...uint64) error {
return DeleteByIdWithDb(global.Db, model_, id) return DeleteByIdWithDb(global.Db, model_, id...)
} }
// 根据id使用指定gromDb删除 // 根据id使用指定gromDb删除
func DeleteByIdWithDb(db *gorm.DB, model_ any, id uint64) error { func DeleteByIdWithDb(db *gorm.DB, model_ any, id ...uint64) error {
return db.Model(model_).Where("id = ?", id).Updates(getDeleteColumnValue()).Error return DeleteByCondWithDb(db, model_, model.NewCond().In(model.IdColumn, id))
} }
// 根据cond条件删除指定model表数据 // 根据cond条件删除指定model表数据

View File

@@ -12,6 +12,9 @@ const (
IdColumn = "id" IdColumn = "id"
DeletedColumn = "is_deleted" // 删除字段 DeletedColumn = "is_deleted" // 删除字段
DeleteTimeColumn = "delete_time" DeleteTimeColumn = "delete_time"
ModifierColumn = "modifier"
ModifierIdColumn = "modifier_id"
UpdateTimeColumn = "update_time"
ModelDeleted int8 = 1 ModelDeleted int8 = 1
ModelUndeleted int8 = 0 ModelUndeleted int8 = 0