refactor: 精简base.repo与base.app等

This commit is contained in:
meilin.huang
2024-04-28 23:45:57 +08:00
parent 653953ee76
commit f2c7ef78c0
91 changed files with 758 additions and 957 deletions

View File

@@ -48,7 +48,7 @@
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"@vitejs/plugin-vue": "^5.0.4",
"@vue/compiler-sfc": "^3.4.23",
"@vue/compiler-sfc": "^3.4.25",
"code-inspector-plugin": "^0.4.5",
"dotenv": "^16.3.1",
"eslint": "^8.35.0",

View File

@@ -15,7 +15,7 @@ const config = {
baseWsUrl: `${(window as any).globalConfig.BaseWsUrl || `${location.protocol == 'https:' ? 'wss:' : 'ws:'}//${getBaseApiUrl()}`}/api`,
// 系统版本
version: 'v1.8.1',
version: 'v1.8.2',
};
export default config;

View File

@@ -159,7 +159,7 @@
@current-change="handlePageNumChange"
@size-change="handlePageSizeChange"
style="text-align: right"
layout="prev, pager, next, total, sizes, jumper"
layout="prev, pager, next, total, sizes"
:total="total"
v-model:current-page="queryForm.pageNum"
v-model:page-size="queryForm.pageSize"

View File

@@ -1,20 +0,0 @@
import { saveThemeConfig } from '@/common/utils/storage';
import { isDark } from './user.vue';
export const switchDark = () => {
themeConfig.value.isDark = isDark.value;
if (isDark.value) {
themeConfig.value.editorTheme = 'vs-dark';
} else {
themeConfig.value.editorTheme = 'vs';
}
// 如果终端主题不是自定义主题,则切换主题
if (themeConfig.value.terminalTheme != 'custom') {
if (isDark.value) {
themeConfig.value.terminalTheme = 'dark';
} else {
themeConfig.value.terminalTheme = 'solarizedLight';
}
}
saveThemeConfig(themeConfig.value);
};

View File

@@ -114,7 +114,7 @@ export const useThemeConfig = defineStore('themeConfig', {
// 默认布局,可选 1、默认 defaults 2、经典 classic 3、横向 transverse 4、分栏 columns
layout: 'classic',
terminalTheme: 'solarizedLight',
terminalTheme: 'light',
// ssh终端字体颜色
terminalForeground: '#C5C8C6',
// ssh终端背景色
@@ -207,7 +207,7 @@ export const useThemeConfig = defineStore('themeConfig', {
if (isDark) {
this.themeConfig.terminalTheme = 'dark';
} else {
this.themeConfig.terminalTheme = 'solarizedLight';
this.themeConfig.terminalTheme = 'light';
}
}
},

View File

@@ -67,21 +67,21 @@
<el-col :sm="12">
<el-card shadow="hover">
<template #header>
<div class="pointer-icon" @click="toPage('machine')">
<div class="resource-num">
<el-row justify="center">
<div class="resource-num pointer-icon" @click="toPage('machine')">
<SvgIcon
class="mb5 mr5"
:size="28"
:name="TagResourceTypeEnum.Machine.extra.icon"
:color="TagResourceTypeEnum.Machine.extra.iconColor"
/>
<span>{{ state.machine.num }}</span>
<span class="">{{ state.machine.num }}</span>
</div>
</div>
</el-row>
</template>
<el-row>
<el-col :sm="24">
<el-table :data="state.machine.opLogs" :height="state.resourceOpTableHeight" stripe size="small">
<el-table :data="state.machine.opLogs" :height="state.resourceOpTableHeight" stripe size="small" empty-text="暂无操作记录">
<el-table-column prop="createTime" show-overflow-tooltip width="135">
<template #default="scope">
{{ dateFormat(scope.row.createTime) }}
@@ -106,16 +106,16 @@
<el-col :sm="12">
<el-card shadow="hover">
<template #header>
<div class="pointer-icon" @click="toPage('db')">
<div class="resource-num">
<el-row justify="center">
<div class="resource-num pointer-icon" @click="toPage('db')">
<SvgIcon class="mb5 mr5" :size="28" :name="TagResourceTypeEnum.Db.extra.icon" :color="TagResourceTypeEnum.Db.extra.iconColor" />
<span>{{ state.db.num }}</span>
<span class="">{{ state.db.num }}</span>
</div>
</div>
</el-row>
</template>
<el-row>
<el-col :sm="24">
<el-table :data="state.db.opLogs" :height="state.resourceOpTableHeight" stripe size="small">
<el-table :data="state.db.opLogs" :height="state.resourceOpTableHeight" stripe size="small" empty-text="暂无操作记录">
<el-table-column prop="createTime" show-overflow-tooltip min-width="135">
<template #default="scope">
{{ dateFormat(scope.row.createTime) }}
@@ -142,21 +142,21 @@
<el-col :sm="12">
<el-card shadow="hover">
<template #header>
<div class="pointer-icon" @click="toPage('redis')">
<div class="resource-num">
<el-row justify="center">
<div class="resource-num pointer-icon" @click="toPage('redis')">
<SvgIcon
class="mb5 mr5"
:size="28"
:name="TagResourceTypeEnum.Redis.extra.icon"
:color="TagResourceTypeEnum.Redis.extra.iconColor"
/>
<span>{{ state.redis.num }}</span>
<span class="">{{ state.redis.num }}</span>
</div>
</div>
</el-row>
</template>
<el-row>
<el-col :sm="24">
<el-table :data="state.redis.opLogs" :height="state.resourceOpTableHeight" stripe size="small">
<el-table :data="state.redis.opLogs" :height="state.resourceOpTableHeight" stripe size="small" empty-text="暂无操作记录">
<el-table-column prop="createTime" show-overflow-tooltip min-width="135">
<template #default="scope">
{{ dateFormat(scope.row.createTime) }}
@@ -181,21 +181,21 @@
<el-col :sm="12">
<el-card shadow="hover">
<template #header>
<div class="pointer-icon" @click="toPage('mongo')">
<div class="resource-num">
<el-row justify="center">
<div class="resource-num pointer-icon" @click="toPage('mongo')">
<SvgIcon
class="mb5 mr5"
:size="28"
:name="TagResourceTypeEnum.Mongo.extra.icon"
:color="TagResourceTypeEnum.Mongo.extra.iconColor"
/>
<span>{{ state.mongo.num }}</span>
<span class="">{{ state.mongo.num }}</span>
</div>
</div>
</el-row>
</template>
<el-row>
<el-col :sm="24">
<el-table :data="state.mongo.opLogs" :height="state.resourceOpTableHeight" stripe size="small">
<el-table :data="state.mongo.opLogs" :height="state.resourceOpTableHeight" stripe size="small" empty-text="暂无操作记录">
<el-table-column prop="createTime" show-overflow-tooltip min-width="135">
<template #default="scope">
{{ dateFormat(scope.row.createTime) }}

View File

@@ -258,7 +258,7 @@ const cancelEdit = () => {
const btnOk = async () => {
acForm.value.validate(async (valid: boolean) => {
if (valid) {
emit('confirm', state.form);
emit('confirm', { ...state.form });
}
});
};

View File

@@ -144,6 +144,13 @@ const rules = {
trigger: ['change', 'blur'],
},
],
authCertName: [
{
required: true,
message: '请选择授权凭证',
trigger: ['change', 'blur'],
},
],
database: [
{
required: true,
@@ -235,18 +242,14 @@ const open = async () => {
};
const btnOk = async () => {
dbForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
try {
await dbForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
emit('confirm', state.form);
// await saveDbExec();
// ElMessage.success('保存成功');
// emit('val-change', state.form);
// cancel();
});
emit('confirm', state.form);
};
const resetInputDb = () => {

View File

@@ -267,33 +267,33 @@ const getReqForm = async () => {
};
const testConn = async (authCert: any) => {
dbForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
try {
await dbForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = await getReqForm();
state.submitForm.authCerts = [authCert];
await testConnExec();
ElMessage.success('连接成功');
});
state.submitForm = await getReqForm();
state.submitForm.authCerts = [authCert];
await testConnExec();
ElMessage.success('连接成功');
};
const btnOk = async () => {
dbForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
try {
await dbForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = await getReqForm();
await saveInstanceExec();
ElMessage.success('保存成功');
state.form.id = saveInstanceRes as any;
emit('val-change', state.form);
cancel();
});
state.submitForm = await getReqForm();
await saveInstanceExec();
ElMessage.success('保存成功');
state.form.id = saveInstanceRes as any;
emit('val-change', state.form);
cancel();
};
const cancel = () => {

View File

@@ -199,37 +199,37 @@ watchEffect(() => {
});
const testConn = async (authCert: any) => {
machineForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
try {
await machineForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = getReqForm();
state.submitForm.authCerts = [authCert];
await testConnExec();
ElMessage.success('连接成功');
});
state.submitForm = getReqForm();
state.submitForm.authCerts = [authCert];
await testConnExec();
ElMessage.success('连接成功');
};
const btnOk = async () => {
machineForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
try {
await machineForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
if (state.form.authCerts.length == 0) {
ElMessage.error('请完善授权凭证账号信息');
return false;
}
if (state.form.authCerts.length == 0) {
ElMessage.error('请完善授权凭证账号信息');
return false;
}
state.submitForm = getReqForm();
await saveMachineExec();
ElMessage.success('保存成功');
emit('val-change', submitForm);
cancel();
});
state.submitForm = getReqForm();
await saveMachineExec();
ElMessage.success('保存成功');
emit('val-change', submitForm);
cancel();
};
const getReqForm = () => {

View File

@@ -163,30 +163,30 @@ const getReqForm = () => {
};
const testConn = async () => {
mongoForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = getReqForm();
await testConnExec();
ElMessage.success('连接成功');
});
try {
await mongoForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = getReqForm();
await testConnExec();
ElMessage.success('连接成功');
};
const btnOk = async () => {
mongoForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = getReqForm();
await saveMongoExec();
ElMessage.success('保存成功');
emit('val-change', state.form);
cancel();
});
try {
await mongoForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = getReqForm();
await saveMongoExec();
ElMessage.success('保存成功');
emit('val-change', state.form);
cancel();
};
const cancel = () => {

View File

@@ -253,30 +253,31 @@ const getReqForm = async () => {
};
const testConn = async () => {
redisForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
try {
await redisForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = await getReqForm();
await testConnExec();
ElMessage.success('连接成功');
});
state.submitForm = await getReqForm();
await testConnExec();
ElMessage.success('连接成功');
};
const btnOk = async () => {
redisForm.value.validate(async (valid: boolean) => {
if (!valid) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = await getReqForm();
await saveRedisExec();
ElMessage.success('保存成功');
emit('val-change', state.form);
cancel();
});
try {
await redisForm.value.validate();
} catch (e: any) {
ElMessage.error('请正确填写信息');
return false;
}
state.submitForm = await getReqForm();
await saveRedisExec();
ElMessage.success('保存成功');
emit('val-change', state.form);
cancel();
};
const cancel = () => {

View File

@@ -14,6 +14,7 @@ import (
"mayfly-go/pkg/cache"
"mayfly-go/pkg/captcha"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/otp"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils/collx"
@@ -50,7 +51,7 @@ func (a *AccountLogin) Login(rc *req.Ctx) {
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
account := &sysentity.Account{Username: username}
err = a.AccountApp.GetBy(account, "Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret")
err = a.AccountApp.GetByCond(model.NewModelCond(account).Columns("Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret"))
failCountKey := fmt.Sprintf("account:login:failcount:%s", username)
nowFailCount := cache.GetInt(failCountKey)

View File

@@ -79,7 +79,7 @@ func (a *LdapLogin) Login(rc *req.Ctx) {
func (a *LdapLogin) getUser(userName string, cols ...string) (*sysentity.Account, error) {
account := &sysentity.Account{Username: userName}
if err := a.AccountApp.GetBy(account, cols...); err != nil {
if err := a.AccountApp.GetByCond(model.NewModelCond(account).Columns(cols...)); err != nil {
return nil, err
}
return account, nil

View File

@@ -99,7 +99,7 @@ func (a *Oauth2Login) OAuth2Callback(rc *req.Ctx) {
account := new(sysentity.Account)
account.Id = accountId
err = a.AccountApp.GetBy(account, "username")
err = a.AccountApp.GetByCond(model.NewModelCond(account).Columns("username"))
biz.ErrIsNilAppendErr(err, "该账号不存在")
rc.ReqParam = collx.Kvs("username", account.Username, "type", "bind")
@@ -145,9 +145,11 @@ func (a *Oauth2Login) doLoginAction(rc *req.Ctx, userId string, oauth *config.Oa
now := time.Now()
account := &sysentity.Account{
Model: model.Model{
CreateTime: &now,
CreatorId: 0,
Creator: "oauth2",
CreateModel: model.CreateModel{
CreateTime: &now,
CreatorId: 0,
Creator: "oauth2",
},
UpdateTime: &now,
},
Name: userId,

View File

@@ -4,6 +4,7 @@ import (
"context"
"mayfly-go/internal/auth/domain/entity"
"mayfly-go/internal/auth/domain/repository"
"mayfly-go/pkg/model"
)
type Oauth2 interface {
@@ -19,7 +20,7 @@ type oauth2AppImpl struct {
}
func (a *oauth2AppImpl) GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error {
return a.Oauth2AccountRepo.GetBy(condition, cols...)
return a.Oauth2AccountRepo.GetByCond(model.NewModelCond(condition).Columns(cols...))
}
func (a *oauth2AppImpl) BindOAuthAccount(e *entity.Oauth2Account) error {

View File

@@ -5,6 +5,7 @@ import (
"mayfly-go/internal/db/application"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
)
@@ -24,7 +25,7 @@ func (d *DbSql) SaveSql(rc *req.Ctx) {
// 获取用于是否有该dbsql的保存记录有则更改否则新增
dbSql := &entity.DbSql{Type: dbSqlForm.Type, DbId: dbId, Name: dbSqlForm.Name, Db: dbSqlForm.Db}
dbSql.CreatorId = account.Id
e := d.DbSqlApp.GetBy(dbSql)
e := d.DbSqlApp.GetByCond(dbSql)
// 更新sql信息
dbSql.Sql = dbSqlForm.Sql
@@ -43,7 +44,7 @@ func (d *DbSql) GetSqlNames(rc *req.Ctx) {
dbSql := &entity.DbSql{Type: 1, DbId: dbId, Db: dbName}
dbSql.CreatorId = rc.GetLoginAccount().Id
var sqls []entity.DbSql
d.DbSqlApp.ListByCond(dbSql, &sqls, "id", "name")
d.DbSqlApp.ListByCond(model.NewModelCond(dbSql).Columns("id", "name"), &sqls)
rc.ResData = sqls
}
@@ -67,7 +68,7 @@ func (d *DbSql) GetSql(rc *req.Ctx) {
dbSql.CreatorId = rc.GetLoginAccount().Id
dbSql.Name = rc.Query("name")
e := d.DbSqlApp.GetBy(dbSql)
e := d.DbSqlApp.GetByCond(dbSql)
if e != nil {
return
}

View File

@@ -71,7 +71,7 @@ func (d *dbAppImpl) SaveDb(ctx context.Context, dbEntity *entity.Db) error {
return errorx.NewBiz("授权凭证不存在")
}
err = d.GetBy(oldDb)
err = d.GetByCond(oldDb)
if dbEntity.Id == 0 {
if err == nil {
return errorx.NewBiz("该实例下数据库名已存在")
@@ -206,7 +206,8 @@ func (d *dbAppImpl) GetDbConnByInstanceId(instanceId uint64) (*dbi.DbConn, error
}
var dbs []*entity.Db
if err := d.ListByCond(&entity.Db{InstanceId: instanceId}, &dbs, "id", "database"); err != nil {
if err := d.ListByCond(model.NewModelCond(&entity.Db{InstanceId: instanceId}).Columns("id", "database"), &dbs); err != nil {
return nil, errorx.NewBiz("获取数据库列表失败")
}
if len(dbs) == 0 {

View File

@@ -5,7 +5,6 @@ import (
"encoding/binary"
"errors"
"fmt"
"gorm.io/gorm"
"math"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
@@ -15,6 +14,8 @@ import (
"sync"
"time"
"gorm.io/gorm"
"github.com/google/uuid"
)
@@ -74,7 +75,7 @@ func (app *DbBackupApp) prune(ctx context.Context) error {
historyCond := map[string]any{
"db_backup_id": job.Id,
}
if err := app.backupHistoryRepo.ListByCondOrder(historyCond, &histories, "id"); err != nil {
if err := app.backupHistoryRepo.SelectByCond(historyCond, &histories); err != nil {
return err
}
expiringTime := time.Now().Add(-math.MaxInt64)
@@ -140,7 +141,7 @@ func (app *DbBackupApp) Delete(ctx context.Context, jobId uint64) error {
history := &entity.DbBackupHistory{
DbBackupId: jobId,
}
err := app.backupHistoryRepo.GetBy(history, "name")
err := app.backupHistoryRepo.GetByCond(history)
switch {
default:
return err

View File

@@ -76,7 +76,7 @@ func (app *DbBinlogApp) fetchBinlog(ctx context.Context) error {
func (app *DbBinlogApp) pruneBinlog(ctx context.Context) error {
var jobs []*entity.DbBinlog
if err := app.binlogRepo.ListByCond(map[string]any{}, &jobs); err != nil {
if err := app.binlogRepo.SelectByCond(map[string]any{}, &jobs); err != nil {
logx.Error("DbBinlogApp: 获取 BINLOG 同步任务失败: ", err.Error())
return err
}

View File

@@ -110,7 +110,7 @@ func (app *instanceAppImpl) SaveDbInstance(ctx context.Context, instance *SaveDb
SshTunnelMachineId: instanceEntity.SshTunnelMachineId,
}
err := app.GetBy(oldInstance)
err := app.GetByCond(oldInstance)
if instanceEntity.Id == 0 {
if err == nil {
return 0, errorx.NewBiz("该数据库实例已存在")
@@ -178,7 +178,7 @@ func (app *instanceAppImpl) Delete(ctx context.Context, instanceId uint64) error
restore := &entity.DbRestore{
DbInstanceId: instanceId,
}
err = app.restoreApp.restoreRepo.GetBy(restore)
err = app.restoreApp.restoreRepo.GetByCond(restore)
switch {
case err == nil:
biz.ErrNotNil(err, "不能删除数据库实例【%s】请先删除关联的数据库恢复任务。", instance.Name)
@@ -191,7 +191,7 @@ func (app *instanceAppImpl) Delete(ctx context.Context, instanceId uint64) error
backup := &entity.DbBackup{
DbInstanceId: instanceId,
}
err = app.backupApp.backupRepo.GetBy(backup)
err = app.backupApp.backupRepo.GetByCond(backup)
switch {
case err == nil:
biz.ErrNotNil(err, "不能删除数据库实例【%s】请先删除关联的数据库备份任务。", instance.Name)
@@ -204,7 +204,7 @@ func (app *instanceAppImpl) Delete(ctx context.Context, instanceId uint64) error
db := &entity.Db{
InstanceId: instanceId,
}
err = app.dbApp.GetBy(db)
err = app.dbApp.GetByCond(db)
switch {
case err == nil:
biz.ErrNotNil(err, "不能删除数据库实例【%s】请先删除关联的数据库资源。", instance.Name)

View File

@@ -165,7 +165,7 @@ func (d *dbSqlExecAppImpl) FlowBizHandle(ctx context.Context, bizHandleParam *fl
return nil
}
dbSqlExec := &entity.DbSqlExec{FlowBizKey: bizKey}
if err := d.dbSqlExecRepo.GetBy(dbSqlExec); err != nil {
if err := d.dbSqlExecRepo.GetByCond(dbSqlExec); err != nil {
logx.Errorf("flow-[%s]关联的sql执行信息不存在", bizKey)
return nil
}

View File

@@ -11,6 +11,4 @@ type Db interface {
// 分页获取数据信息列表
GetDbList(condition *entity.DbQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
Count(condition *entity.DbQuery) int64
}

View File

@@ -18,30 +18,16 @@ func newDbRepo() repository.Db {
// 分页获取数据库信息列表
func (d *dbRepoImpl) GetDbList(condition *entity.DbQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQueryWithTableName("t_db db").
Select("db.*, inst.name instance_name, inst.type instance_type, inst.host, inst.port ").
Joins("JOIN t_db_instance inst ON db.instance_id = inst.id").
Eq("db.instance_id", condition.InstanceId).
Eq("db.id", condition.Id).
Like("db.database", condition.Database).
Eq("db.code", condition.Code).
In("db.code", condition.Codes).
Eq0("db."+model.DeletedColumn, model.ModelUndeleted).
Eq0("inst."+model.DeletedColumn, model.ModelUndeleted)
qd := gormx.NewQueryWithTableName("t_db db").Joins("JOIN t_db_instance inst ON db.instance_id = inst.id").
WithCond(model.NewCond().Columns("db.*, inst.name instance_name, inst.type instance_type, inst.host, inst.port ").
Eq("db.instance_id", condition.InstanceId).
Eq("db.id", condition.Id).
Like("db.database", condition.Database).
Eq("db.code", condition.Code).
In("db.code", condition.Codes).
Eq0("db."+model.DeletedColumn, model.ModelUndeleted).
Eq0("inst."+model.DeletedColumn, model.ModelUndeleted),
)
return gormx.PageQuery(qd, pageParam, toEntity)
}
func (d *dbRepoImpl) Count(condition *entity.DbQuery) int64 {
where := make(map[string]any)
if len(condition.TagIds) > 0 {
where["tag_id"] = condition.TagIds
}
if condition.InstanceId > 0 {
where["instance_id"] = condition.InstanceId
}
if condition.Code != "" {
where["code"] = condition.Code
}
return d.CountByCond(where)
}

View File

@@ -64,13 +64,13 @@ func (d *dbBackupRepoImpl) ListToDo(jobs any) error {
// GetPageList 分页获取数据库备份任务列表
func (d *dbBackupRepoImpl) GetPageList(condition *entity.DbBackupQuery, pageParam *model.PageParam, toEntity any, _ ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(d.GetModel()).
qd := model.NewCond().
Eq("id", condition.Id).
Eq0("db_instance_id", condition.DbInstanceId).
Eq0("repeated", condition.Repeated).
In0("db_name", condition.InDbNames).
Like("db_name", condition.DbName)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}
// AddJob 添加数据库任务
@@ -93,5 +93,5 @@ func (d *dbBackupRepoImpl) UpdateEnabled(_ context.Context, jobId uint64, enable
}
func (d *dbBackupRepoImpl) ListByCond(cond any, listModels any, cols ...string) error {
return d.dbJobBaseImpl.ListByCond(cond, listModels, cols...)
return d.dbJobBaseImpl.SelectByCond(model.NewModelCond(cond).Columns(cols...), listModels)
}

View File

@@ -2,13 +2,14 @@ package persistence
import (
"errors"
"gorm.io/gorm"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/global"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"gorm.io/gorm"
)
var _ repository.DbBackupHistory = (*dbBackupHistoryRepoImpl)(nil)
@@ -22,13 +23,13 @@ func NewDbBackupHistoryRepo() repository.DbBackupHistory {
}
func (repo *dbBackupHistoryRepoImpl) GetPageList(condition *entity.DbBackupHistoryQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(repo.GetModel()).
qd := model.NewCond().
Eq("id", condition.Id).
Eq0("db_instance_id", condition.DbInstanceId).
In0("db_name", condition.InDbNames).
Eq("db_backup_id", condition.DbBackupId).
Eq("db_name", condition.DbName)
return gormx.PageQuery(qd, pageParam, toEntity)
return repo.PageByCond(qd, pageParam, toEntity)
}
func (repo *dbBackupHistoryRepoImpl) GetHistories(backupHistoryIds []uint64, toEntity any) error {

View File

@@ -3,13 +3,15 @@ package persistence
import (
"context"
"errors"
"gorm.io/gorm"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/global"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"time"
"gorm.io/gorm"
)
var _ repository.DbBinlogHistory = (*dbBinlogHistoryRepoImpl)(nil)
@@ -23,47 +25,40 @@ func NewDbBinlogHistoryRepo() repository.DbBinlogHistory {
}
func (repo *dbBinlogHistoryRepoImpl) GetHistoryByTime(instanceId uint64, targetTime time.Time) (*entity.DbBinlogHistory, error) {
gdb := gormx.NewQuery(repo.GetModel()).
qc := model.NewCond().
Eq("db_instance_id", instanceId).
Le("first_event_time", targetTime).
Undeleted().
OrderByDesc("first_event_time").
GenGdb()
OrderByDesc("first_event_time")
history := &entity.DbBinlogHistory{}
err := gdb.First(history).Error
if err != nil {
if err := repo.GetByCond(qc.Dest(history)); err != nil {
return nil, err
}
return history, err
return history, nil
}
func (repo *dbBinlogHistoryRepoImpl) GetHistories(instanceId uint64, start, target *entity.BinlogInfo) ([]*entity.DbBinlogHistory, error) {
gdb := gormx.NewQuery(repo.GetModel()).
qc := model.NewCond().
Eq("db_instance_id", instanceId).
Ge("sequence", start.Sequence).
Le("sequence", target.Sequence).
Undeleted().
OrderByAsc("sequence").
GenGdb()
OrderByAsc("sequence")
var histories []*entity.DbBinlogHistory
err := gdb.Find(&histories).Error
if err != nil {
if err := repo.SelectByCond(qc, &histories); err != nil {
return nil, err
}
if len(histories) == 0 {
return nil, errors.New("未找到满足条件的 binlog 文件")
}
return histories, err
return histories, nil
}
func (repo *dbBinlogHistoryRepoImpl) GetLatestHistory(instanceId uint64) (*entity.DbBinlogHistory, bool, error) {
history := &entity.DbBinlogHistory{}
err := gormx.NewQuery(repo.GetModel()).
qc := model.NewCond().
Eq("db_instance_id", instanceId).
Undeleted().
OrderByDesc("sequence").
GenGdb().
First(history).Error
Dest(history)
err := repo.GetByCond(qc)
switch {
case err == nil:
return history, true, nil

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,10 +17,10 @@ func newDataSyncTaskRepo() repository.DataSyncTask {
// 分页获取数据库信息列表
func (d *dataSyncTaskRepoImpl) GetTaskList(condition *entity.DataSyncTaskQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.DataSyncTask)).
qd := model.NewCond().
Like("task_name", condition.Name).
Eq("status", condition.Status)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}
type dataSyncLogRepoImpl struct {
@@ -30,9 +29,9 @@ type dataSyncLogRepoImpl struct {
// 分页获取数据库信息列表
func (d *dataSyncLogRepoImpl) GetTaskLogList(condition *entity.DataSyncLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.DataSyncLog)).
qd := model.NewCond().
Eq("task_id", condition.TaskId)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}
func newDataSyncLogRepo() repository.DataSyncLog {

View File

@@ -4,12 +4,13 @@ import (
"context"
"errors"
"fmt"
"gorm.io/gorm"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"reflect"
"gorm.io/gorm"
)
var _ repository.DbJobBase[entity.DbJob] = (*dbJobBaseImpl[entity.DbJob])(nil)

View File

@@ -55,13 +55,13 @@ func (d *dbRestoreRepoImpl) ListToDo(jobs any) error {
// GetPageList 分页获取数据库备份任务列表
func (d *dbRestoreRepoImpl) GetPageList(condition *entity.DbRestoreQuery, pageParam *model.PageParam, toEntity any, _ ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(d.GetModel()).
qd := model.NewCond().
Eq("id", condition.Id).
Eq0("db_instance_id", condition.DbInstanceId).
Eq0("repeated", condition.Repeated).
In0("db_name", condition.InDbNames).
Like("db_name", condition.DbName)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}
func (d *dbRestoreRepoImpl) GetEnabledRestores(toEntity any, backupHistoryId ...uint64) error {

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -19,9 +18,9 @@ func NewDbRestoreHistoryRepo() repository.DbRestoreHistory {
}
func (d *dbRestoreHistoryRepoImpl) GetDbRestoreHistories(condition *entity.DbRestoreHistoryQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(d.GetModel()).
qd := model.NewCond().
Eq("id", condition.Id).
Eq("db_backup_id", condition.DbRestoreId)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,13 +17,13 @@ func newDbSqlExecRepo() repository.DbSqlExec {
// 分页获取
func (d *dbSqlExecRepoImpl) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.DbSqlExec)).
qd := model.NewCond().
Eq("db_id", condition.DbId).
Eq("`table`", condition.Table).
Eq("type", condition.Type).
Eq("creator_id", condition.CreatorId).
Eq("flow_biz_key", condition.FlowBizKey).
In("status", condition.Status).
RLike("db", condition.Db).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
RLike("db", condition.Db).OrderBy(orderBy...)
return d.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,8 +17,8 @@ func newDbTransferTaskRepo() repository.DbTransferTask {
// 分页获取数据库信息列表
func (d *dbTransferTaskRepoImpl) GetTaskList(condition *entity.DbTransferTaskQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.DbTransferTask))
qd := model.NewCond()
//Like("task_name", condition.Name).
//Eq("status", condition.Status)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,11 +17,11 @@ func NewInstanceRepo() repository.Instance {
// 分页获取数据库信息列表
func (d *instanceRepoImpl) GetInstanceList(condition *entity.InstanceQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.DbInstance)).
qd := model.NewCond().
Eq("id", condition.Id).
Eq("host", condition.Host).
Like("name", condition.Name).
Like("code", condition.Code).
In("code", condition.Codes)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -26,7 +26,7 @@ func (p *Procdef) GetProcdef(rc *req.Ctx) {
biz.NotEmpty(defkey, "流程定义key不能为空")
procdef := &entity.Procdef{DefKey: defkey}
biz.ErrIsNil(p.ProcdefApp.GetBy(procdef), "该流程定义不存在")
biz.ErrIsNil(p.ProcdefApp.GetByCond(procdef), "该流程定义不存在")
rc.ResData = procdef
}

View File

@@ -51,7 +51,7 @@ func (p *Procinst) GetProcinstDetail(rc *req.Ctx) {
// 流程实例任务信息
instTasks := new([]*entity.ProcinstTask)
biz.ErrIsNil(p.ProcinstTaskRepo.ListByCond(&entity.ProcinstTask{ProcinstId: pi.Id}, instTasks))
biz.ErrIsNil(p.ProcinstTaskRepo.SelectByCond(&entity.ProcinstTask{ProcinstId: pi.Id}, instTasks))
pivo.ProcinstTasks = *instTasks
rc.ResData = pivo

View File

@@ -41,7 +41,7 @@ func (p *procdefAppImpl) Save(ctx context.Context, def *entity.Procdef) error {
return err
}
if def.Id == 0 {
if p.GetBy(&entity.Procdef{DefKey: def.DefKey}) == nil {
if p.GetByCond(&entity.Procdef{DefKey: def.DefKey}) == nil {
return errorx.NewBiz("该流程实例key已存在")
}
return p.Insert(ctx, def)

View File

@@ -57,7 +57,7 @@ func (p *procinstAppImpl) GetProcinstTasks(condition *entity.ProcinstTaskQuery,
func (p *procinstAppImpl) StartProc(ctx context.Context, procdefKey string, reqParam *StarProcParam) (*entity.Procinst, error) {
procdef := &entity.Procdef{DefKey: procdefKey}
if err := p.procdefApp.GetBy(procdef); err != nil {
if err := p.procdefApp.GetByCond(procdef); err != nil {
return nil, errorx.NewBiz("流程实例[%s]不存在", procdefKey)
}
@@ -208,7 +208,7 @@ func (p *procinstAppImpl) BackTask(ctx context.Context, instTaskId uint64, remar
func (p *procinstAppImpl) cancelInstTasks(ctx context.Context, procinstId uint64, cancelReason string) error {
// 流程实例任务信息
instTasks := new([]*entity.ProcinstTask)
p.procinstTaskRepo.ListByCond(&entity.ProcinstTask{ProcinstId: procinstId, Status: entity.ProcinstTaskStatusProcess}, instTasks)
p.procinstTaskRepo.SelectByCond(&entity.ProcinstTask{ProcinstId: procinstId, Status: entity.ProcinstTaskStatusProcess}, instTasks)
for _, instTask := range *instTasks {
instTask.Status = entity.ProcinstTaskStatusCanceled
instTask.Remark = cancelReason

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/flow/domain/entity"
"mayfly-go/internal/flow/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,8 +16,8 @@ func newProcdefRepo() repository.Procdef {
}
func (p *procdefImpl) GetPageList(condition *entity.Procdef, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Procdef)).
qd := model.NewCond().
Like("name", condition.Name).
Like("def_key", condition.DefKey)
return gormx.PageQuery(qd, pageParam, toEntity)
return p.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/flow/domain/entity"
"mayfly-go/internal/flow/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,8 +16,8 @@ func newProcinstRepo() repository.Procinst {
}
func (p *procinstImpl) GetPageList(condition *entity.ProcinstQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Procinst)).WithCondModel(condition)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewModelCond(condition)
return p.PageByCond(qd, pageParam, toEntity)
}
//-----------procinst task--------------
@@ -32,6 +31,6 @@ func newProcinstTaskRepo() repository.ProcinstTask {
}
func (p *procinstTaskImpl) GetPageList(condition *entity.ProcinstTaskQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.ProcinstTask)).WithCondModel(condition)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewModelCond(condition)
return p.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"mayfly-go/internal/event"
"mayfly-go/internal/machine/api/vo"
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/internal/machine/infrastructure/cache"
@@ -40,7 +39,7 @@ type Machine interface {
Delete(ctx context.Context, id uint64) error
// 分页获取机器信息列表
GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity *[]*vo.MachineVO, orderBy ...string) (*model.PageResult[*[]*vo.MachineVO], error)
GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
// 新建机器客户端连接需手动调用Close
NewCli(authCertName string) (*mcm.Cli, error)
@@ -78,7 +77,7 @@ func (m *machineAppImpl) InjectMachineRepo(repo repository.Machine) {
}
// 分页获取机器信息列表
func (m *machineAppImpl) GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity *[]*vo.MachineVO, orderBy ...string) (*model.PageResult[*[]*vo.MachineVO], error) {
func (m *machineAppImpl) GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.GetRepo().GetMachineList(condition, pageParam, toEntity, orderBy...)
}
@@ -98,7 +97,7 @@ func (m *machineAppImpl) SaveMachine(ctx context.Context, param *SaveMachinePara
SshTunnelMachineId: me.SshTunnelMachineId,
}
err := m.GetBy(oldMachine)
err := m.GetByCond(oldMachine)
if me.Id == 0 {
if err == nil {
return errorx.NewBiz("该机器信息已存在")
@@ -268,7 +267,7 @@ func (m *machineAppImpl) TimerUpdateStats() {
logx.Debug("开始定时收集并缓存服务器状态信息...")
scheduler.AddFun("@every 2m", func() {
machineIds := new([]entity.Machine)
m.GetRepo().ListByCond(&entity.Machine{Status: entity.MachineStatusEnable, Protocol: entity.MachineProtocolSsh}, machineIds, "id")
m.ListByCond(model.NewModelCond(&entity.Machine{Status: entity.MachineStatusEnable, Protocol: entity.MachineProtocolSsh}).Columns("id"), machineIds)
for _, ma := range *machineIds {
go func(mid uint64) {
defer func() {
@@ -303,7 +302,7 @@ func (m *machineAppImpl) ToMachineInfoByAc(authCertName string) (*mcm.MachineInf
machine := &entity.Machine{
Code: authCert.ResourceCode,
}
if err := m.GetBy(machine); err != nil {
if err := m.GetByCond(machine); err != nil {
return nil, errorx.NewBiz("该授权凭证关联的机器信息不存在")
}

View File

@@ -193,7 +193,7 @@ func (m *machineCronJobAppImpl) RunCronJob(key string) {
cronJob := new(entity.MachineCronJob)
cronJob.Key = key
err := m.GetBy(cronJob)
err := m.GetByCond(cronJob)
// 不存在或禁用,则移除该任务
if err != nil || cronJob.Status == entity.MachineCronJobStatusDisable {
scheduler.RemoveByKey(key)

View File

@@ -105,7 +105,7 @@ func (m *machineFileAppImpl) GetPageList(condition *entity.MachineFile, pagePara
// 根据条件获取
func (m *machineFileAppImpl) GetMachineFile(condition *entity.MachineFile, cols ...string) error {
return m.GetBy(condition, cols...)
return m.GetByCond(model.NewModelCond(condition).Columns(cols...))
}
// 保存机器文件配置

View File

@@ -1,7 +1,6 @@
package repository
import (
"mayfly-go/internal/machine/api/vo"
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/pkg/base"
"mayfly-go/pkg/model"
@@ -11,5 +10,5 @@ type Machine interface {
base.Repo[*entity.Machine]
// 分页获取机器信息列表
GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity *[]*vo.MachineVO, orderBy ...string) (*model.PageResult[*[]*vo.MachineVO], error)
GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
}

View File

@@ -1,16 +1,10 @@
package persistence
import (
"mayfly-go/internal/machine/api/vo"
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"strings"
"github.com/may-fly/cast"
)
type machineRepoImpl struct {
@@ -22,25 +16,19 @@ func newMachineRepo() repository.Machine {
}
// 分页获取机器信息列表
func (m *machineRepoImpl) GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity *[]*vo.MachineVO, orderBy ...string) (*model.PageResult[*[]*vo.MachineVO], error) {
qd := gormx.NewQuery(new(entity.Machine)).
func (m *machineRepoImpl) GetMachineList(condition *entity.MachineQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := model.NewCond().
Eq("status", condition.Status).
Like("ip", condition.Ip).
Like("name", condition.Name).
In("code", condition.Codes).
Like("code", condition.Code)
Like("code", condition.Code).
In("id", condition.Ids)
// 只查询ssh服务器
if condition.Ssh == entity.MachineProtocolSsh {
qd.Eq("protocol", entity.MachineProtocolSsh)
}
if condition.Ids != "" {
// ,分割id转为id数组
qd.In("id", collx.ArrayMap[string, uint64](strings.Split(condition.Ids, ","), func(val string) uint64 {
return cast.ToUint64(val)
}))
}
return gormx.PageQuery(qd, pageParam, toEntity)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,6 +17,6 @@ func newMachineCronJobRepo() repository.MachineCronJob {
// 分页获取机器信息列表
func (m *machineCronJobRepoImpl) GetPageList(condition *entity.MachineCronJob, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).Like("name", condition.Name).Eq("status", condition.Status).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewCond().Like("name", condition.Name).Eq("status", condition.Status).OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,6 +17,6 @@ func newMachineCronJobExecRepo() repository.MachineCronJobExec {
// 分页获取机器信息列表
func (m *machineCropJobExecRepoImpl) GetPageList(condition *entity.MachineCronJobExec, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewModelCond(condition).OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,7 @@ import (
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
type machineCronJobRelateRepoImpl struct {
@@ -17,18 +17,18 @@ func newMachineCronJobRelateRepo() repository.MachineCronJobRelate {
func (m *machineCronJobRelateRepoImpl) GetList(condition *entity.MachineCronJobRelate) []entity.MachineCronJobRelate {
list := new([]entity.MachineCronJobRelate)
m.ListByCond(condition, list)
m.SelectByCond(condition, list)
return *list
}
func (m *machineCronJobRelateRepoImpl) GetMachineIds(cronJobId uint64) []uint64 {
var machineIds []uint64
m.ListByCond(&entity.MachineCronJobRelate{CronJobId: cronJobId}, &machineIds, "machine_id")
m.SelectByCond(model.NewModelCond(&entity.MachineCronJobRelate{CronJobId: cronJobId}).Columns("machine_id"), &machineIds)
return machineIds
}
func (m *machineCronJobRelateRepoImpl) GetCronJobIds(machineId uint64) []uint64 {
var cronJobIds []uint64
gormx.ListBy(&entity.MachineCronJobRelate{MachineId: machineId}, &cronJobIds, "cron_job_id")
m.SelectByCond(model.NewModelCond(&entity.MachineCronJobRelate{MachineId: machineId}).Columns("cron_job_id"), &cronJobIds)
return cronJobIds
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,6 +17,6 @@ func newMachineFileRepo() repository.MachineFile {
// 分页获取机器文件信息列表
func (m *machineFileRepoImpl) GetPageList(condition *entity.MachineFile, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewModelCond(condition).OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,6 +17,6 @@ func newMachineScriptRepo() repository.MachineScript {
// 分页获取机器信息列表
func (m *machineScriptRepoImpl) GetPageList(condition *entity.MachineScript, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewModelCond(condition).OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/machine/domain/entity"
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,14 +16,14 @@ func newMachineTermOpRepoImpl() repository.MachineTermOp {
}
func (m *machineTermOpRepoImpl) GetPageList(condition *entity.MachineTermOp, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
pd := model.NewModelCond(condition).OrderBy(orderBy...)
return m.PageByCond(pd, pageParam, toEntity)
}
// 根据条件获取记录列表
func (m *machineTermOpRepoImpl) SelectByQuery(cond *entity.MachineTermOpQuery) ([]*entity.MachineTermOp, error) {
qd := gormx.NewQuery(m.GetModel()).Le("create_time", cond.StartCreateTime)
qd := model.NewCond().Le("create_time", cond.StartCreateTime)
var res []*entity.MachineTermOp
err := gormx.ListByQueryCond(qd, &res)
err := m.SelectByCond(qd, &res)
return res, err
}

View File

@@ -77,7 +77,7 @@ func (d *mongoAppImpl) TestConn(me *entity.Mongo) error {
func (d *mongoAppImpl) SaveMongo(ctx context.Context, m *entity.Mongo, tagCodePaths ...string) error {
oldMongo := &entity.Mongo{Name: m.Name, SshTunnelMachineId: m.SshTunnelMachineId}
err := d.GetBy(oldMongo)
err := d.GetByCond(oldMongo)
if m.Id == 0 {
if err == nil {

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/mongo/domain/entity"
"mayfly-go/internal/mongo/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,9 +17,9 @@ func newMongoRepo() repository.Mongo {
// 分页获取数据库信息列表
func (d *mongoRepoImpl) GetList(condition *entity.MongoQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Mongo)).
qd := model.NewCond().
Like("name", condition.Name).
Eq("code", condition.Code).
In("code", condition.Codes)
return gormx.PageQuery(qd, pageParam, toEntity)
return d.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/msg/domain/entity"
"mayfly-go/internal/msg/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,6 +16,6 @@ func newMsgRepo() repository.Msg {
}
func (m *msgRepoImpl) GetPageList(condition *entity.Msg, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
pd := model.NewModelCond(condition).OrderBy(orderBy...)
return m.PageByCond(pd, pageParam, toEntity)
}

View File

@@ -115,7 +115,7 @@ func (r *redisAppImpl) SaveRedis(ctx context.Context, param *SaveRedisParam) err
Host: re.Host,
SshTunnelMachineId: re.SshTunnelMachineId,
}
err := r.GetBy(oldRedis)
err := r.GetByCond(oldRedis)
if re.Id == 0 {
if err == nil {

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/redis/domain/entity"
"mayfly-go/internal/redis/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -18,10 +17,10 @@ func newRedisRepo() repository.Redis {
// 分页获取redis信息列表
func (r *redisRepoImpl) GetRedisList(condition *entity.RedisQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Redis)).
qd := model.NewCond().
Eq("id", condition.Id).
Like("host", condition.Host).
Eq("code", condition.Code).
In("code", condition.Codes)
return gormx.PageQuery(qd, pageParam, toEntity)
return r.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -68,7 +68,7 @@ func (a *Account) ChangePassword(rc *req.Ctx) {
biz.ErrIsNilAppendErr(err, "解密旧密码错误: %s")
account := &entity.Account{Username: form.Username}
err = a.AccountApp.GetBy(account, "Id", "Username", "Password", "Status")
err = a.AccountApp.GetByCond(model.NewModelCond(account).Columns("Id", "Username", "Password", "Status"))
biz.ErrIsNil(err, "旧密码错误")
biz.IsTrue(cryptox.CheckPwdHash(originOldPwd, account.Password), "旧密码错误")
biz.IsTrue(account.IsEnable(), "该账号不可用")

View File

@@ -7,6 +7,7 @@ import (
"mayfly-go/internal/sys/application"
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils/collx"
)
@@ -17,7 +18,7 @@ type Resource struct {
func (r *Resource) GetAllResourceTree(rc *req.Ctx) {
var resources vo.ResourceManageVOList
r.ResourceApp.ListByCondOrder(new(entity.Resource), &resources, "weight asc")
r.ResourceApp.ListByCond(model.NewCond().OrderByAsc("weight"), &resources)
rc.ResData = resources.ToTrees(0)
}

View File

@@ -76,11 +76,10 @@ func (r *Role) SaveResource(rc *req.Ctx) {
// 将,拼接的字符串进行切割并转换
newIds := collx.ArrayMap[string, uint64](strings.Split(form.ResourceIds, ","), func(val string) uint64 {
id, _ := strconv.Atoi(val)
return uint64(id)
return cast.ToUint64(val)
})
r.RoleApp.SaveRoleResource(rc.MetaCtx, form.Id, newIds)
biz.ErrIsNilAppendErr(r.RoleApp.SaveRoleResource(rc.MetaCtx, form.Id, newIds), "保存角色资源失败: %s")
}
// 查看角色关联的用户

View File

@@ -6,11 +6,8 @@ import (
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/cryptox"
"gorm.io/gorm"
)
type Account interface {
@@ -27,6 +24,8 @@ type Account interface {
type accountAppImpl struct {
base.AppImpl[*entity.Account, repository.Account]
accountRoleRepo repository.AccountRole `inject:"AccountRoleRepo"`
}
// 注入AccountRepo
@@ -39,7 +38,7 @@ func (a *accountAppImpl) GetPageList(condition *entity.AccountQuery, pageParam *
}
func (a *accountAppImpl) Create(ctx context.Context, account *entity.Account) error {
if a.GetBy(&entity.Account{Username: account.Username}) == nil {
if a.GetByCond(&entity.Account{Username: account.Username}) == nil {
return errorx.NewBiz("该账号用户名已存在")
}
// 默认密码为账号用户名
@@ -51,7 +50,7 @@ func (a *accountAppImpl) Create(ctx context.Context, account *entity.Account) er
func (a *accountAppImpl) Update(ctx context.Context, account *entity.Account) error {
if account.Username != "" {
unAcc := &entity.Account{Username: account.Username}
err := a.GetBy(unAcc)
err := a.GetByCond(unAcc)
if err == nil && unAcc.Id != account.Id {
return errorx.NewBiz("该用户名已存在")
}
@@ -61,14 +60,9 @@ func (a *accountAppImpl) Update(ctx context.Context, account *entity.Account) er
}
func (a *accountAppImpl) Delete(ctx context.Context, id uint64) error {
return gormx.Tx(
func(db *gorm.DB) error {
// 删除account信息
return a.DeleteByIdWithDb(ctx, db, id)
},
func(db *gorm.DB) error {
// 删除账号关联的角色信息
return gormx.DeleteByWithDb(db, &entity.AccountRole{AccountId: id})
},
)
return a.Tx(ctx, func(ctx context.Context) error {
return a.DeleteById(ctx, id)
}, func(ctx context.Context) error {
return a.accountRoleRepo.DeleteByCond(ctx, &entity.AccountRole{AccountId: id})
})
}

View File

@@ -66,7 +66,7 @@ func (a *configAppImpl) GetConfig(key string) *entity.Config {
return config
}
if err := a.GetBy(config, "Id", "Key", "Value", "Permission"); err != nil {
if err := a.GetByCond(model.NewModelCond(config).Columns("Id", "Key", "Value", "Permission")); err != nil {
logx.Warnf("不存在key = [%s] 的系统配置", key)
} else {
cache.SetStr(SysConfigKeyPrefix+key, jsonx.ToStr(config), -1)

View File

@@ -8,6 +8,7 @@ import (
"mayfly-go/pkg/base"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/stringx"
"strings"
"time"
@@ -29,6 +30,8 @@ type Resource interface {
type resourceAppImpl struct {
base.AppImpl[*entity.Resource, repository.Resource]
roleResourceRepo repository.RoleResource `inject:"RoleResourceRepo"`
}
// 注入ResourceRepo
@@ -149,7 +152,7 @@ func (r *resourceAppImpl) checkCode(code string) error {
if strings.Contains(code, ",") {
return errorx.NewBiz("code不能包含','")
}
if gormx.CountBy(&entity.Resource{Code: code}) != 0 {
if r.CountByCond(&entity.Resource{Code: code}) != 0 {
return errorx.NewBiz("该code已存在")
}
return nil
@@ -166,7 +169,7 @@ func (r *resourceAppImpl) Delete(ctx context.Context, id uint64) error {
for _, v := range children {
r.GetRepo().DeleteById(ctx, v.Id)
// 删除角色关联的资源信息
gormx.DeleteBy(&entity.RoleResource{ResourceId: v.Id})
return r.roleResourceRepo.DeleteByCond(ctx, &entity.RoleResource{ResourceId: v.Id})
}
return nil
}
@@ -177,7 +180,7 @@ func (r *resourceAppImpl) GetAccountResources(accountId uint64, toEntity any) er
cond := &entity.Resource{
Status: entity.ResourceStatusEnable,
}
return r.ListByCondOrder(cond, toEntity, "pid asc", "weight asc")
return r.ListByCond(model.NewModelCond(cond).OrderByAsc("pid").OrderByAsc("weight"), toEntity)
}
return r.GetRepo().GetAccountResources(accountId, toEntity)

View File

@@ -5,17 +5,17 @@ import (
"mayfly-go/internal/sys/consts"
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"time"
"gorm.io/gorm"
)
type Role interface {
base.App[*entity.Role]
GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error)
@@ -29,7 +29,7 @@ type Role interface {
GetRoleResources(roleId uint64, toEntity any)
// 保存角色资源关联记录
SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64)
SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64) error
// 关联账号角色
RelateAccountRole(ctx context.Context, accountId, roleId uint64, relateType consts.AccountRoleRelateType) error
@@ -42,53 +42,55 @@ type Role interface {
}
type roleAppImpl struct {
roleRepo repository.Role `inject:"RoleRepo"`
accountRoleRepo repository.AccountRole `inject:"AccountRoleRepo"`
base.AppImpl[*entity.Role, repository.Role]
accountRoleRepo repository.AccountRole `inject:"AccountRoleRepo"`
roleResourceRepo repository.RoleResource `inject:"RoleResourceRepo"`
}
func (r *roleAppImpl) InjectRoleRepo(repo repository.Role) {
r.Repo = repo
}
func (m *roleAppImpl) GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.roleRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
return m.GetRepo().GetPageList(condition, pageParam, toEntity, orderBy...)
}
func (m *roleAppImpl) ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error) {
return m.roleRepo.ListByQuery(condition)
return m.GetRepo().ListByQuery(condition)
}
func (m *roleAppImpl) SaveRole(ctx context.Context, role *entity.Role) error {
if role.Id != 0 {
// code不可更改防止误传
role.Code = ""
return gormx.UpdateById(role)
return m.UpdateById(ctx, role)
}
role.Status = 1
return m.roleRepo.Insert(ctx, role)
return m.Insert(ctx, role)
}
func (m *roleAppImpl) DeleteRole(ctx context.Context, id uint64) error {
// 删除角色与资源账号的关联关系
return gormx.Tx(
func(db *gorm.DB) error {
return m.roleRepo.DeleteByIdWithDb(ctx, db, id)
},
func(db *gorm.DB) error {
return gormx.DeleteByWithDb(db, &entity.RoleResource{RoleId: id})
},
func(db *gorm.DB) error {
return gormx.DeleteByWithDb(db, &entity.AccountRole{RoleId: id})
},
)
return m.Tx(ctx, func(ctx context.Context) error {
return m.DeleteById(ctx, id)
}, func(ctx context.Context) error {
return m.roleResourceRepo.DeleteByCond(ctx, &entity.RoleResource{RoleId: id})
}, func(ctx context.Context) error {
return m.accountRoleRepo.DeleteByCond(ctx, &entity.AccountRole{RoleId: id})
})
}
func (m *roleAppImpl) GetRoleResourceIds(roleId uint64) []uint64 {
return m.roleRepo.GetRoleResourceIds(roleId)
return m.roleResourceRepo.GetRoleResourceIds(roleId)
}
func (m *roleAppImpl) GetRoleResources(roleId uint64, toEntity any) {
m.roleRepo.GetRoleResources(roleId, toEntity)
m.roleResourceRepo.GetRoleResources(roleId, toEntity)
}
func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64) {
func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64) error {
oIds := m.GetRoleResourceIds(roleId)
addIds, delIds, _ := collx.ArrayCompare(resourceIds, oIds)
@@ -105,11 +107,18 @@ func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resou
rr.IsDeleted = undeleted
addVals = append(addVals, rr)
}
m.roleRepo.SaveRoleResource(addVals)
for _, v := range delIds {
m.roleRepo.DeleteRoleResource(roleId, v)
}
return m.Tx(ctx, func(ctx context.Context) error {
if len(addVals) > 0 {
return m.roleResourceRepo.BatchInsert(ctx, addVals)
}
return nil
}, func(ctx context.Context) error {
if len(delIds) > 0 {
return m.roleResourceRepo.DeleteByCond(ctx, model.NewCond().In("resource_id", delIds))
}
return nil
})
}
func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId uint64, relateType consts.AccountRoleRelateType) error {
@@ -118,7 +127,7 @@ func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId u
return m.accountRoleRepo.DeleteByCond(ctx, accountRole)
}
err := m.accountRoleRepo.GetBy(accountRole)
err := m.accountRoleRepo.GetByCond(accountRole)
if err == nil {
return errorx.NewBiz("该用户已拥有该权限")
}
@@ -133,7 +142,7 @@ func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId u
func (m *roleAppImpl) GetAccountRoles(accountId uint64) ([]*entity.AccountRole, error) {
var res []*entity.AccountRole
err := m.accountRoleRepo.ListByCond(&entity.AccountRole{AccountId: accountId}, &res)
err := m.accountRoleRepo.SelectByCond(&entity.AccountRole{AccountId: accountId}, &res)
return res, err
}

View File

@@ -12,15 +12,6 @@ type Role interface {
GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error)
// 获取角色拥有的资源id数组从role_resource表获取
GetRoleResourceIds(roleId uint64) []uint64
GetRoleResources(roleId uint64, toEntity any)
SaveRoleResource(rr []*entity.RoleResource)
DeleteRoleResource(roleId uint64, resourceId uint64)
}
type AccountRole interface {
@@ -28,3 +19,12 @@ type AccountRole interface {
GetPageList(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
}
type RoleResource interface {
base.Repo[*entity.RoleResource]
// 获取角色拥有的资源id数组从role_resource表获取
GetRoleResourceIds(roleId uint64) []uint64
GetRoleResources(roleId uint64, toEntity any)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,9 +16,9 @@ func newAccountRepo() repository.Account {
}
func (m *AccountRepoImpl) GetPageList(condition *entity.AccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Account)).
qd := model.NewCond().
Like("name", condition.Name).
Like("username", condition.Username).
In("id", condition.Ids)
return gormx.PageQuery(qd, pageParam, toEntity)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -18,13 +18,14 @@ func newAccountRoleRepo() repository.AccountRole {
func (m *accountRoleRepoImpl) GetPageList(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQueryWithTableName("t_sys_account_role t").
Select("t.creator, t.create_time, a.username, a.name accountName, a.status accountStatus, a.id accountId").
Joins("JOIN t_sys_account a ON t.account_id = a.id AND a.status = 1").
Eq0("a.is_deleted", model.ModelUndeleted).
Eq0("t.is_deleted", model.ModelUndeleted).
RLike("a.username", condition.Username).
RLike("a.name", condition.Name).
Eq("t.role_id", condition.RoleId).
OrderByDesc("t.id")
WithCond(model.NewCond().Columns("t.creator, t.create_time, a.username, a.name accountName, a.status accountStatus, a.id accountId").
Eq0("a.is_deleted", model.ModelUndeleted).
Eq0("t.is_deleted", model.ModelUndeleted).
RLike("a.username", condition.Username).
RLike("a.name", condition.Name).
Eq("t.role_id", condition.RoleId).
OrderByDesc("t.id"))
return gormx.PageQuery(qd, pageParam, toEntity)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,9 +16,9 @@ func newConfigRepo() repository.Config {
}
func (m *configRepoImpl) GetPageList(condition *entity.Config, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).
qd := model.NewCond().
Like("`key`", condition.Key).
And("permission = 'all' OR permission LIKE ?", "%"+condition.Permission+",%").
WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -7,6 +7,7 @@ import (
func InitIoc() {
ioc.Register(newAccountRepo(), ioc.WithComponentName("AccountRepo"))
ioc.Register(newRoleRepo(), ioc.WithComponentName("RoleRepo"))
ioc.Register(newRoleResourceRepo(), ioc.WithComponentName("RoleResourceRepo"))
ioc.Register(newAccountRoleRepo(), ioc.WithComponentName("AccountRoleRepo"))
ioc.Register(newResourceRepo(), ioc.WithComponentName("ResourceRepo"))
ioc.Register(newConfigRepo(), ioc.WithComponentName("ConfigRepo"))

View File

@@ -20,7 +20,7 @@ func newResourceRepo() repository.Resource {
func (r *resourceRepoImpl) GetChildren(uiPath string) []entity.Resource {
sql := "SELECT id, ui_path FROM t_sys_resource WHERE ui_path LIKE ? AND is_deleted = 0"
var rs []entity.Resource
gormx.GetListBySql2Model(sql, &rs, uiPath+"%")
r.SelectBySql(sql, &rs, uiPath+"%")
return rs
}
@@ -63,5 +63,5 @@ func (r *resourceRepoImpl) GetAccountResources(accountId uint64, toEntity any) e
ORDER BY
m.pid ASC,
m.weight ASC`
return gormx.GetListBySql2Model(sql, toEntity, accountId)
return r.SelectBySql(sql, toEntity, accountId)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,54 +16,23 @@ func newRoleRepo() repository.Role {
}
func (m *roleRepoImpl) GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Role)).
qd := model.NewCond().
Like("name", condition.Name).
Like("code", condition.Code).
In("id", condition.Ids).
NotIn("id", condition.NotIds).
WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}
func (m *roleRepoImpl) ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error) {
var res []*entity.Role
qd := gormx.NewQuery(new(entity.Role)).
qd := model.NewCond().
Like("name", condition.Name).
Like("code", condition.Code).
In("id", condition.Ids).
NotIn("id", condition.NotIds).
OrderByDesc("id")
err := gormx.ListByQueryCond(qd, &res)
err := m.SelectByCond(qd, &res)
return res, err
}
// 获取角色拥有的资源id数组从role_resource表获取
func (m *roleRepoImpl) GetRoleResourceIds(roleId uint64) []uint64 {
var rrs []entity.RoleResource
condtion := &entity.RoleResource{RoleId: roleId}
gormx.ListBy(condtion, &rrs, "ResourceId")
var rids []uint64
for _, v := range rrs {
rids = append(rids, v.ResourceId)
}
return rids
}
func (m *roleRepoImpl) GetRoleResources(roleId uint64, toEntity any) {
sql := "select rr.creator AS creator, rr.create_time AS CreateTime, rr.resource_id AS id, r.pid AS pid, " +
"r.name AS name, r.type AS type, r.status AS status " +
"FROM t_sys_role_resource rr JOIN t_sys_resource r ON rr.resource_id = r.id " +
"WHERE rr.role_id = ? AND rr.is_deleted = 0 AND r.is_deleted = 0 " +
"ORDER BY r.pid ASC, r.weight ASC"
gormx.GetListBySql2Model(sql, toEntity, roleId)
}
func (m *roleRepoImpl) SaveRoleResource(rr []*entity.RoleResource) {
gormx.BatchInsert[*entity.RoleResource](rr)
}
func (m *roleRepoImpl) DeleteRoleResource(roleId uint64, resourceId uint64) {
gormx.DeleteBy(&entity.RoleResource{RoleId: roleId, ResourceId: resourceId})
}

View File

@@ -0,0 +1,39 @@
package persistence
import (
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/model"
)
type roleResourceRepoImpl struct {
base.RepoImpl[*entity.RoleResource]
}
func newRoleResourceRepo() repository.RoleResource {
return &roleResourceRepoImpl{base.RepoImpl[*entity.RoleResource]{M: new(entity.RoleResource)}}
}
// 获取角色拥有的资源id数组
func (m *roleResourceRepoImpl) GetRoleResourceIds(roleId uint64) []uint64 {
var rrs []entity.RoleResource
condtion := &entity.RoleResource{RoleId: roleId}
m.SelectByCond(model.NewModelCond(condtion).Columns("ResourceId"), &rrs)
var rids []uint64
for _, v := range rrs {
rids = append(rids, v.ResourceId)
}
return rids
}
func (m *roleResourceRepoImpl) GetRoleResources(roleId uint64, toEntity any) {
sql := "select rr.creator AS creator, rr.create_time AS CreateTime, rr.resource_id AS id, r.pid AS pid, " +
"r.name AS name, r.type AS type, r.status AS status " +
"FROM t_sys_role_resource rr JOIN t_sys_resource r ON rr.resource_id = r.id " +
"WHERE rr.role_id = ? AND rr.is_deleted = 0 AND r.is_deleted = 0 " +
"ORDER BY r.pid ASC, r.weight ASC"
m.SelectBySql(sql, toEntity, roleId)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,7 +16,7 @@ func newSyslogRepo() repository.Syslog {
}
func (m *syslogRepoImpl) GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.SysLog)).Like("description", condition.Description).
Eq("creator_id", condition.CreatorId).Eq("type", condition.Type).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity)
qd := model.NewCond().Like("description", condition.Description).
Eq("creator_id", condition.CreatorId).Eq("type", condition.Type).OrderBy(orderBy...)
return m.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -23,7 +23,7 @@ func (r *ResourceAuthCert) ListByQuery(rc *req.Ctx) {
cond.Name = rc.Query("name")
var racs []*entity.ResourceAuthCert
res, err := r.ResourceAuthCertApp.PageQuery(cond, rc.GetPageParam(), &racs)
res, err := r.ResourceAuthCertApp.PageByCond(cond, rc.GetPageParam(), &racs)
biz.ErrIsNil(err)
for _, rac := range racs {
rac.CiphertextClear()
@@ -37,7 +37,7 @@ func (r *ResourceAuthCert) GetCompleteAuthCert(rc *req.Ctx) {
rc.ReqParam = acName
res := &entity.ResourceAuthCert{Name: acName}
err := r.ResourceAuthCertApp.GetBy(res)
err := r.ResourceAuthCertApp.GetByCond(res)
biz.ErrIsNil(err)
res.CiphertextDecrypt()
rc.ResData = res

View File

@@ -18,7 +18,7 @@ func (r *ResourceOpLog) PageAccountOpLog(rc *req.Ctx) {
cond.CreatorId = rc.GetLoginAccount().Id
var rols []*entity.ResourceOpLog
res, err := r.ResourceOpLogApp.PageQuery(cond, rc.GetPageParam(), &rols)
res, err := r.ResourceOpLogApp.PageByCond(cond, rc.GetPageParam(), &rols)
biz.ErrIsNil(err)
rc.ResData = res
}

View File

@@ -9,6 +9,7 @@ import (
"mayfly-go/internal/tag/application"
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils/collx"
"strings"
@@ -39,7 +40,7 @@ func (p *Team) GetTeams(rc *req.Ctx) {
func (p *Team) SaveTeam(rc *req.Ctx) {
team := req.BindJsonAndValid(rc, new(application.SaveTeamParam))
rc.ReqParam = team
biz.ErrIsNil(p.TeamApp.Save(rc.MetaCtx, team))
biz.ErrIsNil(p.TeamApp.SaveTeam(rc.MetaCtx, team))
}
func (p *Team) DelTeam(rc *req.Ctx) {
@@ -76,7 +77,8 @@ func (p *Team) SaveTeamMember(rc *req.Ctx) {
// 校验账号并赋值username
account := &sys_entity.Account{}
account.Id = accountId
biz.ErrIsNil(p.AccountApp.GetBy(account, "Id", "Username"), "账号不存在")
biz.ErrIsNil(p.AccountApp.GetByCond(model.NewModelCond(account).Columns("Id", "Username")), "账号不存在")
teamMember := new(entity.TeamMember)
teamMember.TeamId = teamId

View File

@@ -7,6 +7,7 @@ import (
"mayfly-go/pkg/base"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
)
@@ -91,7 +92,7 @@ func (r *resourceAuthCertAppImpl) RelateAuthCert(ctx context.Context, params *Re
name2AuthCert[resourceAuthCert.Name] = resourceAuthCert
existNameAc := &entity.ResourceAuthCert{Name: resourceAuthCert.Name}
if resourceAuthCert.Id == 0 && r.GetBy(existNameAc) == nil && existNameAc.ResourceCode != resourceCode {
if resourceAuthCert.Id == 0 && r.GetByCond(existNameAc) == nil && existNameAc.ResourceCode != resourceCode {
return errorx.NewBiz("授权凭证的名称不能重复[%s]", resourceAuthCert.Name)
}
@@ -215,7 +216,7 @@ func (r *resourceAuthCertAppImpl) DeleteAuthCert(ctx context.Context, id uint64)
func (r *resourceAuthCertAppImpl) GetAuthCert(authCertName string) (*entity.ResourceAuthCert, error) {
authCert := &entity.ResourceAuthCert{Name: authCertName}
if err := r.GetBy(authCert); err != nil {
if err := r.GetByCond(authCert); err != nil {
return nil, errorx.NewBiz("该授权凭证不存在")
}
@@ -272,7 +273,7 @@ func (r *resourceAuthCertAppImpl) FillAuthCertByAcs(authCerts []*entity.Resource
func (r *resourceAuthCertAppImpl) FillAuthCertByAcNames(authCertNames []string, resources ...entity.IAuthCert) {
var acs []*entity.ResourceAuthCert
r.ListByWheres(collx.M{"name in ?": authCertNames}, &acs)
r.ListByCond(model.NewCond().In("name", authCertNames), &acs)
r.FillAuthCertByAcs(acs, resources...)
}
@@ -285,7 +286,7 @@ func (r *resourceAuthCertAppImpl) FillAuthCert(resourceType int8, resources ...e
return ac.GetCode()
})
var acs []*entity.ResourceAuthCert
r.ListByWheres(collx.M{"resource_code in ?": resourceCodes, "resource_type = ?": resourceType}, &acs)
r.ListByCond(model.NewCond().In("ResoourceCode", resourceCodes).Eq0("ResourceType", resourceType), &acs)
r.FillAuthCertByAcs(acs, resources...)
}
@@ -403,7 +404,7 @@ func (r *resourceAuthCertAppImpl) decryptAuthCert(authCert *entity.ResourceAuthC
if authCert.CiphertextType == entity.AuthCertCiphertextTypePublic {
// 如果是公共授权凭证,则密文为公共授权凭证名称,需要使用该名称再去获取对应的授权凭证
realAuthCert := &entity.ResourceAuthCert{Name: authCert.Ciphertext}
if err := r.GetBy(realAuthCert); err != nil {
if err := r.GetByCond(realAuthCert); err != nil {
return nil, errorx.NewBiz("该公共授权凭证[%s]不存在", authCert.Ciphertext)
}

View File

@@ -7,7 +7,7 @@ import (
"mayfly-go/pkg/base"
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/utils/collx"
"mayfly-go/pkg/model"
"time"
)
@@ -38,7 +38,8 @@ func (rol *resourceOpLogAppImpl) AddResourceOpLog(ctx context.Context, codePath
}
var logs []*entity.ResourceOpLog
if err := rol.ListByWheres(collx.Kvs("create_time > ?", time.Now().Add(-5*time.Minute), "creator_id = ?", loginAccount.Id, "code_path = ?", codePath), &logs); err != nil {
qc := model.NewCond().Ge("create_time", time.Now().Add(-5*time.Minute)).Eq("creator_id", loginAccount.Id).Eq("code_path", codePath)
if err := rol.ListByCond(qc, &logs); err != nil {
return err
}
// 指定时间内多次操作则不记录
@@ -46,7 +47,7 @@ func (rol *resourceOpLogAppImpl) AddResourceOpLog(ctx context.Context, codePath
return nil
}
tagTree := &entity.TagTree{CodePath: codePath}
if err := rol.tagTreeApp.GetBy(tagTree); err != nil {
if err := rol.tagTreeApp.GetByCond(tagTree); err != nil {
return errorx.NewBiz("资源不存在")
}

View File

@@ -10,6 +10,7 @@ import (
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"strings"
)
@@ -252,7 +253,7 @@ func (p *tagTreeAppImpl) SaveResourceTag(ctx context.Context, param *SaveResourc
// 获取所有关联的父标签
var parentTags []*entity.TagTree
p.ListByWheres(collx.M{"code_path in ?": parentTagCodePaths}, &parentTags)
p.ListByCond(model.NewCond().In("code_path", parentTagCodePaths), &parentTags)
if len(parentTags) == 0 || len(parentTags) != len(parentTagCodePaths) {
return errorx.NewBiz("保存资源标签失败: 存在错误的关联标签")
}
@@ -337,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 {
return p.UpdateByWheres(ctx, &entity.TagTree{Name: tagName}, collx.Kvs("code = ?", tagCode, "type = ?", tagType))
return p.UpdateByCond(ctx, &entity.TagTree{Name: tagName}, model.NewCond().Eq0("type", tagType).Eq0("code", tagCode))
}
func (p *tagTreeAppImpl) ChangeParentTag(ctx context.Context, tagType entity.TagType, tagCode string, parentTagType entity.TagType, newParentCode string) error {
@@ -381,12 +382,12 @@ func (p *tagTreeAppImpl) ChangeParentTag(ctx context.Context, tagType entity.Tag
func (p *tagTreeAppImpl) MovingTag(ctx context.Context, fromTagPath string, toTagPath string) error {
fromTag := &entity.TagTree{CodePath: fromTagPath}
if err := p.GetBy(fromTag); err != nil {
if err := p.GetByCond(fromTag); err != nil {
return errorx.NewBiz("移动标签不存在")
}
toTag := &entity.TagTree{CodePath: toTagPath}
if err := p.GetBy(toTag); err != nil {
if err := p.GetByCond(toTag); err != nil {
return errorx.NewBiz("目标标签不存在")
}
@@ -423,10 +424,8 @@ func (p *tagTreeAppImpl) DeleteTagByParam(ctx context.Context, param *DelResourc
for _, resourceTag := range resourceTags {
// 获取所有关联的子标签
var childrenTag []*entity.TagTree
p.ListByWheres(collx.M{
"code_path LIKE ?": resourceTag.CodePath + "%",
"type = ?": delTagType,
}, &childrenTag)
p.ListByCond(model.NewCond().RLike("code_path", resourceTag.CodePath).Eq0("type", delTagType), &childrenTag)
if len(childrenTag) == 0 {
continue
}
@@ -546,14 +545,10 @@ func (p *tagTreeAppImpl) toTags(parentTags []*entity.TagTree, param *ResourceTag
}
func (p *tagTreeAppImpl) deleteByIds(ctx context.Context, tagIds []uint64) error {
if err := p.DeleteByWheres(ctx, collx.M{
"id in ?": tagIds,
}); err != nil {
if err := p.DeleteByCond(ctx, model.NewCond().In("id", tagIds)); err != nil {
return err
}
// 删除与标签有关联信息的记录(如团队关联的标签等)
return p.tagTreeRelateApp.DeleteByWheres(ctx, collx.M{
"tag_id in ?": tagIds,
})
return p.tagTreeRelateApp.DeleteByCond(ctx, model.NewCond().In("tag_id", tagIds))
}

View File

@@ -6,6 +6,7 @@ import (
"mayfly-go/internal/tag/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
)
@@ -75,7 +76,7 @@ func (tr *tagTreeRelateAppImpl) RelateTag(ctx context.Context, relateType entity
}
if len(delTagIds) > 0 {
if err := tr.DeleteByWheres(ctx, collx.Kvs("relate_type=?", relateType, "relate_id=?", relateId, "tag_id in ?", delTagIds)); err != nil {
if err := tr.DeleteByCond(ctx, model.NewCond().Eq("relate_type", relateType).Eq("relate_id", relateId).In("tag_id", delTagIds)); err != nil {
return err
}
}
@@ -111,7 +112,7 @@ func (tr *tagTreeRelateAppImpl) FillTagInfo(relateType entity.TagRelateType, rel
})
var relateTags []*entity.TagTreeRelate
tr.ListByWheres(collx.Kvs("relate_type=?", relateType, "relate_id in ?", collx.MapKeys(relateIds2Relate)), &relateTags)
tr.ListByCond(model.NewCond().Eq("relate_type", relateType).In("relate_id", collx.MapKeys(relateIds2Relate)), &relateTags)
tagIds := collx.ArrayMap(relateTags, func(rt *entity.TagTreeRelate) uint64 {
return rt.TagId

View File

@@ -4,14 +4,12 @@ import (
"context"
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/internal/tag/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/model"
"gorm.io/gorm"
)
type SaveTeamParam struct {
@@ -23,11 +21,13 @@ type SaveTeamParam struct {
}
type Team interface {
base.App[*entity.Team]
// 分页获取项目团队信息列表
GetPageList(condition *entity.TeamQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
// Save 保存团队信息
Save(ctx context.Context, team *SaveTeamParam) error
// SaveTeam 保存团队信息
SaveTeam(ctx context.Context, team *SaveTeamParam) error
Delete(ctx context.Context, id uint64) error
@@ -45,26 +45,32 @@ type Team interface {
}
type teamAppImpl struct {
teamRepo repository.Team `inject:"TeamRepo"`
teamMemberRepo repository.TeamMember `inject:"TeamMemberRepo"`
base.AppImpl[*entity.Team, repository.Team]
tagTreeRelateApp TagTreeRelate `inject:"TagTreeRelateApp"`
teamMemberRepo repository.TeamMember `inject:"TeamMemberRepo"`
tagTreeRelateApp TagTreeRelate `inject:"TagTreeRelateApp"`
}
var _ (Team) = (*teamAppImpl)(nil)
func (p *teamAppImpl) InjectTeamRepo(repo repository.Team) {
p.Repo = repo
}
func (p *teamAppImpl) GetPageList(condition *entity.TeamQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return p.teamRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
return p.GetRepo().GetPageList(condition, pageParam, toEntity, orderBy...)
}
func (p *teamAppImpl) Save(ctx context.Context, saveParam *SaveTeamParam) error {
func (p *teamAppImpl) SaveTeam(ctx context.Context, saveParam *SaveTeamParam) error {
team := &entity.Team{Name: saveParam.Name, Remark: saveParam.Remark}
team.Id = saveParam.Id
if team.Id == 0 {
if p.teamRepo.CountByCond(&entity.Team{Name: saveParam.Name}) > 0 {
if p.CountByCond(&entity.Team{Name: saveParam.Name}) > 0 {
return errorx.NewBiz("团队名[%s]已存在", saveParam.Name)
}
if err := p.teamRepo.Insert(ctx, team); err != nil {
if err := p.Insert(ctx, team); err != nil {
return err
}
@@ -79,7 +85,7 @@ func (p *teamAppImpl) Save(ctx context.Context, saveParam *SaveTeamParam) error
} else {
// 置空名称,防止变更
team.Name = ""
if err := p.teamRepo.UpdateById(ctx, team); err != nil {
if err := p.UpdateById(ctx, team); err != nil {
return err
}
}
@@ -89,17 +95,13 @@ func (p *teamAppImpl) Save(ctx context.Context, saveParam *SaveTeamParam) error
}
func (p *teamAppImpl) Delete(ctx context.Context, id uint64) error {
return gormx.Tx(
func(db *gorm.DB) error {
return p.teamRepo.DeleteByIdWithDb(ctx, db, id)
},
func(db *gorm.DB) error {
return p.teamMemberRepo.DeleteByCondWithDb(ctx, db, &entity.TeamMember{TeamId: id})
},
func(db *gorm.DB) error {
return p.tagTreeRelateApp.DeleteByCondWithDb(ctx, db, &entity.TagTreeRelate{RelateType: entity.TagRelateTypeTeam, RelateId: id})
},
)
return p.Tx(ctx, func(ctx context.Context) error {
return p.DeleteById(ctx, id)
}, func(ctx context.Context) error {
return p.teamMemberRepo.DeleteByCond(ctx, &entity.TeamMember{TeamId: id})
}, func(ctx context.Context) error {
return p.tagTreeRelateApp.DeleteByCond(ctx, &entity.TagTreeRelate{RelateType: entity.TagRelateTypeTeam, RelateId: id})
})
}
// --------------- 团队成员相关接口 ---------------

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/internal/tag/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
)
type tagTreeRepoImpl struct {
@@ -52,5 +51,5 @@ func (p *tagTreeRepoImpl) SelectByCondition(condition *entity.TagTreeQuery, toEn
sql = sql + ")"
}
sql = sql + " ORDER BY p.type, p.code_path"
gormx.GetListBySql2Model(sql, toEntity, params...)
p.SelectBySql(sql, toEntity, params...)
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/internal/tag/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
)
type tagTreeRelateRepoImpl struct {
@@ -33,7 +32,7 @@ WHERE
ORDER BY
t.code_path
`
if err := gormx.GetListBySql2Model(sql, &res, relateType, tagPaths); err != nil {
if err := tr.SelectBySql(sql, &res, relateType, tagPaths); err != nil {
return res, err
}
return res, nil
@@ -59,7 +58,7 @@ WHERE
ORDER BY
t.code_path
`
gormx.GetListBySql2Model(sql, &res, entity.TagRelateTypeTeam, accountId)
tr.SelectBySql(sql, &res, entity.TagRelateTypeTeam, accountId)
return res
}
@@ -81,6 +80,6 @@ WHERE
ORDER BY
t.code_path
`
gormx.GetListBySql2Model(sql, &res, relateId, relateType)
tr.SelectBySql(sql, &res, relateId, relateType)
return res
}

View File

@@ -4,7 +4,6 @@ import (
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/internal/tag/domain/repository"
"mayfly-go/pkg/base"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
)
@@ -17,8 +16,8 @@ func newTeamRepo() repository.Team {
}
func (p *teamRepoImpl) GetPageList(condition *entity.TeamQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(p.GetModel()).
qd := model.NewCond().
Like("name", condition.Name).
WithOrderBy()
return gormx.PageQuery(qd, pageParam, toEntity)
OrderBy(orderBy...)
return p.PageByCond(qd, pageParam, toEntity)
}

View File

@@ -17,22 +17,22 @@ func newTeamMemberRepo() repository.TeamMember {
}
func (p *teamMemberRepoImpl) ListMemeber(condition *entity.TeamMember, toEntity any, orderBy ...string) {
gormx.ListByOrder(condition, toEntity, orderBy...)
p.SelectByCond(model.NewModelCond(condition).OrderBy(orderBy...), toEntity)
}
func (p *teamMemberRepoImpl) GetPageList(condition *entity.TeamMember, pageParam *model.PageParam, toEntity any) (*model.PageResult[any], error) {
qd := gormx.NewQueryWithTableName("t_team_member t").
Select("t.*, a.name").
Joins("JOIN t_sys_account a ON t.account_id = a.id AND a.status = 1").
Eq("a.account_id", condition.AccountId).
Eq0("a.is_deleted", model.ModelUndeleted).
Eq("t.team_id", condition.TeamId).
Eq0("t.is_deleted", model.ModelUndeleted).
Like("a.username", condition.Username).
OrderByDesc("t.id")
WithCond(model.NewCond().Columns("t.*, a.name").
Eq("a.account_id", condition.AccountId).
Eq0("a.is_deleted", model.ModelUndeleted).
Eq("t.team_id", condition.TeamId).
Eq0("t.is_deleted", model.ModelUndeleted).
Like("a.username", condition.Username).
OrderByDesc("t.id"))
return gormx.PageQuery(qd, pageParam, toEntity)
}
func (p *teamMemberRepoImpl) IsExist(teamId, accountId uint64) bool {
return gormx.CountBy(&entity.TeamMember{TeamId: teamId, AccountId: accountId}) > 0
return p.CountByCond(&entity.TeamMember{TeamId: teamId, AccountId: accountId}) > 0
}

View File

@@ -6,7 +6,6 @@ import (
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"gorm.io/gorm"
)
@@ -14,90 +13,50 @@ import (
// 基础application接口
type App[T model.ModelI] interface {
// 新增一个实体
// Insert 新增一个实体
Insert(ctx context.Context, e T) error
// 使用指定gorm db执行主要用于事务执行
InsertWithDb(ctx context.Context, db *gorm.DB, e T) error
// 批量新增实体
// BatchInsert 批量新增实体
BatchInsert(ctx context.Context, models []T) error
// 使用指定gorm db执行主要用于事务执行
BatchInsertWithDb(ctx context.Context, db *gorm.DB, es []T) error
// 根据实体id更新实体信息
// UpdateById 根据实体id更新实体信息
UpdateById(ctx context.Context, e T) error
// 使用指定gorm db执行主要用于事务执行
UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T) error
// UpdateByCond 更新满足条件的数据
// @param cond 可为*model.QueryCond也可以为普通查询model
UpdateByCond(ctx context.Context, e T, cond any) error
// UpdateByWheres 更新满足wheres条件的数据
// @param wheres key => "age > ?" value => 10等
UpdateByWheres(ctx context.Context, e T, wheres collx.M, columns ...string) error
// UpdateByWheresWithDb 使用指定gorm.Db更新满足wheres条件的数据
// @param wheres key => "age > ?" value => 10等
UpdateByWheresWithDb(ctx context.Context, db *gorm.DB, e T, wheres collx.M, columns ...string) error
// 根据实体主键删除实体
// DeleteById 根据实体主键删除实体
DeleteById(ctx context.Context, id uint64) error
// 使用指定gorm db执行主要用于事务执行
DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id uint64) error
// DeleteByWheres 根据wheres条件进行删除
// @param wheres key -> "age > ?" value -> 10等
DeleteByWheres(ctx context.Context, wheres collx.M) error
// DeleteByWheresWithDb 使用指定gorm.Db根据wheres条件进行删除
// @param wheres key -> "age > ?" value -> 10等
DeleteByWheresWithDb(ctx context.Context, db *gorm.DB, wheres collx.M) error
// 根据实体条件更新参数udpateFields指定字段
Updates(ctx context.Context, cond any, udpateFields map[string]any) error
// 保存实体实体IsCreate返回true则新增否则更新
Save(ctx context.Context, e T) error
// 保存实体实体IsCreate返回true则新增否则更新。
// 使用指定gorm db执行主要用于事务执行
SaveWithDb(ctx context.Context, db *gorm.DB, e T) error
// 根据实体条件删除实体
// DeleteByCond 根据条件进行删除
DeleteByCond(ctx context.Context, cond any) error
// 使用指定gorm db执行主要用于事务执行
DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond any) error
// Updates 根据实体条件更新参数udpateFields指定字段
Updates(ctx context.Context, cond any, udpateFields map[string]any) error
// 根据实体id查询
// Save 保存实体实体IsCreate返回true则新增否则更新
Save(ctx context.Context, e T) error
// GetById 根据实体id查询
GetById(e T, id uint64, cols ...string) (T, error)
// GetByIdIn 根据实体id数组查询
GetByIdIn(list any, ids []uint64, orderBy ...string) error
// 根据实体条件查询实体信息
GetBy(condModel T, cols ...string) error
// GetByCond 根据实体条件查询实体信息(获取单个实体)
GetByCond(cond any) error
// 根据条件查询数据映射至listModels
ListByCond(cond any, listModels any, cols ...string) error
// ListByCond 根据条件查询数据映射至res
ListByCond(cond any, res any) error
// 根据wheres条件进行过滤
// @param wheres key -> "age > ?" value -> 10等
ListByWheres(wheres collx.M, listModels any, cols ...string) error
// PageByCond 分页查询
PageByCond(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error)
// PageQuery 分页查询
PageQuery(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error)
// 获取满足model中不为空的字段值条件的所有数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体
// @param cond 条件
ListByCondOrder(cond any, list any, order ...string) error
// 根据指定条件统计model表的数量, cond为条件可以为map等
// CountByCond 根据指定条件统计model表的数量
CountByCond(cond any) int64
// 执行事务操作
// Tx 执行事务操作
Tx(ctx context.Context, funcs ...func(context.Context) error) (err error)
}
@@ -116,37 +75,18 @@ func (ai *AppImpl[T, R]) Insert(ctx context.Context, e T) error {
return ai.GetRepo().Insert(ctx, e)
}
// 使用指定gorm db执行主要用于事务执行
func (ai *AppImpl[T, R]) InsertWithDb(ctx context.Context, db *gorm.DB, e T) error {
return ai.GetRepo().InsertWithDb(ctx, db, e)
}
// 批量新增实体 (单纯新增,不做其他业务逻辑处理)
func (ai *AppImpl[T, R]) BatchInsert(ctx context.Context, es []T) error {
return ai.GetRepo().BatchInsert(ctx, es)
}
// 使用指定gorm db执行主要用于事务执行
func (ai *AppImpl[T, R]) BatchInsertWithDb(ctx context.Context, db *gorm.DB, models []T) error {
return ai.GetRepo().BatchInsertWithDb(ctx, db, models)
}
// 根据实体id更新实体信息 (单纯更新,不做其他业务逻辑处理)
func (ai *AppImpl[T, R]) UpdateById(ctx context.Context, e T) error {
return ai.GetRepo().UpdateById(ctx, e)
}
// 使用指定gorm db执行主要用于事务执行
func (ai *AppImpl[T, R]) UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T) error {
return ai.GetRepo().UpdateByIdWithDb(ctx, db, e)
}
func (ai *AppImpl[T, R]) UpdateByWheres(ctx context.Context, e T, wheres collx.M, columns ...string) error {
return ai.GetRepo().UpdateByWheres(ctx, e, wheres, columns...)
}
func (ai *AppImpl[T, R]) UpdateByWheresWithDb(ctx context.Context, db *gorm.DB, e T, wheres collx.M, columns ...string) error {
return ai.GetRepo().UpdateByWheresWithDb(ctx, db, e, wheres, columns...)
func (ai *AppImpl[T, R]) UpdateByCond(ctx context.Context, e T, cond any) error {
return ai.GetRepo().UpdateByCond(ctx, e, cond)
}
// 根据实体条件更新参数udpateFields指定字段 (单纯更新,不做其他业务逻辑处理)
@@ -170,28 +110,11 @@ func (ai *AppImpl[T, R]) DeleteById(ctx context.Context, id uint64) error {
return ai.GetRepo().DeleteById(ctx, id)
}
func (ai *AppImpl[T, R]) DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id uint64) error {
return ai.GetRepo().DeleteByCondWithDb(ctx, db, id)
}
// 根据指定条件删除实体 (单纯删除实体,不做其他业务逻辑处理)
func (ai *AppImpl[T, R]) DeleteByCond(ctx context.Context, cond any) error {
return ai.GetRepo().DeleteByCond(ctx, cond)
}
// 使用指定gorm db执行主要用于事务执行
func (ai *AppImpl[T, R]) DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond any) error {
return ai.GetRepo().DeleteByCondWithDb(ctx, db, cond)
}
func (ai *AppImpl[T, R]) DeleteByWheres(ctx context.Context, wheres collx.M) error {
return ai.GetRepo().DeleteByWheres(ctx, wheres)
}
func (ai *AppImpl[T, R]) DeleteByWheresWithDb(ctx context.Context, db *gorm.DB, wheres collx.M) error {
return ai.GetRepo().DeleteByWheresWithDb(ctx, db, wheres)
}
// 根据实体id查询
func (ai *AppImpl[T, R]) GetById(e T, id uint64, cols ...string) (T, error) {
if err := ai.GetRepo().GetById(e, id, cols...); err != nil {
@@ -205,30 +128,17 @@ func (ai *AppImpl[T, R]) GetByIdIn(list any, ids []uint64, orderBy ...string) er
}
// 根据实体条件查询实体信息
func (ai *AppImpl[T, R]) GetBy(condModel T, cols ...string) error {
return ai.GetRepo().GetBy(condModel, cols...)
func (ai *AppImpl[T, R]) GetByCond(cond any) error {
return ai.GetRepo().GetByCond(cond)
}
// 根据条件查询数据映射至listModels
func (ai *AppImpl[T, R]) ListByCond(cond any, listModels any, cols ...string) error {
return ai.GetRepo().ListByCond(cond, listModels, cols...)
func (ai *AppImpl[T, R]) ListByCond(cond any, res any) error {
return ai.GetRepo().SelectByCond(cond, res)
}
func (ai *AppImpl[T, R]) ListByWheres(wheres collx.M, listModels any, cols ...string) error {
return ai.GetRepo().ListByWheres(wheres, listModels, cols...)
}
// PageQuery 分页查询
func (ai *AppImpl[T, R]) PageQuery(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error) {
return ai.GetRepo().PageQuery(cond, pageParam, toModels)
}
// 获取满足model中不为空的字段值条件的所有数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体
// @param cond 条件
func (ai *AppImpl[T, R]) ListByCondOrder(cond any, list any, order ...string) error {
return ai.GetRepo().ListByCondOrder(cond, list, order...)
// PageByCond 分页查询
func (ai *AppImpl[T, R]) PageByCond(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error) {
return ai.GetRepo().PageByCond(cond, pageParam, toModels)
}
// 根据指定条件统计model表的数量, cond为条件可以为map等

View File

@@ -5,7 +5,6 @@ import (
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"gorm.io/gorm"
)
@@ -34,13 +33,12 @@ type Repo[T model.ModelI] interface {
// 使用指定gorm db执行主要用于事务执行
UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T, columns ...string) error
// UpdateByWheres 更新满足wheres条件的数据
// @param wheres key => "age > ?" value => 10等
UpdateByWheres(ctx context.Context, e T, wheres collx.M, columns ...string) error
// UpdateByCond 更新满足条件的数据
// @param cond 条件
UpdateByCond(ctx context.Context, e T, cond any) error
// UpdateByWheresWithDb 使用指定gorm.Db更新满足wheres条件的数据
// @param wheres key => "age > ?" value => 10等
UpdateByWheresWithDb(ctx context.Context, db *gorm.DB, e T, wheres collx.M, columns ...string) error
// UpdateByCondWithDb 更新满足条件的数据
UpdateByCondWithDb(ctx context.Context, db *gorm.DB, e T, cond any) error
// 保存实体实体IsCreate返回true则新增否则更新
Save(ctx context.Context, e T) error
@@ -64,40 +62,25 @@ type Repo[T model.ModelI] interface {
// 使用指定gorm db执行主要用于事务执行
DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond any) error
// DeleteByWheres 根据wheres条件进行删除
// @param wheres key -> "age > ?" value -> 10等
DeleteByWheres(ctx context.Context, wheres collx.M) error
// DeleteByWheresWithDb 使用指定gorm.Db根据wheres条件进行删除
// @param wheres key -> "age > ?" value -> 10等
DeleteByWheresWithDb(ctx context.Context, db *gorm.DB, wheres collx.M) error
// 根据实体id查询
GetById(e T, id uint64, cols ...string) error
// 根据实体id数组查询对应实体列表并将响应结果映射至list
GetByIdIn(list any, ids []uint64, orderBy ...string) error
// 根据实体条件查询实体信息
GetBy(cond T, cols ...string) error
// GetByCond 根据实体条件查询实体信息(单个结果集)
GetByCond(cond any) error
// 根据实体条件查询数据映射至listModels
ListByCond(cond any, listModels any, cols ...string) error
// SelectByCond 根据实体条件查询数据映射至res
SelectByCond(cond any, res any) error
// 根据wheres条件进行过滤
// @param wheres key -> "age > ?" value -> 10等
ListByWheres(wheres collx.M, listModels any, cols ...string) error
// PageByCond 根据查询条件分页查询
PageByCond(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error)
// PageQuery 分页查询
PageQuery(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error)
// SelectBySql 根据sql语句查询数据
SelectBySql(sql string, res any, params ...any) error
// 获取满足model中不为空的字段值条件的所有数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体
// @param cond 条件
ListByCondOrder(cond any, list any, order ...string) error
// 根据指定条件统计model表的数量, cond为条件可以为map等
// 根据指定条件统计model表的数量
CountByCond(cond any) int64
}
@@ -147,22 +130,22 @@ func (br *RepoImpl[T]) UpdateByIdWithDb(ctx context.Context, db *gorm.DB, e T, c
return gormx.UpdateByIdWithDb(db, br.fillBaseInfo(ctx, e), columns...)
}
func (br *RepoImpl[T]) UpdateByWheres(ctx context.Context, e T, wheres collx.M, columns ...string) error {
func (br *RepoImpl[T]) UpdateByCond(ctx context.Context, e T, cond any) error {
if db := contextx.GetDb(ctx); db != nil {
return br.UpdateByWheresWithDb(ctx, db, e, wheres, columns...)
return br.UpdateByCondWithDb(ctx, db, e, cond)
}
e = br.fillBaseInfo(ctx, e)
// model的主键值需为空否则会带上主键条件
e.SetId(0)
return gormx.UpdateByWheres(e, wheres)
return gormx.UpdateByCond(e, toQueryCond(cond))
}
func (br *RepoImpl[T]) UpdateByWheresWithDb(ctx context.Context, db *gorm.DB, e T, wheres collx.M, columns ...string) error {
func (br *RepoImpl[T]) UpdateByCondWithDb(ctx context.Context, db *gorm.DB, e T, cond any) error {
e = br.fillBaseInfo(ctx, e)
// model的主键值需为空否则会带上主键条件
e.SetId(0)
return gormx.UpdateByWheresWithDb(db, br.fillBaseInfo(ctx, e), wheres, columns...)
return gormx.UpdateByCondWithDb(db, br.fillBaseInfo(ctx, e), toQueryCond(cond))
}
func (br *RepoImpl[T]) Updates(cond any, udpateFields map[string]any) error {
@@ -191,35 +174,18 @@ func (br *RepoImpl[T]) DeleteById(ctx context.Context, id uint64) error {
}
func (br *RepoImpl[T]) DeleteByIdWithDb(ctx context.Context, db *gorm.DB, id uint64) error {
return gormx.DeleteByCondWithDb(db, br.GetModel(), id)
return gormx.DeleteByIdWithDb(db, br.GetModel(), id)
}
func (br *RepoImpl[T]) DeleteByCond(ctx context.Context, cond any) error {
if db := contextx.GetDb(ctx); db != nil {
return br.DeleteByCondWithDb(ctx, db, cond)
}
return gormx.DeleteByCond(br.GetModel(), cond)
return gormx.DeleteByCond(br.GetModel(), toQueryCond(cond))
}
func (br *RepoImpl[T]) DeleteByCondWithDb(ctx context.Context, db *gorm.DB, cond any) error {
return gormx.DeleteByCondWithDb(db, br.GetModel(), cond)
}
func (br *RepoImpl[T]) DeleteByWheres(ctx context.Context, wheres collx.M) error {
if db := contextx.GetDb(ctx); db != nil {
return br.DeleteByWheresWithDb(ctx, db, wheres)
}
// model的主键值需为空否则会带上主键条件
e := br.GetModel()
e.SetId(0)
return gormx.DeleteByWheres(e, wheres)
}
func (br *RepoImpl[T]) DeleteByWheresWithDb(ctx context.Context, db *gorm.DB, wheres collx.M) error {
// model的主键值需为空否则会带上主键条件
e := br.GetModel()
e.SetId(0)
return gormx.DeleteByWheresWithDb(db, e, wheres)
return gormx.DeleteByCondWithDb(db, br.GetModel(), toQueryCond(cond))
}
func (br *RepoImpl[T]) GetById(e T, id uint64, cols ...string) error {
@@ -230,32 +196,27 @@ func (br *RepoImpl[T]) GetById(e T, id uint64, cols ...string) error {
}
func (br *RepoImpl[T]) GetByIdIn(list any, ids []uint64, orderBy ...string) error {
return gormx.GetByIdIn(br.GetModel(), list, ids, orderBy...)
return br.SelectByCond(model.NewCond().In(model.IdColumn, ids).OrderBy(orderBy...), list)
}
func (br *RepoImpl[T]) GetBy(cond T, cols ...string) error {
return gormx.GetBy(cond, cols...)
func (br *RepoImpl[T]) GetByCond(cond any) error {
return gormx.GetByCond(br.GetModel(), toQueryCond(cond))
}
func (br *RepoImpl[T]) ListByCond(cond any, listModels any, cols ...string) error {
return gormx.ListByCond(br.GetModel(), cond, listModels, cols...)
func (br *RepoImpl[T]) SelectByCond(cond any, res any) error {
return gormx.SelectByCond(br.GetModel(), toQueryCond(cond).Dest(res))
}
func (br *RepoImpl[T]) ListByWheres(wheres collx.M, listModels any, cols ...string) error {
return gormx.ListByWheres(br.GetModel(), wheres, listModels, cols...)
func (br *RepoImpl[T]) PageByCond(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error) {
return gormx.PageByCond(br.GetModel(), toQueryCond(cond), pageParam, toModels)
}
func (br *RepoImpl[T]) PageQuery(cond any, pageParam *model.PageParam, toModels any) (*model.PageResult[any], error) {
qd := gormx.NewQuery(br.GetModel()).WithCondModel(cond)
return gormx.PageQuery(qd, pageParam, toModels)
}
func (br *RepoImpl[T]) ListByCondOrder(cond any, list any, order ...string) error {
return gormx.ListByCondOrder(br.GetModel(), cond, list, order...)
func (br *RepoImpl[T]) SelectBySql(sql string, res any, params ...any) error {
return gormx.SelectBySql(sql, res, params...)
}
func (br *RepoImpl[T]) CountByCond(cond any) int64 {
return gormx.CountByCond(br.GetModel(), cond)
return gormx.CountByCond(br.GetModel(), toQueryCond(cond))
}
// GetModel 获取表的模型实例
@@ -269,3 +230,10 @@ func (br *RepoImpl[T]) fillBaseInfo(ctx context.Context, e T) T {
e.FillBaseInfo(model.IdGenTypeNone, contextx.GetLoginAccount(ctx))
return e
}
func toQueryCond(cond any) *model.QueryCond {
if qc, ok := cond.(*model.QueryCond); ok {
return qc
}
return model.NewModelCond(cond)
}

View File

@@ -4,7 +4,7 @@ import "fmt"
const (
AppName = "mayfly-go"
Version = "v1.8.1"
Version = "v1.8.2"
)
func GetAppInfo() string {

View File

@@ -4,9 +4,6 @@ import (
"fmt"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/anyx"
"mayfly-go/pkg/utils/collx"
"strings"
"time"
"gorm.io/gorm"
@@ -20,40 +17,29 @@ func UndeleteScope(db *gorm.DB) *gorm.DB {
// 根据id获取实体对象。model需为指针类型需要将查询出来的值赋值给model
//
// 若error不为nil则为不存在该记录
// @param model 数据库映射实体模型
func GetById(model any, id uint64, cols ...string) error {
return NewQuery(model).Eq("id", id).Undeleted().GenGdb().First(model).Error
}
// 根据id列表查询实体信息
// @param model 数据库映射实体模型
func GetByIdIn(model any, list any, ids []uint64, orderBy ...string) error {
return NewQuery(model).In("id", ids).Undeleted().GenGdb().Find(list).Error
// @param modelP 数据库映射实体模型
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
}
// 获取满足model中不为空的字段值条件的单个对象。model需为指针类型需要将查询出来的值赋值给model
//
// 若 error不为nil则为不存在该记录
// @param model 数据库映射实体模型
func GetBy(model any, cols ...string) error {
return global.Db.Select(cols).Where(model).Scopes(UndeleteScope).First(model).Error
}
// 根据model指定条件统计数量
func CountBy(model any) int64 {
return CountByCond(model, model)
// @param cond 模型条件
func GetByCond(dbModel any, cond *model.QueryCond) error {
return NewQuery(dbModel, cond).GenGdb().Scopes(UndeleteScope).First(cond.GetDest()).Error
}
// 根据条件cond获取指定model表统计数量
func CountByCond(model any, cond any) int64 {
func CountByCond(dbModel any, cond *model.QueryCond) int64 {
var count int64
NewQuery(model).WithCondModel(cond).Undeleted().GenGdb().Count(&count)
NewQuery(dbModel, cond).GenGdb().Scopes(UndeleteScope).Count(&count)
return count
}
// 根据查询条件分页查询数据
// 若未指定查询列则查询列以toModels字段为准
func PageQuery[T any](q *QueryCond, 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()
gdb := q.GenGdb()
var count int64
@@ -74,64 +60,19 @@ func PageQuery[T any](q *QueryCond, pageParam *model.PageParam, toModels T) (*mo
return &model.PageResult[T]{Total: count, List: toModels}, nil
}
// 根据查询条件查询列表信息
func ListByQueryCond(q *QueryCond, list any) error {
q.Undeleted()
gdb := q.GenGdb()
return gdb.Find(list).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)
}
// 获取满足model中不为空的字段值条件的所有数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体即只包含需要返回的字段结构体
func ListBy(model any, list any, cols ...string) error {
return ListByCond(model, model, list, cols...)
// SelectByCond 根据条件查询结果集
func SelectByCond(dbModel any, cond *model.QueryCond) error {
return NewQuery(dbModel, cond).GenGdb().Scopes(UndeleteScope).Find(cond.GetDest()).Error
}
// 获取满足cond中不为空的字段值条件的所有model表数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体即只包含需要返回的字段结构体
func ListByCond(model any, cond any, list any, cols ...string) error {
return global.Db.Model(model).Select(cols).Where(cond).Scopes(UndeleteScope).Order("id desc").Find(list).Error
}
// 获取满足cond中不为空的字段值条件的所有model表数据.
//
// @param wheres key -> "age > ?" value -> 10等
func ListByWheres(model any, wheres collx.M, list any, cols ...string) error {
gdb := global.Db.Model(model).Select(cols)
for k, v := range wheres {
if !anyx.IsBlank(v) {
gdb.Where(k, v)
}
}
return gdb.Scopes(UndeleteScope).Order("id desc").Find(list).Error
}
// 获取满足model中不为空的字段值条件的所有数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体
// @param model 数据库映射实体模型
func ListByOrder(model any, list any, order ...string) error {
return ListByCondOrder(model, model, list, order...)
}
// 获取满足cond中不为空的字段值条件的所有model表数据.
//
// @param list为数组类型 如 var users *[]User可指定为非model结构体
// @param model 数据库映射实体模型
func ListByCondOrder(model any, cond any, list any, order ...string) error {
var orderByStr string
if order == nil {
orderByStr = "id desc"
} else {
orderByStr = strings.Join(order, ",")
}
return global.Db.Model(model).Where(cond).Scopes(UndeleteScope).Order(orderByStr).Find(list).Error
}
func GetListBySql2Model(sql string, toEntity any, params ...any) error {
return global.Db.Raw(sql, params...).Find(toEntity).Error
// SelectBySql 根据sql查询数据
func SelectBySql(sql string, toEntity any, params ...any) error {
return global.Db.Raw(sql, params...).Scan(toEntity).Error
}
func ExecSql(sql string, params ...any) error {
@@ -169,21 +110,15 @@ func UpdateByIdWithDb(db *gorm.DB, model any, columns ...string) error {
return db.Model(model).Select(columns).Updates(model).Error
}
// UpdateByWheres 更新满足wheres条件的数据(model的主键值需为空否则会带上主键条件)
// @param wheres key -> "age > ?" value -> 10等
func UpdateByWheres(model_ any, wheres collx.M) error {
return UpdateByWheresWithDb(global.Db, model_, wheres)
// UpdateByCondWithDb 使用指定gorm.DB更新满足条件的数据(model的主键值需为空否则会带上主键条件)
func UpdateByCond(dbModel any, cond *model.QueryCond) error {
return UpdateByCondWithDb(global.Db, dbModel, cond)
}
// UpdateByWheresWithDb 使用指定gorm.DB更新满足wheres条件的数据(model的主键值需为空否则会带上主键条件)
// @param wheres key -> "age > ?" value -> 10等
func UpdateByWheresWithDb(db *gorm.DB, model any, wheres collx.M, columns ...string) error {
gormDb := db.Model(model).Select(columns)
for k, v := range wheres {
if !anyx.IsBlank(v) {
gormDb.Where(k, v)
}
}
// UpdateByCondWithDb 使用指定gorm.DB更新满足条件的数据(model的主键值需为空否则会带上主键条件)
func UpdateByCondWithDb(db *gorm.DB, model any, cond *model.QueryCond) error {
gormDb := db.Model(model).Select(cond.GetSelectColumns())
setGdbWhere(gormDb, cond)
return gormDb.Updates(model).Error
}
@@ -203,50 +138,20 @@ func DeleteByIdWithDb(db *gorm.DB, model_ any, id uint64) error {
return db.Model(model_).Where("id = ?", id).Updates(getDeleteColumnValue()).Error
}
// 根据model条件删除
// @param model 数据库映射实体模型
func DeleteBy(model_ any) error {
return DeleteByCond(model_, model_)
}
// 根据cond条件删除指定model表数据
//
// @param model_ 数据库映射实体模型
// @param dbModel 数据库映射实体模型
// @param cond 条件
func DeleteByCond(model_ any, cond any) error {
return DeleteByCondWithDb(global.Db, model_, cond)
}
// 根据model条件删除
// @param model 数据库映射实体模型
func DeleteByWithDb(db *gorm.DB, model_ any) error {
return DeleteByCondWithDb(db, model_, model_)
}
// DeleteByWheres 使用指定wheres删除(model的主键值需为空否则会带上主键条件)
// @param wheres key -> "age > ?" value -> 10等
func DeleteByWheres(model_ any, wheres collx.M) error {
return DeleteByWheresWithDb(global.Db, model_, wheres)
}
// DeleteByWheresWithDb 使用指定gorm.Db根据wheres条件进行删除(model的主键值需为空否则会带上主键条件)
// @param wheres key -> "age > ?" value -> 10等
func DeleteByWheresWithDb(db *gorm.DB, model_ any, wheres collx.M) error {
gormDb := db.Model(model_)
for k, v := range wheres {
if !anyx.IsBlank(v) {
gormDb.Where(k, v)
}
}
return gormDb.Updates(getDeleteColumnValue()).Error
func DeleteByCond(dbModel any, cond *model.QueryCond) error {
return DeleteByCondWithDb(global.Db, dbModel, cond)
}
// 根据cond条件删除指定model表数据
//
// @param model 数据库映射实体模型
// @param dbModel 数据库映射实体模型
// @param cond 条件
func DeleteByCondWithDb(db *gorm.DB, model_ any, cond any) error {
return db.Model(model_).Where(cond).Updates(getDeleteColumnValue()).Error
func DeleteByCondWithDb(db *gorm.DB, dbModel any, cond *model.QueryCond) error {
return setGdbWhere(db.Model(dbModel), cond).Updates(getDeleteColumnValue()).Error
}
func getDeleteColumnValue() map[string]any {

View File

@@ -1,80 +1,55 @@
package gormx
import (
"fmt"
"mayfly-go/pkg/consts"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/anyx"
"strings"
"gorm.io/gorm"
)
type QueryCond struct {
dbModel any // 数据库模型
table string
selectColumns string // 查询的列信息
joins string // join 类似 left join emails on emails.user_id = users.id
condModel any // 条件模型
columns []string // 查询的所有列与values一一对应
values []any // 查询列对应的值
orderBy []string
type Query struct {
dbModel any // 数据库模型
table string
joins string // join 类似 left join emails on emails.user_id = users.id
cond *model.QueryCond // 条件
}
// NewQuery 构建查询条件
func NewQuery(dbModel any) *QueryCond {
return &QueryCond{dbModel: dbModel}
func NewQuery(dbModel any, cond *model.QueryCond) *Query {
return &Query{dbModel: dbModel, cond: cond}
}
func NewQueryWithTableName(tableName string) *QueryCond {
return &QueryCond{table: tableName}
func NewQueryWithTableName(tableName string) *Query {
return &Query{table: tableName}
}
func (q *QueryCond) WithCondModel(condModel any) *QueryCond {
q.condModel = condModel
func (q *Query) WithCond(cond *model.QueryCond) *Query {
q.cond = cond
return q
}
func (q *QueryCond) WithOrderBy(orderBy ...string) *QueryCond {
q.orderBy = append(q.orderBy, orderBy...)
return q
}
func (q *QueryCond) Select(columns ...string) *QueryCond {
q.selectColumns = strings.Join(columns, ",")
return q
}
func (q *QueryCond) Joins(joins string) *QueryCond {
func (q *Query) Joins(joins string) *Query {
q.joins = joins
return q
}
func (q *QueryCond) OrderByDesc(column string) *QueryCond {
q.orderBy = append(q.orderBy, fmt.Sprintf("%s DESC", column))
return q
}
func (q *QueryCond) OrderByAsc(column string) *QueryCond {
q.orderBy = append(q.orderBy, fmt.Sprintf("%s ASC", column))
return q
}
// 添加未删除数据过滤条件(适用于单表用实体查询)
func (q *QueryCond) Undeleted() *QueryCond {
func (q *Query) Undeleted() *Query {
// 存在表名,则可能为关联查询等,需要自行设置未删除条件过滤
if q.table != "" {
return q
}
return q.Eq0(model.DeletedColumn, model.ModelUndeleted)
q.cond.Eq0(model.DeletedColumn, model.ModelUndeleted)
return q
}
func (q *QueryCond) GenGdb() *gorm.DB {
func (q *Query) GenGdb() *gorm.DB {
return q.GenGdbWithDb(global.Db)
}
func (q *QueryCond) GenGdbWithDb(db *gorm.DB) *gorm.DB {
func (q *Query) GenGdbWithDb(db *gorm.DB) *gorm.DB {
var gdb *gorm.DB
if q.table != "" {
gdb = db.Table(q.table)
@@ -82,20 +57,18 @@ func (q *QueryCond) GenGdbWithDb(db *gorm.DB) *gorm.DB {
gdb = db.Model(q.dbModel)
}
if q.selectColumns != "" {
gdb.Select(q.selectColumns)
cond := q.cond
if len(cond.GetSelectColumns()) > 0 {
gdb.Select(cond.GetSelectColumns())
}
if q.joins != "" {
gdb.Joins(q.joins)
}
if q.condModel != nil {
gdb.Where(q.condModel)
}
for i, v := range q.columns {
gdb.Where(v, q.values[i])
}
if len(q.orderBy) > 0 {
gdb.Order(strings.Join(q.orderBy, ","))
setGdbWhere(gdb, cond)
if len(cond.GetOrderBy()) > 0 {
gdb.Order(strings.Join(cond.GetOrderBy(), ","))
} else {
gdb.Order("id desc")
}
@@ -103,85 +76,13 @@ func (q *QueryCond) GenGdbWithDb(db *gorm.DB) *gorm.DB {
return gdb
}
// Eq 等于 =
func (q *QueryCond) Eq(column string, val any) *QueryCond {
return q.Cond(consts.Eq, column, val, true)
}
// Eq 等于 = (零值也不忽略该添加)
func (q *QueryCond) Eq0(column string, val any) *QueryCond {
return q.Cond(consts.Eq, column, val, false)
}
func (q *QueryCond) Like(column string, val string) *QueryCond {
if val == "" {
return q
func setGdbWhere(gdb *gorm.DB, cond *model.QueryCond) *gorm.DB {
if cond.GetCondModel() != nil {
gdb.Where(cond.GetCondModel())
}
return q.Cond(consts.Like, column, "%"+val+"%", false)
}
func (q *QueryCond) RLike(column string, val string) *QueryCond {
if val == "" {
return q
for i, v := range cond.GetWheres() {
gdb.Where(i, v)
}
return q.Cond(consts.Like, column, val+"%", false)
}
func (q *QueryCond) In(column string, val any) *QueryCond {
return q.Cond(consts.In, column, val, true)
}
func (q *QueryCond) NotIn(column string, val any) *QueryCond {
return q.Cond(consts.NotIn, column, val, true)
}
func (q *QueryCond) In0(column string, val any) *QueryCond {
return q.Cond(consts.In, column, val, true)
}
// // Ne 不等于 !=
func (q *QueryCond) Ne(column string, val any) *QueryCond {
q.Cond(consts.Ne, column, val, true)
return q
}
// Gt 大于 >
func (q *QueryCond) Gt(column string, val any) *QueryCond {
q.Cond(consts.Gt, column, val, true)
return q
}
// Ge 大于等于 >=
func (q *QueryCond) Ge(column string, val any) *QueryCond {
q.Cond(consts.Ge, column, val, true)
return q
}
// Lt 小于 <
func (q *QueryCond) Lt(column string, val any) *QueryCond {
q.Cond(consts.Lt, column, val, true)
return q
}
// Le 小于等于 <=
func (q *QueryCond) Le(column string, val any) *QueryCond {
q.Cond(consts.Le, column, val, true)
return q
}
// And条件
func (q *QueryCond) And(column string, val any) *QueryCond {
q.columns = append(q.columns, column)
q.values = append(q.values, val)
return q
}
func (q *QueryCond) Cond(cond, column string, val any, skipBlank bool) *QueryCond {
// 零值跳过
if skipBlank && anyx.IsBlank(val) {
return q
}
q.columns = append(q.columns, fmt.Sprintf("%s %s ?", column, cond))
q.values = append(q.values, val)
return q
return gdb
}

View File

@@ -92,11 +92,8 @@ func (m *CreateModel) FillBaseInfo(idGenType IdGenType, account *LoginAccount) {
// 基础实体模型,数据表最基础字段,尽量每张表都包含这些字段
type Model struct {
DeletedModel
CreateModel
CreateTime *time.Time `json:"createTime"`
CreatorId uint64 `json:"creatorId"`
Creator string `json:"creator"`
UpdateTime *time.Time `json:"updateTime"`
ModifierId uint64 `json:"modifierId"`
Modifier string `json:"modifier"`

View File

@@ -0,0 +1,166 @@
package model
import (
"fmt"
"mayfly-go/pkg/consts"
"mayfly-go/pkg/utils/anyx"
"mayfly-go/pkg/utils/collx"
)
type QueryCond struct {
selectColumns []string // 查询的列信息
condModel any // 条件模型
wheres collx.M
orderBy []string
dest any // 结果集指针
}
// NewCond 构建查询条件
func NewCond() *QueryCond {
return &QueryCond{}
}
// NewModelCond 新建模型条件(使用模型中非零值作为条件)
func NewModelCond(condModel any) *QueryCond {
return &QueryCond{condModel: condModel}
}
// 设置结果集绑定的指针
func (q *QueryCond) Dest(dest any) *QueryCond {
q.dest = dest
return q
}
// Columns 设置查询的列
func (q *QueryCond) Columns(columns ...string) *QueryCond {
q.selectColumns = columns
return q
}
func (q *QueryCond) OrderByDesc(column string) *QueryCond {
return q.OrderBy(fmt.Sprintf("%s DESC", column))
}
func (q *QueryCond) OrderByAsc(column string) *QueryCond {
return q.OrderBy(fmt.Sprintf("%s ASC", column))
}
func (q *QueryCond) OrderBy(orderBy ...string) *QueryCond {
q.orderBy = append(q.orderBy, orderBy...)
return q
}
// Eq 等于 =
func (q *QueryCond) Eq(column string, val any) *QueryCond {
return q.Cond(consts.Eq, column, val, true)
}
// Eq 等于 = (零值也不忽略该添加)
func (q *QueryCond) Eq0(column string, val any) *QueryCond {
return q.Cond(consts.Eq, column, val, false)
}
// Like LIKE %xx%
func (q *QueryCond) Like(column string, val string) *QueryCond {
if val == "" {
return q
}
return q.Cond(consts.Like, column, "%"+val+"%", false)
}
// RLike LIKE xx%
func (q *QueryCond) RLike(column string, val string) *QueryCond {
if val == "" {
return q
}
return q.Cond(consts.Like, column, val+"%", false)
}
func (q *QueryCond) In(column string, val any) *QueryCond {
return q.Cond(consts.In, column, val, true)
}
func (q *QueryCond) NotIn(column string, val any) *QueryCond {
return q.Cond(consts.NotIn, column, val, true)
}
func (q *QueryCond) In0(column string, val any) *QueryCond {
return q.Cond(consts.In, column, val, true)
}
// // Ne 不等于 !=
func (q *QueryCond) Ne(column string, val any) *QueryCond {
q.Cond(consts.Ne, column, val, true)
return q
}
// Gt 大于 >
func (q *QueryCond) Gt(column string, val any) *QueryCond {
q.Cond(consts.Gt, column, val, true)
return q
}
// Ge 大于等于 >=
func (q *QueryCond) Ge(column string, val any) *QueryCond {
q.Cond(consts.Ge, column, val, true)
return q
}
// Lt 小于 <
func (q *QueryCond) Lt(column string, val any) *QueryCond {
q.Cond(consts.Lt, column, val, true)
return q
}
// Le 小于等于 <=
func (q *QueryCond) Le(column string, val any) *QueryCond {
q.Cond(consts.Le, column, val, true)
return q
}
// And条件
func (q *QueryCond) And(column string, val any) *QueryCond {
if q.wheres == nil {
q.wheres = collx.M{}
}
q.wheres[column] = val
return q
}
func (q *QueryCond) Cond(cond, column string, val any, skipBlank bool) *QueryCond {
// 零值跳过
if skipBlank && anyx.IsBlank(val) {
return q
}
return q.And(fmt.Sprintf("%s %s ?", column, cond), val)
}
func (q *QueryCond) GetWheres() collx.M {
return q.wheres
}
func (q *QueryCond) GetCondModel() any {
return q.condModel
}
func (q *QueryCond) GetSelectColumns() []string {
return q.selectColumns
}
func (q *QueryCond) GetOrderBy() []string {
return q.orderBy
}
// 获取输出目标结果集指针若dest为空则使用condModel
func (q *QueryCond) GetDest() any {
if !anyx.IsBlank(q.dest) {
return q.dest
}
if !anyx.IsBlank(q.condModel) {
return q.condModel
}
panic("*model.QueryCond dest and condModel is nil")
}