6 Commits

Author SHA1 Message Date
meilin.huang
1c18a01bf6 feat: 新增pgsql数据操作&redis集群操作 2022-07-10 12:14:06 +08:00
meilin.huang
729a3d7028 feat: 新增linux文件夹创建&删除&其他优化 2022-07-04 20:21:24 +08:00
meilin.huang
b88923a128 feat: 数据库表数据支持分页查看 2022-07-02 18:59:46 +08:00
meilin.huang
fe8cd93c78 feat: 新增数据库导出功能&其他小优化 2022-06-30 16:42:25 +08:00
meilin.huang
64b49dae2e fix: 功能优化&小问题修复 2022-06-25 19:52:11 +08:00
meilin.huang
edbbbca5f9 fix: sql脚本导入参数修复 2022-06-21 17:54:07 +08:00
46 changed files with 1191 additions and 496 deletions

View File

@@ -1,7 +1,7 @@
# 🌈mayfly-go
### 介绍
简单基于DDD(领域驱动设计)分层架构实现的web版 **linux、数据库mysql、redis、mongo统一管理操作平台**
简单基于DDD(领域驱动设计)分层架构实现的web版 **linux、数据库mysql postgres、redis(单机 集群)、mongo统一管理操作平台**
### 开发语言与主要框架

View File

@@ -7,25 +7,25 @@
"lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
},
"dependencies": {
"@element-plus/icons-vue": "^2.0.4",
"@element-plus/icons-vue": "^2.0.6",
"axios": "^0.27.2",
"codemirror": "^5.65.5",
"countup.js": "^2.0.7",
"cropperjs": "^1.5.11",
"echarts": "^5.3.2",
"element-plus": "^2.2.4",
"jsoneditor": "^9.8.0",
"echarts": "^5.3.3",
"element-plus": "^2.2.9",
"jsoneditor": "^9.9.0",
"lodash": "^4.17.21",
"mitt": "^3.0.0",
"nprogress": "^0.2.0",
"screenfull": "^5.1.0",
"sortablejs": "^1.13.0",
"sql-formatter": "^6.1.2",
"sql-formatter": "^7.0.3",
"vue": "^3.2.37",
"vue-clipboard3": "^1.0.1",
"vue-router": "^4.0.15",
"vue-router": "^4.0.16",
"vuex": "^4.0.2",
"xterm": "^4.18.0",
"xterm": "^4.19.0",
"xterm-addon-fit": "^0.5.0"
},
"devDependencies": {
@@ -43,8 +43,8 @@
"prettier": "^2.3.0",
"sass": "^1.45.1",
"sass-loader": "^12.4.0",
"typescript": "^4.2.4",
"vite": "^2.9.10",
"typescript": "^4.7.4",
"vite": "^2.9.13",
"vue-eslint-parser": "^8.0.1"
},
"browserslist": [

View File

@@ -239,16 +239,6 @@
color: set-color(primary);
}
/* Switch 开关
------------------------------- */
.el-switch.is-checked .el-switch__core {
border-color: set-color(primary);
background-color: set-color(primary);
}
.el-switch__label.is-active {
color: set-color(primary);
}
/* Slider 滑块
------------------------------- */
.el-slider__bar {

View File

@@ -30,7 +30,7 @@ import { useStore } from '@/store/index.ts';
export default defineComponent({
name: 'layoutBreadcrumbSearch',
setup() {
const layoutMenuAutocompleteRef = ref();
const layoutMenuAutocompleteRef: any = ref(null);
const store = useStore();
const router = useRouter();
const state: any = reactive({
@@ -44,7 +44,9 @@ export default defineComponent({
state.isShowSearch = true;
initTageView();
nextTick(() => {
layoutMenuAutocompleteRef.value.focus();
setTimeout(() => {
layoutMenuAutocompleteRef.value.focus();
});
});
};
// 搜索弹窗关闭
@@ -68,7 +70,6 @@ export default defineComponent({
// 初始化菜单数据
const initTageView = () => {
if (state.tagsViewList.length > 0) return false;
console.log(getRoutes(store.state.routesList.routesList));
getRoutes(store.state.routesList.routesList).map((v: any) => {
if (!v.meta.isHide) {
state.tagsViewList.push({ ...v });

View File

@@ -1,7 +1,7 @@
<template>
<div>
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :close-on-click-modal="false" :destroy-on-close="true" width="35%">
<el-form :model="form" ref="dbForm" :rules="rules" label-width="85px">
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :close-on-click-modal="false" :destroy-on-close="true" width="38%">
<el-form :model="form" ref="dbForm" :rules="rules" label-width="95px">
<el-form-item prop="projectId" label="项目:" required>
<el-select style="width: 100%" v-model="form.projectId" placeholder="请选择项目" @change="changeProject" filterable>
<el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
@@ -19,6 +19,7 @@
<el-form-item prop="type" label="类型:" required>
<el-select style="width: 100%" v-model="form.type" placeholder="请选择数据库类型">
<el-option key="item.id" label="mysql" value="mysql"> </el-option>
<el-option key="item.id" label="postgres" value="postgres"> </el-option>
</el-select>
</el-form-item>
<el-form-item prop="host" label="host:" required>
@@ -39,6 +40,9 @@
autocomplete="new-password"
></el-input>
</el-form-item>
<el-form-item prop="params" label="连接参数:">
<el-input v-model="form.params" placeholder="其他连接参数,形如: key1=value1&key2=value2"></el-input>
</el-form-item>
<el-form-item prop="database" label="数据库名:" required>
<el-tag
v-for="db in databaseList"
@@ -116,6 +120,7 @@ export default defineComponent({
port: 3306,
username: null,
password: null,
params: null,
database: '',
project: null,
projectId: null,
@@ -173,13 +178,6 @@ export default defineComponent({
trigger: ['change', 'blur'],
},
],
// password: [
// {
// required: true,
// message: '请输入密码',
// trigger: ['change', 'blur'],
// },
// ],
database: [
{
required: true,

View File

@@ -20,15 +20,15 @@
</el-radio>
</template>
</el-table-column>
<el-table-column prop="project" label="项目" min-width="100"></el-table-column>
<el-table-column prop="project" label="项目" min-width="100" show-overflow-tooltip></el-table-column>
<el-table-column prop="env" label="环境" min-width="100"></el-table-column>
<el-table-column prop="name" label="名称" min-width="200"></el-table-column>
<el-table-column min-width="160" label="host:port">
<el-table-column prop="name" label="名称" min-width="160" show-overflow-tooltip></el-table-column>
<el-table-column min-width="170" label="host:port" show-overflow-tooltip>
<template #default="scope">
{{ `${scope.row.host}:${scope.row.port}` }}
</template>
</el-table-column>
<el-table-column prop="type" label="类型" min-width="80"></el-table-column>
<el-table-column prop="type" label="类型" min-width="90"></el-table-column>
<el-table-column prop="database" label="数据库" min-width="160">
<template #default="scope">
<el-tag
@@ -72,9 +72,35 @@
<el-dialog width="75%" :title="`${db} 表信息`" :before-close="closeTableInfo" v-model="tableInfoDialog.visible">
<el-row class="mb10">
<el-popover v-model:visible="showDumpInfo" :width="470" placement="right">
<template #reference>
<el-button class="ml5" type="success" size="small" @click="showDumpInfo = !showDumpInfo">导出</el-button>
</template>
<el-form-item label="导出内容: ">
<el-radio-group v-model="dumpInfo.type">
<el-radio :label="1" size="small">结构</el-radio>
<el-radio :label="2" size="small">数据</el-radio>
<el-radio :label="3" size="small">结构数据</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="导出表: ">
<el-table @selection-change="handleDumpTableSelectionChange" max-height="300" size="small" :data="tableInfoDialog.infos">
<el-table-column type="selection" width="45" />
<el-table-column property="tableName" label="表名" min-width="150" show-overflow-tooltip> </el-table-column>
<el-table-column property="tableComment" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
</el-table>
</el-form-item>
<div style="text-align: right">
<el-button @click="showDumpInfo = false" size="small">取消</el-button>
<el-button @click="dump(db)" type="success" size="small">确定</el-button>
</div>
</el-popover>
<el-button type="primary" size="small" @click="tableCreateDialog.visible = true">创建表</el-button>
</el-row>
<el-table border stripe :data="tableInfoDialog.infos" size="small">
<el-table v-loading="tableInfoDialog.loading" border stripe :data="tableInfoDialog.infos" size="small">
<el-table-column property="tableName" label="表名" min-width="150" show-overflow-tooltip></el-table-column>
<el-table-column property="tableComment" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
<el-table-column
@@ -198,6 +224,7 @@
<el-table-column prop="columnName" label="列名" show-overflow-tooltip> </el-table-column>
<el-table-column prop="seqInIndex" label="列序列号" show-overflow-tooltip> </el-table-column>
<el-table-column prop="indexType" label="类型"> </el-table-column>
<el-table-column prop="indexComment" label="备注" min-width="230" show-overflow-tooltip> </el-table-column>
</el-table>
</el-dialog>
@@ -226,6 +253,10 @@ import { dbApi } from './api';
import enums from './enums';
import { projectApi } from '../project/api.ts';
import SqlExecBox from './component/SqlExecBox.ts';
import config from '@/common/config';
import { getSession } from '@/common/utils/storage';
import { isTrue } from '@/common/assert';
export default defineComponent({
name: 'DbList',
components: {
@@ -255,6 +286,13 @@ export default defineComponent({
},
datas: [],
total: 0,
showDumpInfo: false,
dumpInfo: {
id: 0,
db: '',
type: 3,
tables: [],
},
// sql执行记录弹框
sqlExecLogDialog: {
title: '',
@@ -276,6 +314,7 @@ export default defineComponent({
},
chooseTableName: '',
tableInfoDialog: {
loading: false,
visible: false,
infos: [],
},
@@ -303,7 +342,7 @@ export default defineComponent({
onMounted(async () => {
search();
state.projects = (await projectApi.projects.request({ pageNum: 1, pageSize: 100 })).list;
state.projects = await projectApi.accountProjects.request(null);
});
const choose = (item: any) => {
@@ -391,6 +430,29 @@ export default defineComponent({
searchSqlExecLog();
};
/**
* 选择导出数据库表
*/
const handleDumpTableSelectionChange = (vals: any) => {
state.dumpInfo.tables = vals.map((x: any) => x.tableName);
};
/**
* 数据库信息导出
*/
const dump = (db: string) => {
isTrue(state.dumpInfo.tables.length > 0, '请选择要导出的表');
const a = document.createElement('a');
a.setAttribute(
'href',
`${config.baseApiUrl}/dbs/${state.dbId}/dump?db=${db}&type=${state.dumpInfo.type}&tables=${state.dumpInfo.tables.join(
','
)}&token=${getSession('token')}`
);
a.click();
state.showDumpInfo = false;
};
const onShowRollbackSql = async (sqlExecLog: any) => {
const columns = await dbApi.columnMetadata.request({ id: sqlExecLog.dbId, db: sqlExecLog.db, tableName: sqlExecLog.table });
const primaryKey = columns[0].columnName;
@@ -434,13 +496,19 @@ export default defineComponent({
};
const showTableInfo = async (row: any, db: string) => {
state.tableInfoDialog.infos = await dbApi.tableInfos.request({ id: row.id, db });
state.dbId = row.id;
state.db = db;
state.tableInfoDialog.loading = true;
state.tableInfoDialog.visible = true;
try {
state.tableInfoDialog.infos = await dbApi.tableInfos.request({ id: row.id, db });
state.dbId = row.id;
state.db = db;
} finally {
state.tableInfoDialog.loading = false;
}
};
const closeTableInfo = () => {
state.showDumpInfo = false;
state.tableInfoDialog.visible = false;
state.tableInfoDialog.infos = [];
};
@@ -510,6 +578,8 @@ export default defineComponent({
valChange,
deleteDb,
onShowSqlExec,
handleDumpTableSelectionChange,
dump,
onBeforeCloseSqlExecDialog,
handleSqlExecPageChange,
searchSqlExecLog,

View File

@@ -190,7 +190,7 @@
@cell-dblclick="cellClick"
@sort-change="onTableSortChange"
@selection-change="onDataSelectionChange"
:data="dt.execRes.data"
:data="dt.datas"
size="small"
:max-height="dataTabsTableHeight"
v-loading="dt.loading"
@@ -200,12 +200,12 @@
border
class="mt5"
>
<el-table-column v-if="dt.execRes.tableColumn.length > 0" type="selection" width="35" />
<el-table-column v-if="dt.datas.length > 0" type="selection" width="35" />
<el-table-column
min-width="100"
:width="flexColumnWidth(item, dt.execRes.data)"
:width="flexColumnWidth(item, dt.datas)"
align="center"
v-for="item in dt.execRes.tableColumn"
v-for="item in dt.columnNames"
:key="item"
:prop="item"
:label="item"
@@ -215,12 +215,21 @@
<template #header>
<el-tooltip raw-content placement="top" effect="customized">
<template #content> {{ getColumnTip(dt.name, item) }} </template>
<!-- <el-icon><question-filled /></el-icon> -->
{{ item }}
</el-tooltip>
</template>
</el-table-column>
</el-table>
<el-row type="flex" class="mt5" justify="center">
<el-pagination
small
:total="dt.count"
@current-change="handlePageChange(dt)"
layout="prev, pager, next, total, jumper"
v-model:current-page="dt.pageNum"
:page-size="defalutLimit"
></el-pagination>
</el-row>
</el-tab-pane>
</el-tabs>
</el-container>
@@ -263,15 +272,15 @@ export default defineComponent({
const state = reactive({
token: token,
defalutLimit: 25, // 默认查询数量
defalutLimit: 20, // 默认查询数量
dbs: [], // 数据库实例列表
databaseList: [], // 数据库实例拥有的数据库列表1数据库实例 -> 多数据库
db: '', // 当前操作的数据库
dbType: '',
tables: [],
dbId: null, // 当前选中操作的数据库实例
tableName: '',
tableMetadata: [],
columnMetadata: [],
sqlName: '', // 当前sql模板名
sqlNames: [], // 所有sql模板名
activeName: 'Query',
@@ -356,7 +365,7 @@ export default defineComponent({
const setHeight = () => {
// 默认300px
codemirror.setSize('auto', `${window.innerHeight - 538}px`);
state.dataTabsTableHeight = window.innerHeight - 258;
state.dataTabsTableHeight = window.innerHeight - 258 - 33;
};
/**
@@ -457,33 +466,6 @@ export default defineComponent({
sql: sql.trim(),
remark,
});
// const sqlTrim = sql.trim();
// let remark = '';
// let canRun = true;
// const needRemark = ['update', 'UPDATE', 'delete', 'DELETE', 'INSERT', 'insert'].indexOf(sqlTrim.split(' ')[0]);
// if (needRemark) {
// const res: any = await ElMessageBox.prompt('请输入备注', 'Tip', {
// confirmButtonText: '确定',
// cancelButtonText: '取消',
// });
// remark = res.value;
// if (!remark) {
// canRun = false;
// }
// }
// if (!canRun) {
// return;
// }
// try {
// state.queryTab.loading = true;
// return await dbApi.sqlExec.request({
// id: state.dbId,
// db: state.db,
// sql: sqlTrim,
// remark,
// });
// } catch (e: any) {}
};
const removeDataTab = (targetName: string) => {
@@ -533,7 +515,7 @@ export default defineComponent({
// 获取sql文件上传执行url
const getUploadSqlFileUrl = () => {
return `${config.baseApiUrl}/dbs/${state.dbId}/exec-sql-file`;
return `${config.baseApiUrl}/dbs/${state.dbId}/exec-sql-file?db=${state.db}`;
};
const flexColumnWidth = (str: any, tableData: any, flag = 'equal') => {
@@ -641,7 +623,9 @@ export default defineComponent({
*/
const changeDbInstance = (dbId: any) => {
state.db = '';
state.databaseList = (state.dbs.find((e: any) => e.id == dbId) as any).database.split(' ');
const dbInfo = state.dbs.find((e: any) => e.id == dbId) as any;
state.dbType = dbInfo.type;
state.databaseList = dbInfo.database.split(' ');
clearDb();
};
@@ -673,8 +657,6 @@ export default defineComponent({
if (tableName == '') {
return;
}
state.columnMetadata = (await getColumns(tableName)) as any;
if (!execSelectSql) {
return;
}
@@ -691,40 +673,17 @@ export default defineComponent({
tab = {
label: tableName,
name: tableName,
execRes: {
tableColumn: [],
data: [],
},
querySql: getDefaultSelectSql(tableName),
datas: [],
columnNames: [],
pageNum: 1,
count: 0,
};
tab.columnNames = await getColumnNames(tableName);
state.dataTabs[tableName] = tab;
state.dataTabs[tableName].execRes.tableColumn = [];
state.dataTabs[tableName].execRes.data = [];
onRefresh(tableName);
};
/**
* 获取默认查询语句
*/
const getDefaultSelectSql = (tableName: string, where: string = '', orderBy: string = '') => {
return `SELECT * FROM \`${tableName}\` ${where ? 'WHERE ' + where : ''} ${orderBy ? orderBy : ''} LIMIT ${state.defalutLimit}`;
};
const selectByCondition = async (tableName: string, condition: string) => {
notEmpty(condition, '条件不能为空');
state.dataTabs[tableName].loading = true;
try {
const colAndData: any = await runSql(getDefaultSelectSql(tableName, condition));
state.dataTabs[tableName].execRes.tableColumn = colAndData.colNames;
state.dataTabs[tableName].execRes.data = colAndData.res;
state.dataTabs[tableName].loading = false;
} catch (err) {
state.dataTabs[tableName].loading = false;
}
};
/**
* 获取表的所有列信息
*/
@@ -748,6 +707,11 @@ export default defineComponent({
return tableMap.get(tableName);
};
const getColumnNames = async (tableName: string) => {
const columns = await getColumns(tableName);
return columns.map((t: any) => t.columnName);
};
/**
* 条件查询,点击列信息后显示输入对应的值
*/
@@ -773,13 +737,75 @@ export default defineComponent({
};
const onRefresh = async (tableName: string) => {
const dataTab = state.dataTabs[tableName];
// 查询条件置空
state.dataTabs[tableName].condition = '';
state.dataTabs[tableName].loading = true;
const colAndData: any = await runSql(state.dataTabs[tableName].querySql);
state.dataTabs[tableName].execRes.tableColumn = colAndData.colNames;
state.dataTabs[tableName].execRes.data = colAndData.res;
state.dataTabs[tableName].loading = false;
dataTab.condition = '';
dataTab.pageNum = 1;
setDataTabDatas(dataTab);
};
/**
* 数据tab修改页数
*/
const handlePageChange = async (dataTab: any) => {
setDataTabDatas(dataTab);
};
/**
* 根据条件查询数据
*/
const selectByCondition = async (tableName: string, condition: string) => {
notEmpty(condition, '条件不能为空');
const dataTab = state.dataTabs[tableName];
dataTab.pageNum = 1;
setDataTabDatas(dataTab);
};
/**
* 设置data tab的表数据
*/
const setDataTabDatas = async (dataTab: any) => {
dataTab.loading = true;
try {
dataTab.count = await getTableCount(dataTab.name, dataTab.condition);
if (dataTab.count > 0) {
const colAndData: any = await runSql(getDefaultSelectSql(dataTab.name, dataTab.condition, dataTab.orderBy, dataTab.pageNum));
dataTab.datas = colAndData.res;
} else {
dataTab.datas = [];
}
} finally {
dataTab.loading = false;
}
};
/**
* 获取表的统计数量
*/
const getTableCount = async (tableName: string, condition: string = '') => {
const countRes = await runSql(getDefaultCountSql(tableName, condition));
return countRes.res[0].count;
};
/**
* 获取默认查询语句
*/
const getDefaultSelectSql = (tableName: string, where: string = '', orderBy: string = '', pageNum: number = 1) => {
const baseSql = `SELECT * FROM ${tableName} ${where ? 'WHERE ' + where : ''} ${orderBy ? orderBy : ''}`;
if (state.dbType == 'mysql') {
return `${baseSql} LIMIT ${(pageNum - 1) * state.defalutLimit}, ${state.defalutLimit};`
}
if (state.dbType == 'postgres') {
return `${baseSql} OFFSET ${(pageNum - 1) * state.defalutLimit} LIMIT ${state.defalutLimit};`
}
return baseSql;
};
/**
* 获取默认查询统计语句
*/
const getDefaultCountSql = (tableName: string, where: string = '') => {
return `SELECT COUNT(*) count FROM ${tableName} ${where ? 'WHERE ' + where : ''}`;
};
/**
@@ -801,7 +827,8 @@ export default defineComponent({
const tableName = state.activeName;
const sortType = sort.order == 'descending' ? 'DESC' : 'ASC';
state.dataTabs[state.activeName].querySql = getDefaultSelectSql(tableName, '', `ORDER BY \`${sort.prop}\` ${sortType}`);
const orderBy = `ORDER BY ${sort.prop} ${sortType}`;
state.dataTabs[state.activeName].orderBy = orderBy;
onRefresh(tableName);
};
@@ -892,7 +919,6 @@ export default defineComponent({
state.tableName = '';
state.nowTableName = '';
state.tableMetadata = [];
state.columnMetadata = [];
state.dataTabs = {};
setCodermirrorValue('');
state.sqlNames = [];
@@ -927,10 +953,7 @@ export default defineComponent({
promptExeSql(sql, null, () => {
if (!queryTab) {
state.dataTabs[state.activeName].execRes.data = state.dataTabs[state.activeName].execRes.data.filter(
(d: any) => !(deleteDatas.findIndex((x: any) => x[primaryKeyColumnName] == d[primaryKeyColumnName]) != -1)
);
state.dataTabs[state.activeName].selectionDatas = [];
onRefresh(state.activeName);
} else {
state.queryTab.execRes.data = state.queryTab.execRes.data.filter(
(d: any) => !(deleteDatas.findIndex((x: any) => x[primaryKeyColumnName] == d[primaryKeyColumnName]) != -1)
@@ -955,7 +978,7 @@ export default defineComponent({
return;
}
// 转为字符串比较,可能存在数字等
let text = row[property] + '';
let text = (row[property] ? row[property] : '') + '';
let div = cell.children[0];
if (div) {
let input = document.createElement('input');
@@ -1107,6 +1130,7 @@ export default defineComponent({
formatSql,
onBeforeChange,
onRefresh,
handlePageChange,
selectByCondition,
onCommit,
addRow,

View File

@@ -5,6 +5,7 @@ export const dbApi = {
dbs: Api.create("/dbs", 'get'),
saveDb: Api.create("/dbs", 'post'),
deleteDb: Api.create("/dbs/{id}", 'delete'),
dumpDb: Api.create("/dbs/{id}/dump", 'post'),
tableInfos: Api.create("/dbs/{id}/t-infos", 'get'),
tableIndex: Api.create("/dbs/{id}/t-index", 'get'),
tableDdl: Api.create("/dbs/{id}/t-create-ddl", 'get'),

View File

@@ -2,7 +2,7 @@
<div>
<el-dialog title="待执行SQL" v-model="dialogVisible" :show-close="false" width="600px">
<codemirror height="350px" class="codesql" ref="cmEditor" language="sql" v-model="sqlValue" :options="cmOptions" />
<el-input v-model="remark" placeholder="请输入执行备注" class="mt5" />
<el-input ref="remarkInputRef" v-model="remark" placeholder="请输入执行备注" class="mt5" />
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel"> </el-button>
@@ -14,9 +14,9 @@
</template>
<script lang="ts">
import { toRefs, reactive, defineComponent } from 'vue';
import { toRefs, ref, nextTick, reactive, defineComponent } from 'vue';
import { dbApi } from '../api';
import { ElDialog, ElButton, ElInput, ElMessage } from 'element-plus';
import { ElDialog, ElButton, ElInput, ElMessage, InputInstance } from 'element-plus';
// import base style
import 'codemirror/lib/codemirror.css';
// 引入主题后还需要在 options 中指定主题才会生效
@@ -50,6 +50,7 @@ export default defineComponent({
},
},
setup(props: any) {
const remarkInputRef = ref<InputInstance>();
const state = reactive({
dialogVisible: false,
sqlValue: '',
@@ -84,16 +85,22 @@ export default defineComponent({
ElMessage.error('请输入执行的备注信息');
return;
}
try {
state.btnLoading = true;
await dbApi.sqlExec.request({
const res = await dbApi.sqlExec.request({
id: state.dbId,
db: state.db,
remark: state.remark,
sql: state.sqlValue.trim(),
});
runSuccess = true;
if (parseInt(res.res[0].影响条数) >= 1) {
ElMessage.success('执行成功');
runSuccess = true;
} else {
ElMessage.error('执行失败');
runSuccess = false;
}
} catch (e) {
runSuccess = false;
}
@@ -127,10 +134,16 @@ export default defineComponent({
state.dbId = props.dbId;
state.db = props.db;
state.dialogVisible = true;
nextTick(() => {
setTimeout(() => {
remarkInputRef.value?.focus();
});
});
};
return {
...toRefs(state),
remarkInputRef,
open,
runSql,
cancel,

View File

@@ -89,17 +89,19 @@
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item v-if="data.type == '-' && data.size < 1 * 1024 * 1024">
<el-link
@click.prevent="getFileContent(tree.folder.id, data.path)"
type="info"
icon="view"
:underline="false"
>
查看
</el-link>
<el-dropdown-item
@click="getFileContent(tree.folder.id, data.path)"
v-if="data.type == '-' && data.size < 1 * 1024 * 1024"
>
<el-link type="info" icon="view" :underline="false">查看</el-link>
</el-dropdown-item>
<span v-auth="'machine:file:write'">
<el-dropdown-item @click="showCreateFileDialog(node, data)" v-if="data.type == 'd'">
<el-link type="primary" icon="document" :underline="false" style="margin-left: 2px">新建</el-link>
</el-dropdown-item>
</span>
<span v-auth="'machine:file:upload'">
<el-dropdown-item v-if="data.type == 'd'">
<el-upload
@@ -112,34 +114,20 @@
name="file"
style="display: inline-block; margin-left: 2px"
>
<el-link icon="upload" :underline="false"> 上传 </el-link>
<el-link icon="upload" :underline="false">上传</el-link>
</el-upload>
</el-dropdown-item>
</span>
<span v-auth="'machine:file:write'">
<el-dropdown-item v-if="data.type == '-'">
<el-link
@click.prevent="downloadFile(node, data)"
type="primary"
icon="download"
:underline="false"
style="margin-left: 2px"
>下载</el-link
>
<el-dropdown-item @click="downloadFile(node, data)" v-if="data.type == '-'">
<el-link type="primary" icon="download" :underline="false" style="margin-left: 2px">下载</el-link>
</el-dropdown-item>
</span>
<span v-auth="'machine:file:rm'">
<el-dropdown-item v-if="!dontOperate(data)">
<el-link
@click.prevent="deleteFile(node, data)"
type="danger"
icon="delete"
:underline="false"
style="margin-left: 2px"
>删除
</el-link>
<el-dropdown-item @click="deleteFile(node, data)" v-if="!dontOperate(data)">
<el-link type="danger" icon="delete" :underline="false" style="margin-left: 2px">删除</el-link>
</el-dropdown-item>
</span>
</el-dropdown-menu>
@@ -151,6 +139,35 @@
</div>
</el-dialog>
<el-dialog
:destroy-on-close="true"
title="新建文件"
v-model="createFileDialog.visible"
:before-close="closeCreateFileDialog"
:close-on-click-modal="false"
top="5vh"
width="400px"
>
<div>
<el-form-item prop="name" label="名称:">
<el-input v-model.trim="createFileDialog.name" placeholder="请输入名称" auto-complete="off"></el-input>
</el-form-item>
<el-form-item prop="type" label="类型:">
<el-radio-group v-model="createFileDialog.type">
<el-radio label="d" size="small">文件夹</el-radio>
<el-radio label="-" size="small">文件</el-radio>
</el-radio-group>
</el-form-item>
</div>
<template #footer>
<div class="dialog-footer">
<el-button @click="closeCreateFileDialog">关闭</el-button>
<el-button v-auth="'machine:file:write'" type="primary" @click="createFile">确定</el-button>
</div>
</template>
</el-dialog>
<el-dialog
:destroy-on-close="true"
:title="fileContent.dialogTitle"
@@ -182,6 +199,7 @@ import { codemirror } from '@/components/codemirror';
import { getSession } from '@/common/utils/storage';
import enums from './enums';
import config from '@/common/config';
import { isTrue } from '@/common/assert';
export default defineComponent({
name: 'FileManage',
@@ -202,26 +220,8 @@ export default defineComponent({
const fileTree: any = ref(null);
const token = getSession('token');
const cmOptions = {
tabSize: 2,
mode: 'text/x-sh',
theme: 'panda-syntax',
line: true,
// 开启校验
lint: true,
gutters: ['CodeMirror-lint-markers'],
indentWithTabs: true,
smartIndent: true,
matchBrackets: true,
autofocus: true,
styleSelectedText: true,
styleActiveLine: true, // 高亮选中行
foldGutter: true, // 块槽
hintOptions: {
// 当匹配只有一项的时候是否自动补全
completeSingle: true,
},
};
const folderType = 'd';
const fileType = '-';
const state = reactive({
dialogVisible: false,
@@ -268,6 +268,12 @@ export default defineComponent({
path: '',
type: '',
},
createFileDialog: {
visible: false,
name: '',
type: folderType,
node: null as any,
},
file: null as any,
});
@@ -290,18 +296,6 @@ export default defineComponent({
getFiles();
};
/**
* tab切换触发事件
* @param {Object} tab
* @param {Object} event
*/
// handleClick(tab, event) {
// // if (tab.name == 'file-manage') {
// // this.fileManage.node.childNodes = [];
// // this.loadNode(this.fileManage.node, this.fileManage.resolve);
// // }
// }
const add = () => {
// 往数组头部添加元素
state.fileTable = [{}].concat(state.fileTable);
@@ -329,7 +323,6 @@ export default defineComponent({
})
.then(() => {
getFiles();
// state.fileTable.splice(idx, 1);
});
});
} else {
@@ -406,7 +399,6 @@ export default defineComponent({
emit('update:visible', false);
emit('update:machineId', null);
emit('cancel');
// state.activeName = 'conf-file'
state.fileTable = [];
state.tree.folder = { id: 0 };
};
@@ -431,7 +423,7 @@ export default defineComponent({
return resolve([
{
name: path,
type: 'd',
type: folderType,
path: path,
},
]);
@@ -453,13 +445,42 @@ export default defineComponent({
});
for (const file of res) {
const type = file.type;
if (type != 'd') {
if (type == fileType) {
file.leaf = true;
}
}
return resolve(res);
};
const showCreateFileDialog = (node: any) => {
isTrue(node.expanded, '请先点击展开该节点后再创建');
state.createFileDialog.node = node;
state.createFileDialog.visible = true;
};
const createFile = async () => {
const node = state.createFileDialog.node;
console.log(node.data);
const name = state.createFileDialog.name;
const type = state.createFileDialog.type;
const path = node.data.path + '/' + name;
await machineApi.createFile.request({
machineId: props.machineId,
id: state.tree.folder.id,
path,
type,
});
fileTree.value.append({ name: name, path: path, type: type, leaf: type === fileType, size: 0 }, node);
closeCreateFileDialog();
};
const closeCreateFileDialog = () => {
state.createFileDialog.visible = false;
state.createFileDialog.node = null;
state.createFileDialog.name = '';
state.createFileDialog.type = folderType;
};
const deleteFile = (node: any, data: any) => {
const file = data.path;
ElMessageBox.confirm(`此操作将删除 [${file}], 是否继续?`, '提示', {
@@ -486,7 +507,6 @@ export default defineComponent({
const downloadFile = (node: any, data: any) => {
const a = document.createElement('a');
// a.setAttribute('target', '_blank')
a.setAttribute(
'href',
`${config.baseApiUrl}/machines/${props.machineId}/files/${state.tree.folder.id}/read?type=1&path=${data.path}&token=${token}`
@@ -534,7 +554,6 @@ export default defineComponent({
const beforeUpload = (file: File) => {
state.file = file;
// ElMessage.success(`'${file.name}' 上传中,请关注结果通知`);
};
const getFilePath = (data: object, visible: boolean) => {
if (visible) {
@@ -590,7 +609,6 @@ export default defineComponent({
fileTree,
enums,
token,
cmOptions,
add,
getFiles,
handlePageChange,
@@ -601,6 +619,9 @@ export default defineComponent({
updateContent,
handleClose,
loadNode,
showCreateFileDialog,
closeCreateFileDialog,
createFile,
deleteFile,
downloadFile,
getUploadFile,

View File

@@ -57,11 +57,10 @@
v-model="scope.row.status"
:active-value="1"
:inactive-value="-1"
active-color="#13ce66"
inactive-color="#ff4949"
inline-prompt
active-text="启用"
inactive-text="停用"
style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
@change="changeStatus(scope.row)"
></el-switch>
</template>

View File

@@ -25,7 +25,7 @@
</el-form-item>
<el-form-item prop="params" label="参数">
<el-input v-model.trim="form.params" placeholder="参数数组json若无可不填"></el-input>
<el-input v-model="form.params" placeholder="参数数组json若无可不填"></el-input>
</el-form-item>
<el-form-item prop="script" label="内容" id="content">

View File

@@ -25,6 +25,7 @@ export const machineApi = {
rmFile: Api.create("/machines/{machineId}/files/{fileId}/remove", 'delete'),
uploadFile: Api.create("/machines/{machineId}/files/{fileId}/upload?token={token}", 'post'),
fileContent: Api.create("/machines/{machineId}/files/{fileId}/read", 'get'),
createFile: Api.create("/machines/{machineId}/files/{id}/create-file", 'post'),
// 修改文件内容
updateFileContent: Api.create("/machines/{machineId}/files/{id}/write", 'post'),
// 添加文件or目录

View File

@@ -250,7 +250,7 @@ export default defineComponent({
onMounted(async () => {
search();
state.projects = (await projectApi.projects.request({ pageNum: 1, pageSize: 100 })).list;
state.projects = await projectApi.accountProjects.request(null);
});
const handlePageChange = (curPage: number) => {
@@ -266,12 +266,6 @@ export default defineComponent({
state.currentData = item;
};
// connect() {
// Req.post('/open/redis/connect', this.form, res => {
// this.redisInfo = res
// })
// }
const showDatabases = async (id: number) => {
state.databaseDialog.data = (await mongoApi.databases.request({ id })).Databases;
state.databaseDialog.title = `数据库列表`;
@@ -371,14 +365,6 @@ export default defineComponent({
} catch (err) {}
};
// const info = (redis: any) => {
// redisApi.redisInfo.request({ id: redis.id }).then((res: any) => {
// state.infoDialog.info = res;
// state.infoDialog.title = `'${redis.host}' info`;
// state.infoDialog.visible = true;
// });
// };
const search = async () => {
const res = await mongoApi.mongoList.request(state.query);
state.list = res.list;

View File

@@ -31,7 +31,7 @@
></el-input>
</el-form-item>
<el-form-item label="count" label-width="60px">
<el-input placeholder="count" style="width: 62px" v-model="scanParam.count"></el-input>
<el-input placeholder="count" style="width: 62px" v-model.number="scanParam.count"></el-input>
</el-form-item>
<el-form-item>
<el-button @click="searchKey()" type="success" icon="search" plain></el-button>
@@ -92,7 +92,7 @@ import { toRefs, reactive, defineComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProjectEnvSelect from '../component/ProjectEnvSelect.vue';
import DataEdit from './DataEdit.vue';
import { isTrue, notNull } from '@/common/assert';
import { isTrue, notBlank, notNull } from '@/common/assert';
export default defineComponent({
name: 'DataOperation',
@@ -103,18 +103,15 @@ export default defineComponent({
setup() {
const state = reactive({
loading: false,
cluster: 0,
redisList: [],
query: {
envId: 0,
},
scanParam: {
id: null,
cluster: 0,
match: null,
count: 10,
cursor: 0,
prevCursor: null,
cursor: {},
},
valueDialog: {
visible: false,
@@ -151,31 +148,33 @@ export default defineComponent({
}
};
const changeRedis = () => {
resetScanParam();
const changeRedis = (id: number) => {
resetScanParam(id);
state.keys = [];
state.dbsize = 0;
searchKey();
};
const scan = () => {
const scan = async () => {
isTrue(state.scanParam.id != null, '请先选择redis');
notBlank(state.scanParam.count, 'count不能为空');
isTrue(state.scanParam.count < 20001, 'count不能超过20000');
state.loading = true;
state.scanParam.cluster = state.cluster == 0 ? 0 : 1;
redisApi.scan.request(state.scanParam).then((res) => {
try {
const res = await redisApi.scan.request(state.scanParam);
state.keys = res.keys;
state.dbsize = res.dbSize;
state.scanParam.cursor = res.cursor;
} finally {
state.loading = false;
});
}
};
const searchKey = () => {
state.scanParam.cursor = 0;
scan();
const searchKey = async () => {
state.scanParam.cursor = {};
await scan();
};
const clearRedis = () => {
@@ -193,10 +192,17 @@ export default defineComponent({
}
};
const resetScanParam = () => {
state.scanParam.match = null;
state.scanParam.cursor = 0;
const resetScanParam = (id: number = 0) => {
state.scanParam.count = 10;
if (id != 0) {
const redis: any = state.redisList.find((x: any) => x.id == id);
// 集群模式count设小点因为后端会从所有master节点scan一遍然后合并结果
if (redis && redis.mode == 'cluster') {
state.scanParam.count = 5;
}
}
state.scanParam.match = null;
state.scanParam.cursor = {};
};
const getValue = async (row: any) => {
@@ -204,11 +210,9 @@ export default defineComponent({
const key = row.key;
let res: any;
const id = state.cluster == 0 ? state.scanParam.id : state.cluster;
const reqParam = {
cluster: state.cluster,
key: row.key,
id,
id: state.scanParam.id,
};
switch (type) {
case 'string':
@@ -260,29 +264,27 @@ export default defineComponent({
};
const del = (key: string) => {
ElMessageBox.confirm(`此操作将删除对应的key , 是否继续?`, '提示', {
ElMessageBox.confirm(`确定删除[ ${key} ] 该key?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(() => {
let id = state.cluster == 0 ? state.scanParam.id : state.cluster;
redisApi.delKey
.request({
cluster: state.cluster,
key,
id,
id: state.scanParam.id,
})
.then(() => {
ElMessage.success('删除成功!');
scan();
searchKey();
});
})
.catch(() => {});
};
const ttlConveter = (ttl: any) => {
if (ttl == -1) {
if (ttl == -1 || ttl == 0) {
return '永久';
}
if (!ttl) {

View File

@@ -13,8 +13,14 @@
<el-option v-for="item in envs" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
</el-select>
</el-form-item>
<el-form-item prop="mode" label="mode:" required>
<el-select style="width: 100%" v-model="form.mode" placeholder="请选择模式">
<el-option label="standalone" value="standalone"> </el-option>
<el-option label="cluster" value="cluster"> </el-option>
</el-select>
</el-form-item>
<el-form-item prop="host" label="host:" required>
<el-input v-model.trim="form.host" placeholder="请输入host:port" auto-complete="off"></el-input>
<el-input v-model.trim="form.host" placeholder="请输入host:port,集群模式用','分割" auto-complete="off" type="textarea"></el-input>
</el-form-item>
<el-form-item prop="password" label="密码:">
<el-input
@@ -28,6 +34,9 @@
<el-form-item prop="db" label="库号:" required>
<el-input v-model.number="form.db" placeholder="请输入库号"></el-input>
</el-form-item>
<el-form-item prop="remark" label="备注:">
<el-input v-model.trim="form.remark" auto-complete="off" type="textarea"></el-input>
</el-form-item>
</el-form>
<template #footer>
@@ -71,12 +80,14 @@ export default defineComponent({
form: {
id: null,
name: null,
mode: "standalone",
host: null,
password: null,
project: null,
projectId: null,
envId: null,
env: null,
remark: "",
},
btnLoading: false,
rules: {
@@ -108,6 +119,13 @@ export default defineComponent({
trigger: ['change', 'blur'],
},
],
mode: [
{
required: true,
message: '请输入模式',
trigger: ['change', 'blur'],
},
],
},
});

View File

@@ -5,16 +5,12 @@
<el-button type="primary" icon="edit" :disabled="currentId == null" @click="editRedis(false)" plain>编辑</el-button>
<el-button type="danger" icon="delete" :disabled="currentId == null" @click="deleteRedis" plain>删除</el-button>
<div style="float: right">
<!-- <el-input placeholder="host" style="width: 140px" v-model="query.host" @clear="search" plain clearable></el-input>
<el-select v-model="params.clusterId" clearable placeholder="集群选择">
<el-option v-for="item in clusters" :key="item.id" :value="item.id" :label="item.name"></el-option>
</el-select> -->
<el-select v-model="query.projectId" placeholder="请选择项目" filterable clearable>
<el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
</el-select>
<el-button class="ml5" @click="search" type="success" icon="search"></el-button>
</div>
<el-table :data="redisTable" style="width: 100%" @current-change="choose" stripe>
<el-table :data="redisTable" @current-change="choose" stripe>
<el-table-column label="选择" width="60px">
<template #default="scope">
<el-radio v-model="currentId" :label="scope.row.id">
@@ -22,19 +18,23 @@
</el-radio>
</template>
</el-table-column>
<el-table-column prop="project" label="项目" width></el-table-column>
<el-table-column prop="env" label="环境" width></el-table-column>
<el-table-column prop="host" label="host:port" width></el-table-column>
<el-table-column prop="createTime" label="创建时间">
<el-table-column prop="project" label="项目" min-width="100"></el-table-column>
<el-table-column prop="env" label="环境" min-width="100"></el-table-column>
<el-table-column prop="host" label="host:port" min-width="150" show-overflow-tooltip> </el-table-column>
<el-table-column prop="mode" label="mode" min-width="100"></el-table-column>
<el-table-column prop="remark" label="备注" min-width="100"></el-table-column>
<el-table-column prop="createTime" label="创建时间" min-width="160">
<template #default="scope">
{{ $filters.dateFormat(scope.row.createTime) }}
</template>
</el-table-column>
<el-table-column prop="creator" label="创建人"></el-table-column>
<el-table-column label="操作" width>
<el-table-column prop="creator" label="创建人" min-width="100"></el-table-column>
<el-table-column label="更多" min-width="130" fixed="right">
<template #default="scope">
<el-button type="primary" @click="info(scope.row)" icon="tickets" plain size="small">info</el-button>
<!-- <el-button type="success" @click="manage(scope.row)" :ref="scope.row" plain>数据管理</el-button> -->
<el-link v-if="scope.row.mode == 'standalone'" type="primary" @click="info(scope.row)" :underline="false">单机信息</el-link>
<el-link @click="onShowClusterInfo(scope.row)" v-if="scope.row.mode == 'cluster'" type="success" :underline="false"
>集群信息</el-link
>
</template>
</el-table-column>
</el-table>
@@ -52,6 +52,84 @@
<info v-model:visible="infoDialog.visible" :title="infoDialog.title" :info="infoDialog.info"></info>
<el-dialog width="1000px" title="集群信息" v-model="clusterInfoDialog.visible">
<el-input type="textarea" :autosize="{ minRows: 12, maxRows: 12 }" v-model="clusterInfoDialog.info"> </el-input>
<el-divider content-position="left">节点信息</el-divider>
<el-table :data="clusterInfoDialog.nodes" stripe size="small" border>
<el-table-column prop="nodeId" label="nodeId" min-width="300">
<template #header>
nodeId
<el-tooltip class="box-item" effect="dark" content="节点id" placement="top">
<el-icon><question-filled /></el-icon>
</el-tooltip>
</template>
</el-table-column>
<el-table-column prop="ip" label="ip" min-width="180">
<template #header>
ip
<el-tooltip
class="box-item"
effect="dark"
content="ip:port1@port2port1指redis服务器与客户端通信的端口port2则是集群内部节点间通信的端口"
placement="top"
>
<el-icon><question-filled /></el-icon>
</el-tooltip>
</template>
<template #default="scope">
<el-tag
@click="info({ id: clusterInfoDialog.redisId, ip: scope.row.ip })"
effect="plain"
type="success"
size="small"
style="cursor: pointer"
>{{ scope.row.ip }}</el-tag
>
</template>
</el-table-column>
<el-table-column prop="flags" label="flags" min-width="110"></el-table-column>
<el-table-column prop="masterSlaveRelation" label="masterSlaveRelation" min-width="300">
<template #header>
masterSlaveRelation
<el-tooltip
class="box-item"
effect="dark"
content="如果节点是slave并且已知master节点则为master节点ID否则为符号'-'"
placement="top"
>
<el-icon><question-filled /></el-icon>
</el-tooltip>
</template>
</el-table-column>
<el-table-column prop="pingSent" label="pingSent" min-width="130" show-overflow-tooltip>
<template #default="scope">
{{ scope.row.pingSent == 0 ? 0 : new Date(parseInt(scope.row.pingSent)).toLocaleString() }}
</template>
</el-table-column>
<el-table-column prop="pongRecv" label="pongRecv" min-width="130" show-overflow-tooltip>
<template #default="scope">
{{ scope.row.pongRecv == 0 ? 0 : new Date(parseInt(scope.row.pongRecv)).toLocaleString() }}
</template>
</el-table-column>
<el-table-column prop="configEpoch" label="configEpoch" min-width="130">
<template #header>
configEpoch
<el-tooltip
class="box-item"
effect="dark"
content="节点的epoch值如果该节点是从节点则为其主节点的epoch值。每当节点发生失败切换时都会创建一个新的独特的递增的epoch。"
placement="top"
>
<el-icon><question-filled /></el-icon>
</el-tooltip>
</template>
</el-table-column>
<el-table-column prop="linkState" label="linkState" min-width="100"></el-table-column>
<el-table-column prop="slot" label="slot" min-width="100"></el-table-column>
</el-table>
</el-dialog>
<redis-edit
@val-change="valChange"
:projects="projects"
@@ -92,6 +170,12 @@ export default defineComponent({
redisInfo: {
url: '',
},
clusterInfoDialog: {
visible: false,
redisId: 0,
info: '',
nodes: [],
},
clusters: [
{
id: 0,
@@ -118,7 +202,7 @@ export default defineComponent({
onMounted(async () => {
search();
state.projects = (await projectApi.projects.request({ pageNum: 1, pageSize: 100 })).list;
state.projects = await projectApi.accountProjects.request(null);
});
const handlePageChange = (curPage: number) => {
@@ -134,12 +218,6 @@ export default defineComponent({
state.currentData = item;
};
// connect() {
// Req.post('/open/redis/connect', this.form, res => {
// this.redisInfo = res
// })
// }
const deleteRedis = async () => {
try {
await ElMessageBox.confirm(`确定删除该redis?`, '提示', {
@@ -155,12 +233,23 @@ export default defineComponent({
} catch (err) {}
};
const info = (redis: any) => {
redisApi.redisInfo.request({ id: redis.id }).then((res: any) => {
state.infoDialog.info = res;
state.infoDialog.title = `'${redis.host}' info`;
state.infoDialog.visible = true;
});
const info = async (redis: any) => {
var host = redis.host;
if (redis.ip) {
host = redis.ip.split('@')[0];
}
const res = await redisApi.redisInfo.request({ id: redis.id, host });
state.infoDialog.info = res;
state.infoDialog.title = `'${host}' info`;
state.infoDialog.visible = true;
};
const onShowClusterInfo = async (redis: any) => {
const ci = await redisApi.clusterInfo.request({ id: redis.id });
state.clusterInfoDialog.info = ci.clusterInfo;
state.clusterInfoDialog.nodes = ci.clusterNodes;
state.clusterInfoDialog.redisId = redis.id;
state.clusterInfoDialog.visible = true;
};
const search = async () => {
@@ -192,6 +281,7 @@ export default defineComponent({
handlePageChange,
choose,
info,
onShowClusterInfo,
deleteRedis,
editRedis,
valChange,

View File

@@ -3,10 +3,11 @@ import Api from '@/common/Api';
export const redisApi = {
redisList : Api.create("/redis", 'get'),
redisInfo: Api.create("/redis/{id}/info", 'get'),
clusterInfo: Api.create("/redis/{id}/cluster-info", 'get'),
saveRedis: Api.create("/redis", 'post'),
delRedis: Api.create("/redis/{id}", 'delete'),
// 获取权限列表
scan: Api.create("/redis/{id}/scan/{cursor}/{count}", 'get'),
scan: Api.create("/redis/{id}/scan", 'post'),
getStringValue: Api.create("/redis/{id}/string-value", 'get'),
saveStringValue: Api.create("/redis/{id}/string-value", 'post'),
getHashValue: Api.create("/redis/{id}/hash-value", 'get'),

View File

@@ -3,7 +3,7 @@
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :show-close="false" width="35%" :destroy-on-close="true">
<el-form :model="form" ref="accountForm" :rules="rules" label-width="85px">
<el-form-item prop="username" label="用户名:" required>
<el-input :disabled="edit" v-model.trim="form.username" placeholder="请输入账号用户名" auto-complete="off"></el-input>
<el-input :disabled="edit" v-model.trim="form.username" placeholder="请输入账号用户名,密码默认与账号名一致" auto-complete="off"></el-input>
</el-form-item>
<!-- <el-form-item prop="password" label="密码:" required>
<el-input type="password" v-model.trim="form.password" placeholder="请输入密码" autocomplete="new-password"></el-input>

View File

@@ -2,7 +2,7 @@
<div class="role-list">
<el-card>
<el-button v-auth="'account:add'" type="primary" icon="plus" @click="editAccount(true)">添加</el-button>
<el-button v-auth="'account:update'" :disabled="chooseId == null" @click="editAccount(false)" type="primary" icon="edit">编辑</el-button>
<!-- <el-button v-auth="'account:update'" :disabled="chooseId == null" @click="editAccount(false)" type="primary" icon="edit">编辑</el-button> -->
<el-button v-auth="'account:saveRoles'" :disabled="chooseId == null" @click="roleEdit()" type="success" icon="setting"
>角色分配</el-button
>

View File

@@ -12,15 +12,10 @@
resolved "https://registry.npmmirror.com/@ctrl/tinycolor/-/tinycolor-3.4.1.tgz#75b4c27948c81e88ccd3a8902047bcd797f38d32"
integrity sha512-ej5oVy6lykXsvieQtqZxCOaLT+xD4+QNarq78cIYISHmZXshCvROLudpQN3lfL8G0NL7plMSSK+zlyvCaIJ4Iw==
"@element-plus/icons-vue@^2.0.4":
version "2.0.4"
resolved "https://registry.npmmirror.com/@element-plus/icons-vue/-/icons-vue-2.0.4.tgz#98fb9680c814a2a4f231b8bdabc8cd59b1b79d86"
integrity sha512-UeBVBU3fuBsYa9mzM7DgkRztQ1Aftw3sMTI/1gZsqXq2NWiCOi16ZYXXGIc0jFDIu+k6SojzdlxOjv+rN/Y6FQ==
"@element-plus/icons-vue@^2.0.5":
version "2.0.5"
resolved "https://registry.npmmirror.com/@element-plus/icons-vue/-/icons-vue-2.0.5.tgz#8eb4143a7b5e4d8468d2e72af99eefee446f5ea0"
integrity sha512-jvNWyKcdvPvMDLTWjghrPY+bYHKqh7hbAFIPe+HWR073zilzt33csREzmKx3VwhdlJUW5u0nCqN+0rwI8jlH+w==
"@element-plus/icons-vue@^2.0.6":
version "2.0.6"
resolved "https://registry.npmmirror.com/@element-plus/icons-vue/-/icons-vue-2.0.6.tgz#8490e7a3193c17515d10c3be0544d800afe6a228"
integrity sha512-lPpG8hYkjL/Z97DH5Ei6w6o22Z4YdNglWCNYOPcB33JCF2A4wye6HFgSI7hEt9zdLyxlSpiqtgf9XcYU+m5mew==
"@eslint/eslintrc@^1.0.5":
version "1.0.5"
@@ -37,17 +32,17 @@
minimatch "^3.0.4"
strip-json-comments "^3.1.1"
"@floating-ui/core@^0.7.2":
version "0.7.2"
resolved "https://registry.npmmirror.com/@floating-ui/core/-/core-0.7.2.tgz#f7af9613d080dc29360e77c970965b79b524d45a"
integrity sha512-FRVAkSNU/vGXLIsgbggcs70GkXKEOXgBBbNpYPNHSaKsCAMMd00NrjbtKTesxkdv9xm9N3+XiDlcFGY6WnatBg==
"@floating-ui/core@^0.7.3":
version "0.7.3"
resolved "https://registry.npmmirror.com/@floating-ui/core/-/core-0.7.3.tgz#d274116678ffae87f6b60e90f88cc4083eefab86"
integrity sha512-buc8BXHmG9l82+OQXOFU3Kr2XQx9ys01U/Q9HMIrZ300iLc8HLMgh7dcCqgYzAzf4BkoQvDcXf5Y+CuEZ5JBYg==
"@floating-ui/dom@^0.5.0":
version "0.5.2"
resolved "https://registry.npmmirror.com/@floating-ui/dom/-/dom-0.5.2.tgz#908f3febbfc0d6696d70921616ec194fe07af183"
integrity sha512-z1DnEa7F3d8Fm/eXSbii8UEGpcjZGkQaYYUI0WpEVgD3vBfebDW8j/3ysusxonuMexoigA+A3b/fYH7sEqiwyg==
"@floating-ui/dom@^0.5.4":
version "0.5.4"
resolved "https://registry.npmmirror.com/@floating-ui/dom/-/dom-0.5.4.tgz#4eae73f78bcd4bd553ae2ade30e6f1f9c73fe3f1"
integrity sha512-419BMceRLq0RrmTSDxn8hf9R3VCJv2K9PUfugh5JyEFmdjzDo+e8U5EdR8nzKq8Yj1htzLm3b6eQEEam3/rrtg==
dependencies:
"@floating-ui/core" "^0.7.2"
"@floating-ui/core" "^0.7.3"
"@humanwhocodes/config-array@^0.9.2":
version "0.9.2"
@@ -131,6 +126,11 @@
resolved "https://registry.npmmirror.com/@types/sortablejs/download/@types/sortablejs-1.10.7.tgz#ab9039c85429f0516955ec6dbc0bb20139417b15"
integrity sha1-q5A5yFQp8FFpVextvAuyATlBexU=
"@types/web-bluetooth@^0.0.14":
version "0.0.14"
resolved "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.14.tgz#94e175b53623384bff1f354cdb3197a8d63cdbe5"
integrity sha512-5d2RhCard1nQUC3aHcq/gHzWYO6K0WJmAbjO7mQJgCQKtZpgXxv1rOM6O/dBDhDYYVutk1sciOgNSe+5YyfM8A==
"@typescript-eslint/eslint-plugin@^4.23.0":
version "4.33.0"
resolved "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/download/@typescript-eslint/eslint-plugin-4.33.0.tgz#c24dc7c8069c7706bc40d99f6fa87edcb2005276"
@@ -364,31 +364,32 @@
resolved "https://registry.npmmirror.com/@vue/shared/-/shared-3.2.37.tgz#8e6adc3f2759af52f0e85863dfb0b711ecc5c702"
integrity sha512-4rSJemR2NQIo9Klm1vabqWjD8rs/ZaJSzMxkMNeJS6lHiUjjUeYFbooN19NgFjztubEKh3WlZUeOLVdbbUWHsw==
"@vueuse/core@^8.5.0":
version "8.6.0"
resolved "https://registry.npmmirror.com/@vueuse/core/-/core-8.6.0.tgz#a8f80363cc63d17382423f16beae57696f376e67"
integrity sha512-VirzExCm/N+QdrEWT7J4uSrvJ5hquKIAU9alQ37kUvIJk9XxCLxmfRnmekYc1kz2+6BnoyuKYXVmrMV351CB4w==
"@vueuse/core@^8.7.5":
version "8.7.5"
resolved "https://registry.npmmirror.com/@vueuse/core/-/core-8.7.5.tgz#e74a888251ea11a9d432068ce18cbdfc4f810251"
integrity sha512-tqgzeZGoZcXzoit4kOGLWJibDMLp0vdm6ZO41SSUQhkhtrPhAg6dbIEPiahhUu6sZAmSYvVrZgEr5aKD51nrLA==
dependencies:
"@vueuse/metadata" "8.6.0"
"@vueuse/shared" "8.6.0"
"@types/web-bluetooth" "^0.0.14"
"@vueuse/metadata" "8.7.5"
"@vueuse/shared" "8.7.5"
vue-demi "*"
"@vueuse/metadata@8.6.0":
version "8.6.0"
resolved "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-8.6.0.tgz#34771443a72ee891ae001a70aa05dd9a1d799372"
integrity sha512-F+CKPvaExsm7QgRr8y+ZNJFwXasn89rs5wth/HeX9lJ1q8XEt+HJ16Q5Sxh4rfG5YSKXrStveVge8TKvPjMjFA==
"@vueuse/metadata@8.7.5":
version "8.7.5"
resolved "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-8.7.5.tgz#c7f2b21d873d1604a8860ed9c5728d8f3295f00a"
integrity sha512-emJZKRQSaEnVqmlu39NpNp8iaW+bPC2kWykWoWOZMSlO/0QVEmO/rt8A5VhOEJTKLX3vwTevqbiRy9WJRwVOQg==
"@vueuse/shared@8.6.0":
version "8.6.0"
resolved "https://registry.npmmirror.com/@vueuse/shared/-/shared-8.6.0.tgz#63dad9fc4b73a7fccbe5d6b97adeacf73d4fec41"
integrity sha512-Y/IVywZo7IfEoSSEtCYpkVEmPV7pU35mEIxV7PbD/D3ly18B3mEsBaPbtDkNM/QP3zAZ5mn4nEkOfddX4uwuIA==
"@vueuse/shared@8.7.5":
version "8.7.5"
resolved "https://registry.npmmirror.com/@vueuse/shared/-/shared-8.7.5.tgz#06fb08f6f8fc9e90be9d1e033fa443de927172b0"
integrity sha512-THXPvMBFmg6Gf6AwRn/EdTh2mhqwjGsB2Yfp374LNQSQVKRHtnJ0I42bsZTn7nuEliBxqUrGQm/lN6qUHmhJLw==
dependencies:
vue-demi "*"
ace-builds@^1.5.3:
version "1.5.3"
resolved "https://registry.npmmirror.com/ace-builds/-/ace-builds-1.5.3.tgz#05f81d3464a9ea19696e5e6fd0f924d37dab442f"
integrity sha512-WN5BKR2aTSuBmisO8jo3Fytk6sOmJGki82v/Boeic81IgYN8pFHNkXq2anDF0XkmfDWMqLbRoW9sjc/GtKzQbQ==
ace-builds@^1.6.0:
version "1.7.1"
resolved "https://registry.npmmirror.com/ace-builds/-/ace-builds-1.7.1.tgz#be796fbd98610dda5e138aed98d309cac2ab0872"
integrity sha512-1mcbP5kXvr729sJ9dA/8tul0pjuvKbma0LF/ZMRwPEwjoNWNpe/x0OXpaPJo36aRpZCjRZMl5zsME3hAKTiaNw==
acorn-jsx@^5.3.1:
version "5.3.2"
@@ -445,10 +446,10 @@ array-union@^2.1.0:
resolved "https://registry.npm.taobao.org/array-union/download/array-union-2.1.0.tgz?cache=0&sync_timestamp=1614624262896&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Farray-union%2Fdownload%2Farray-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d"
integrity sha1-t5hCCtvrHego2ErNii4j0+/oXo0=
async-validator@^4.1.1:
version "4.1.1"
resolved "https://registry.npmmirror.com/async-validator/-/async-validator-4.1.1.tgz#3cd1437faa2de64743f7d56649dd904c946a18fe"
integrity sha512-p4DO/JXwjs8klJyJL8Q2oM4ks5fUTze/h5k10oPPKMiLe1fj3G1QMzPHNmN1Py4ycOk7WlO2DcGXv1qiESJCZA==
async-validator@^4.2.5:
version "4.2.5"
resolved "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz#c96ea3332a521699d0afaaceed510a54656c6339"
integrity sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==
asynckit@^0.4.0:
version "0.4.0"
@@ -578,10 +579,10 @@ csstype@^2.6.8:
resolved "https://registry.npmmirror.com/csstype/download/csstype-2.6.19.tgz?cache=0&sync_timestamp=1637224514674&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcsstype%2Fdownload%2Fcsstype-2.6.19.tgz#feeb5aae89020bb389e1f63669a5ed490e391caa"
integrity sha512-ZVxXaNy28/k3kJg0Fou5MiYpp88j7H9hLZp8PDC3jV0WFjfH5E9xHb56L0W59cPbKbcHXeP4qyT8PrHp8t6LcQ==
dayjs@^1.11.2:
version "1.11.2"
resolved "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.2.tgz#fa0f5223ef0d6724b3d8327134890cfe3d72fbe5"
integrity sha512-F4LXf1OeU9hrSYRPTTj/6FbO4HTjPKXvEIC1P2kcnFurViINCVk3ZV0xAS3XVx9MkMsXbbqlK6hjseaYbgKEHw==
dayjs@^1.11.3:
version "1.11.3"
resolved "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.3.tgz#4754eb694a624057b9ad2224b67b15d552589258"
integrity sha512-xxwlswWOlGhzgQ4TKzASQkUhqERI3egRNqgV4ScR8wlANA/A9tZ7miXa44vTTKEq5l7vWoL5G57bG3zA+Kow0A==
debug@^4.1.1, debug@^4.3.1, debug@^4.3.2:
version "4.3.3"
@@ -624,28 +625,28 @@ dotenv@^10.0.0:
resolved "https://registry.nlark.com/dotenv/download/dotenv-10.0.0.tgz#3d4227b8fb95f81096cdd2b66653fb2c7085ba81"
integrity sha1-PUInuPuV+BCWzdK2ZlP7LHCFuoE=
echarts@^5.3.2:
version "5.3.2"
resolved "https://registry.npmmirror.com/echarts/-/echarts-5.3.2.tgz#0a7b3be8c48a48b2e7cb1b82121df0c208d42d2c"
integrity sha512-LWCt7ohOKdJqyiBJ0OGBmE9szLdfA9sGcsMEi+GGoc6+Xo75C+BkcT/6NNGRHAWtnQl2fNow05AQjznpap28TQ==
echarts@^5.3.3:
version "5.3.3"
resolved "https://registry.npmmirror.com/echarts/-/echarts-5.3.3.tgz#df97b09c4c0e2ffcdfb44acf518d50c50e0b838e"
integrity sha512-BRw2serInRwO5SIwRviZ6Xgm5Lb7irgz+sLiFMmy/HOaf4SQ+7oYqxKzRHAKp4xHQ05AuHw1xvoQWJjDQq/FGw==
dependencies:
tslib "2.3.0"
zrender "5.3.1"
zrender "5.3.2"
element-plus@^2.2.4:
version "2.2.4"
resolved "https://registry.npmmirror.com/element-plus/-/element-plus-2.2.4.tgz#f07f400222a5b0ae93ee9a139155342604746813"
integrity sha512-jktZr0o3ARDxWNWPEaJZQm2BN7thTpQl0aIfCUo5eB5m+zEap2DEcojyGKMHSQsCULcPM32NFfu2sHlhbhOiGA==
element-plus@^2.2.9:
version "2.2.9"
resolved "https://registry.npmmirror.com/element-plus/-/element-plus-2.2.9.tgz#f0366dfb2048d614813926274cb443f17e5fdef2"
integrity sha512-jYbL0JkCdv95rkT6trZJjCAizLPySa0qcd2cgq+57SKQnCZAcNDDq4GbTuFRnNavdoeCJnuM3HIficTIUpsMOQ==
dependencies:
"@ctrl/tinycolor" "^3.4.1"
"@element-plus/icons-vue" "^2.0.5"
"@floating-ui/dom" "^0.5.0"
"@element-plus/icons-vue" "^2.0.6"
"@floating-ui/dom" "^0.5.4"
"@popperjs/core" "npm:@sxzz/popperjs-es@^2.11.7"
"@types/lodash" "^4.14.182"
"@types/lodash-es" "^4.17.6"
"@vueuse/core" "^8.5.0"
async-validator "^4.1.1"
dayjs "^1.11.2"
"@vueuse/core" "^8.7.5"
async-validator "^4.2.5"
dayjs "^1.11.3"
escape-html "^1.0.3"
lodash "^4.17.21"
lodash-es "^4.17.21"
@@ -1201,12 +1202,12 @@ json-stable-stringify-without-jsonify@^1.0.1:
resolved "https://registry.nlark.com/json-stable-stringify-without-jsonify/download/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651"
integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=
jsoneditor@^9.8.0:
version "9.8.0"
resolved "https://registry.npmmirror.com/jsoneditor/-/jsoneditor-9.8.0.tgz#08db81ccf6f6e9fdff8691e42c4fb62d3efdd6ad"
integrity sha512-q1ekwYizbSAny0/UAEOzLviVCyBS5XFGwM/EUNf9KnfB1MRSDmJDWjt4lAqMVz1TUV5O/l3J4/WzUSLQh2tZjw==
jsoneditor@^9.9.0:
version "9.9.0"
resolved "https://registry.npmmirror.com/jsoneditor/-/jsoneditor-9.9.0.tgz#671e1231e23c43ebc6e1eb43fe97b2f97b156faf"
integrity sha512-NHJhyaqcc5U33ah6dEcd0S9b14Auocpe9nydvC9ui7Uq/vjEFnsd7ot6O9Jqwv53B7DmHFUWq5cT4qeWh4MEoA==
dependencies:
ace-builds "^1.5.3"
ace-builds "^1.6.0"
ajv "^6.12.6"
javascript-natural-sort "^0.7.1"
jmespath "^0.16.0"
@@ -1587,10 +1588,10 @@ sourcemap-codec@^1.4.4:
resolved "https://registry.npm.taobao.org/sourcemap-codec/download/sourcemap-codec-1.4.8.tgz#ea804bd94857402e6992d05a38ef1ae35a9ab4c4"
integrity sha1-6oBL2UhXQC5pktBaOO8a41qatMQ=
sql-formatter@^6.1.2:
version "6.1.2"
resolved "https://registry.npmmirror.com/sql-formatter/-/sql-formatter-6.1.2.tgz#78b05021c641020312a5f144ec313b38e7663258"
integrity sha512-09AiPmA6zDq82IBXOj5kN33VeAqaV92enkoonlhJge0fmfTESiYs3pwsntGKxa1C89xj/9MoHlNeqMmCr23BJw==
sql-formatter@^7.0.3:
version "7.0.3"
resolved "https://registry.npmmirror.com/sql-formatter/-/sql-formatter-7.0.3.tgz#6c78f1e550cfa8419fa6f50c2c6140178484c3a7"
integrity sha512-E9zotLB0dy9ZZhs1sY4ZqzSzJGF2uC4Vzj0mEzXJC9rlE+Jjmz6t64qT2dzm/IPQosYvZknDbBOrWkygIJz67A==
dependencies:
argparse "^2.0.1"
@@ -1664,10 +1665,10 @@ type-fest@^0.20.2:
resolved "https://registry.npmmirror.com/type-fest/download/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4"
integrity sha1-G/IH9LKPkVg2ZstfvTJ4hzAc1fQ=
typescript@^4.2.4:
version "4.5.4"
resolved "https://registry.npmmirror.com/typescript/download/typescript-4.5.4.tgz#a17d3a0263bf5c8723b9c52f43c5084edf13c2e8"
integrity sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==
typescript@^4.7.4:
version "4.7.4"
resolved "https://registry.npmmirror.com/typescript/-/typescript-4.7.4.tgz#1a88596d1cf47d59507a1bcdfb5b9dfe4d488235"
integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==
uri-js@^4.2.2:
version "4.4.1"
@@ -1688,10 +1689,10 @@ vanilla-picker@^2.12.1:
dependencies:
"@sphinxxxx/color-conversion" "^2.2.2"
vite@^2.9.10:
version "2.9.10"
resolved "https://registry.npmmirror.com/vite/-/vite-2.9.10.tgz#f574d96655622c2e0fbc662edd0ed199c60fe91a"
integrity sha512-TwZRuSMYjpTurLqXspct+HZE7ONiW9d+wSWgvADGxhDPPyoIcNywY+RX4ng+QpK30DCa1l/oZgi2PLZDibhzbQ==
vite@^2.9.13:
version "2.9.13"
resolved "https://registry.npmmirror.com/vite/-/vite-2.9.13.tgz#859cb5d4c316c0d8c6ec9866045c0f7858ca6abc"
integrity sha512-AsOBAaT0AD7Mhe8DuK+/kE4aWYFMx/i0ZNi98hJclxb4e0OhQcZYUrvLjIaQ8e59Ui7txcvKMiJC1yftqpQoDw==
dependencies:
esbuild "^0.14.27"
postcss "^8.4.13"
@@ -1725,10 +1726,10 @@ vue-eslint-parser@^8.0.1:
lodash "^4.17.21"
semver "^7.3.5"
vue-router@^4.0.15:
version "4.0.15"
resolved "https://registry.npmmirror.com/vue-router/-/vue-router-4.0.15.tgz#b4a0661efe197f8c724e0f233308f8776e2c3667"
integrity sha512-xa+pIN9ZqORdIW1MkN2+d9Ui2pCM1b/UMgwYUCZOiFYHAvz/slKKBDha8DLrh5aCG/RibtrpyhKjKOZ85tYyWg==
vue-router@^4.0.16:
version "4.0.16"
resolved "https://registry.npmmirror.com/vue-router/-/vue-router-4.0.16.tgz#9477beeeef36e80e04d041a1738801a55e6e862e"
integrity sha512-JcO7cb8QJLBWE+DfxGUL3xUDOae/8nhM1KVdnudadTAORbuxIC/xAydC5Zr/VLHUDQi1ppuTF5/rjBGzgzrJNA==
dependencies:
"@vue/devtools-api" "^6.0.0"
@@ -1772,19 +1773,19 @@ xterm-addon-fit@^0.5.0:
resolved "https://registry.npmmirror.com/xterm-addon-fit/download/xterm-addon-fit-0.5.0.tgz#2d51b983b786a97dcd6cde805e700c7f913bc596"
integrity sha1-LVG5g7eGqX3NbN6AXnAMf5E7xZY=
xterm@^4.18.0:
version "4.18.0"
resolved "https://registry.npmmirror.com/xterm/-/xterm-4.18.0.tgz#a1f6ab2c330c3918fb094ae5f4c2562987398ea1"
integrity sha512-JQoc1S0dti6SQfI0bK1AZvGnAxH4MVw45ZPFSO6FHTInAiau3Ix77fSxNx3mX4eh9OL4AYa8+4C8f5UvnSfppQ==
xterm@^4.19.0:
version "4.19.0"
resolved "https://registry.npmmirror.com/xterm/-/xterm-4.19.0.tgz#c0f9d09cd61de1d658f43ca75f992197add9ef6d"
integrity sha512-c3Cp4eOVsYY5Q839dR5IejghRPpxciGmLWWaP9g+ppfMeBChMeLa1DCA+pmX/jyDZ+zxFOmlJL/82qVdayVoGQ==
yallist@^4.0.0:
version "4.0.0"
resolved "https://registry.nlark.com/yallist/download/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
integrity sha1-m7knkNnA7/7GO+c1GeEaNQGaOnI=
zrender@5.3.1:
version "5.3.1"
resolved "https://registry.npmmirror.com/zrender/-/zrender-5.3.1.tgz#fa8e63ac7e719cfd563831fe8c42a9756c5af384"
integrity sha512-7olqIjy0gWfznKr6vgfnGBk7y4UtdMvdwFmK92vVQsQeDPyzkHW1OlrLEKg6GHz1W5ePf0FeN1q2vkl/HFqhXw==
zrender@5.3.2:
version "5.3.2"
resolved "https://registry.npmmirror.com/zrender/-/zrender-5.3.2.tgz#f67b11d36d3d020d62411d3bb123eb1c93cccd69"
integrity sha512-8IiYdfwHj2rx0UeIGZGGU4WEVSDEdeVCaIg/fomejg1Xu6OifAL1GVzIPHg2D+MyUkbNgPWji90t0a8IDk+39w==
dependencies:
tslib "2.3.0"

View File

@@ -1,6 +1,6 @@
app:
name: mayfly-go
version: 1.0.0
version: 1.2.0
server:
# debug release test
@@ -29,10 +29,6 @@ jwt:
# 过期时间单位分钟
expire-time: 1440
redis:
host: 127.0.0.1
port: 6379
mysql:
host: localhost:3306
username: root

View File

@@ -1,12 +1,13 @@
module mayfly-go
go 1.17
go 1.18
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // jwt
github.com/gin-gonic/gin v1.7.7
github.com/go-redis/redis v6.15.9+incompatible
github.com/gin-gonic/gin v1.8.1
github.com/go-redis/redis/v8 v8.11.5
github.com/gorilla/websocket v1.5.0
github.com/lib/pq v1.10.6
github.com/mojocn/base64Captcha v1.3.5 //
github.com/pkg/sftp v1.13.4
github.com/robfig/cron/v3 v3.0.1 //
@@ -21,14 +22,16 @@ require (
)
require (
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.10.1 // indirect
github.com/go-sql-driver/mysql v1.6.0 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/goccy/go-json v0.9.7 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
@@ -39,8 +42,7 @@ require (
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/onsi/ginkgo v1.16.5 // indirect
github.com/onsi/gomega v1.18.1 // indirect
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
@@ -48,9 +50,11 @@ require (
github.com/xdg-go/stringprep v1.0.2 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
golang.org/x/image v0.0.0-20220302094943-723b81ca9867 // indirect
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 // indirect
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.27.1 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

View File

@@ -2,7 +2,7 @@ package api
import (
"fmt"
"io/ioutil"
"io"
"mayfly-go/internal/devops/api/form"
"mayfly-go/internal/devops/api/vo"
"mayfly-go/internal/devops/application"
@@ -16,8 +16,10 @@ import (
"mayfly-go/pkg/ws"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/xwb1989/sqlparser"
)
type Db struct {
@@ -27,6 +29,8 @@ type Db struct {
ProjectApp application.Project
}
const DEFAULT_COLUMN_SIZE = 500
// @router /api/dbs [get]
func (d *Db) Dbs(rc *ctx.ReqCtx) {
g := rc.GinCtx
@@ -91,7 +95,7 @@ func (d *Db) ExecSql(rc *ctx.ReqCtx) {
rc.ReqParam = fmt.Sprintf("db: %d:%s | sql: %s", id, db, sql)
biz.NotEmpty(sql, "sql不能为空")
if strings.HasPrefix(sql, "SELECT") || strings.HasPrefix(sql, "select") || strings.HasPrefix(sql, "show") {
if strings.HasPrefix(sql, "SELECT") || strings.HasPrefix(sql, "select") || strings.HasPrefix(sql, "show") || strings.HasPrefix(sql, "explain") {
colNames, res, err := dbInstance.SelectData(sql)
biz.ErrIsNilAppendErr(err, "查询失败: %s")
colAndRes := make(map[string]interface{})
@@ -128,12 +132,8 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
fileheader, err := g.FormFile("file")
biz.ErrIsNilAppendErr(err, "读取sql文件失败: %s")
// 读取sql文件并根据;切割sql语句
file, _ := fileheader.Open()
filename := fileheader.Filename
bytes, _ := ioutil.ReadAll(file)
sqlContent := string(bytes)
sqls := strings.Split(sqlContent, ";")
dbId, db := GetIdAndDb(g)
go func() {
@@ -153,12 +153,14 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, db.ProjectId), "%s")
for _, sql := range sqls {
sql = strings.Trim(sql, " ")
if sql == "" || sql == "\n" {
continue
tokens := sqlparser.NewTokenizer(file)
for {
stmt, err := sqlparser.ParseNext(tokens)
if err == io.EOF {
break
}
_, err := db.Exec(sql)
sql := sqlparser.String(stmt)
_, err = db.Exec(sql)
if err != nil {
d.MsgApp.CreateAndSend(rc.LoginAccount, ws.ErrMsg("sql脚本执行失败", fmt.Sprintf("[%s]%s执行失败: [%s]", filename, dbInfo, err.Error())))
return
@@ -168,6 +170,96 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
}()
}
// 数据库dump
func (d *Db) DumpSql(rc *ctx.ReqCtx) {
g := rc.GinCtx
dbId, db := GetIdAndDb(g)
dumpType := g.Query("type")
tablesStr := g.Query("tables")
biz.NotEmpty(tablesStr, "请选择要导出的表")
tables := strings.Split(tablesStr, ",")
// 是否需要导出表结构
needStruct := dumpType == "1" || dumpType == "3"
// 是否需要导出数据
needData := dumpType == "2" || dumpType == "3"
dbInstance := d.DbApp.GetDbInstance(dbId, db)
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbInstance.ProjectId), "%s")
now := time.Now()
filename := fmt.Sprintf("%s.%s.sql", db, now.Format("200601021504"))
g.Header("Content-Type", "application/octet-stream")
g.Header("Content-Disposition", "attachment; filename="+filename)
rc.ReqParam = fmt.Sprintf("数据库id: %d -- %s", dbId, db)
writer := g.Writer
writer.WriteString("-- ----------------------------")
writer.WriteString("\n-- 导出平台: mayfly-go")
writer.WriteString(fmt.Sprintf("\n-- 导出时间: %s ", now.Format("2006-01-02 15:04:05")))
writer.WriteString(fmt.Sprintf("\n-- 导出数据库: %s ", db))
writer.WriteString("\n-- ----------------------------\n")
for _, table := range tables {
if needStruct {
writer.WriteString(fmt.Sprintf("\n-- ----------------------------\n-- 表结构: %s \n-- ----------------------------\n", table))
writer.WriteString(fmt.Sprintf("DROP TABLE IF EXISTS `%s`;\n", table))
writer.WriteString(dbInstance.GetCreateTableDdl(table)[0]["Create Table"].(string) + ";\n")
}
if !needData {
continue
}
writer.WriteString(fmt.Sprintf("\n-- ----------------------------\n-- 表记录: %s \n-- ----------------------------\n", table))
writer.WriteString("BEGIN;\n")
countSql := fmt.Sprintf("SELECT COUNT(*) count FROM %s", table)
_, countRes, _ := dbInstance.SelectData(countSql)
// 查询出所有列信息总数,手动分页获取所有数据
maCount := int(countRes[0]["count"].(int64))
// 计算需要查询的页数
pageNum := maCount / DEFAULT_COLUMN_SIZE
if maCount%DEFAULT_COLUMN_SIZE > 0 {
pageNum++
}
var sqlTmp string
switch dbInstance.Type {
case "mysql":
sqlTmp = "SELECT * FROM %s LIMIT %d, %d"
case "postgres":
sqlTmp = "SELECT * FROM %s OFFSET %d LIMIT %d"
}
for index := 0; index < pageNum; index++ {
sql := fmt.Sprintf(sqlTmp, table, index*DEFAULT_COLUMN_SIZE, DEFAULT_COLUMN_SIZE)
columns, result, _ := dbInstance.SelectData(sql)
insertSql := "INSERT INTO `%s` VALUES (%s);\n"
for _, res := range result {
var values []string
for _, column := range columns {
value := res[column]
if value == nil {
values = append(values, "NULL")
continue
}
strValue, ok := value.(string)
if ok {
values = append(values, fmt.Sprintf("%#v", strValue))
} else {
values = append(values, utils.ToString(value))
}
}
writer.WriteString(fmt.Sprintf(insertSql, table, strings.Join(values, ", ")))
}
}
writer.WriteString("COMMIT;\n")
}
rc.NoRes = true
}
// @router /api/db/:dbId/t-metadata [get]
func (d *Db) TableMA(rc *ctx.ReqCtx) {
dbi := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx))
@@ -217,7 +309,7 @@ func (d *Db) HintTables(rc *ctx.ReqCtx) {
columnName := fmt.Sprintf("%s [%s]", v["columnName"], v["columnType"])
comment := v["columnComment"]
// 如果字段备注不为空,则加上备注信息
if comment != "" {
if comment != nil && comment != "" {
columnName = fmt.Sprintf("%s[%s]", columnName, comment)
}

View File

@@ -8,6 +8,7 @@ type DbForm struct {
Port int `binding:"required" json:"port"`
Username string `binding:"required" json:"username"`
Password string `json:"password"`
Params string `json:"params"`
Database string `binding:"required" json:"database"`
ProjectId uint64 `binding:"required" json:"projectId"`
Project string `json:"project"`
@@ -15,6 +16,13 @@ type DbForm struct {
EnvId uint64 `binding:"required" json:"envId"`
}
type DbSqlSaveForm struct {
Name string
Sql string `binding:"required"`
Type int `binding:"required"`
Db string `binding:"required"`
}
// 数据库SQL执行表单
type DbSqlExecForm struct {
Db string `binding:"required" json:"db"` //数据库名

View File

@@ -38,11 +38,9 @@ type MachineScriptForm struct {
Script string `binding:"required"`
}
type DbSqlSaveForm struct {
Name string
Sql string `binding:"required"`
Type int `binding:"required"`
Db string `binding:"required"`
type MachineCreateFileForm struct {
Path string `binding:"required"`
Type string `binding:"required"`
}
type MachineFileUpdateForm struct {

View File

@@ -4,6 +4,7 @@ type Redis struct {
Id uint64
Host string `binding:"required" json:"host"`
Password string `json:"password"`
Mode string `json:"mode"`
Db int `json:"db"`
ProjectId uint64 `binding:"required" json:"projectId"`
Project string `json:"project"`
@@ -30,3 +31,9 @@ type SetValue struct {
KeyInfo
Value []interface{} `binding:"required" json:"value"`
}
type RedisScanForm struct {
Cursor map[string]uint64 `json:"cursor"`
Match string `json:"match"`
Count int64 `json:"count"`
}

View File

@@ -60,6 +60,22 @@ func (m *MachineFile) DeleteFile(rc *ctx.ReqCtx) {
/*** sftp相关操作 */
func (m *MachineFile) CreateFile(rc *ctx.ReqCtx) {
g := rc.GinCtx
fid := GetMachineFileId(g)
form := new(form.MachineCreateFileForm)
ginx.BindJsonAndValid(g, form)
path := form.Path
if form.Type == dir {
m.MachineFileApp.MkDir(fid, form.Path)
} else {
m.MachineFileApp.CreateFile(fid, form.Path)
}
rc.ReqParam = fmt.Sprintf("path: %s, type: %s", path, form.Type)
}
func (m *MachineFile) ReadFileContent(rc *ctx.ReqCtx) {
g := rc.GinCtx
fid := GetMachineFileId(g)
@@ -104,6 +120,7 @@ func (m *MachineFile) GetDirEntry(rc *ctx.ReqCtx) {
Size: fi.Size(),
Path: readPath + fi.Name(),
Type: getFileType(fi.Mode()),
Mode: fi.Mode().String(),
})
}
rc.ResData = fisVO
@@ -155,7 +172,6 @@ func (m *MachineFile) UploadFile(rc *ctx.ReqCtx) {
func (m *MachineFile) RemoveFile(rc *ctx.ReqCtx) {
g := rc.GinCtx
fid := GetMachineFileId(g)
// mid := GetMachineId(g)
path := g.Query("path")
m.MachineFileApp.RemoveFile(fid, path)
@@ -167,7 +183,10 @@ func getFileType(fm fs.FileMode) string {
if fm.IsDir() {
return dir
}
return file
if fm.IsRegular() {
return file
}
return dir
}
func GetMachineFileId(g *gin.Context) uint64 {

View File

@@ -1,6 +1,7 @@
package api
import (
"context"
"mayfly-go/internal/devops/api/form"
"mayfly-go/internal/devops/api/vo"
"mayfly-go/internal/devops/application"
@@ -11,7 +12,10 @@ import (
"mayfly-go/pkg/utils"
"strconv"
"strings"
"sync"
"time"
"github.com/go-redis/redis/v8"
)
type Redis struct {
@@ -45,7 +49,40 @@ func (r *Redis) DeleteRedis(rc *ctx.ReqCtx) {
}
func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
res, _ := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(rc.GinCtx, "id"))).Cli.Info().Result()
ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(rc.GinCtx, "id")))
var res string
var err error
ctx := context.Background()
if ri.Mode == "" || ri.Mode == entity.RedisModeStandalone {
res, err = ri.Cli.Info(ctx).Result()
} else if ri.Mode == entity.RedisModeCluster {
host := rc.GinCtx.Query("host")
biz.NotEmpty(host, "集群模式host信息不能为空")
clusterClient := ri.ClusterCli
var redisClient *redis.Client
// 遍历集群的master节点找到该redis client
clusterClient.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error {
if host == client.Options().Addr {
redisClient = client
}
return nil
})
if redisClient == nil {
// 遍历集群的slave节点找到该redis client
clusterClient.ForEachSlave(ctx, func(ctx context.Context, client *redis.Client) error {
if host == client.Options().Addr {
redisClient = client
}
return nil
})
}
biz.NotNil(redisClient, "该实例不在该集群中")
res, err = redisClient.Info(ctx).Result()
}
biz.ErrIsNilAppendErr(err, "获取redis info失败: %s")
datas := strings.Split(res, "\r\n")
i := 0
@@ -81,43 +118,125 @@ func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
rc.ResData = parseMap
}
func (r *Redis) ClusterInfo(rc *ctx.ReqCtx) {
g := rc.GinCtx
ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
biz.IsEquals(ri.Mode, entity.RedisModeCluster, "非集群模式")
info, _ := ri.ClusterCli.ClusterInfo(context.Background()).Result()
nodesStr, _ := ri.ClusterCli.ClusterNodes(context.Background()).Result()
nodesRes := make([]map[string]string, 0)
nodes := strings.Split(nodesStr, "\n")
for _, node := range nodes {
if node == "" {
continue
}
nodeInfos := strings.Split(node, " ")
node := make(map[string]string)
node["nodeId"] = nodeInfos[0]
// ip:port1@port2port1指redis服务器与客户端通信的端口port2则是集群内部节点间通信的端口
node["ip"] = nodeInfos[1]
node["flags"] = nodeInfos[2]
// 如果节点是slave并且已知master节点则为master节点ID否则为符号"-"
node["masterSlaveRelation"] = nodeInfos[3]
// 最近一次发送ping的时间这个时间是一个unix毫秒时间戳0代表没有发送过
node["pingSent"] = nodeInfos[4]
// 最近一次收到pong的时间使用unix时间戳表示
node["pongRecv"] = nodeInfos[5]
// 节点的epoch值如果该节点是从节点则为其主节点的epoch值。每当节点发生失败切换时都会创建一个新的独特的递增的epoch。
// 如果多个节点竞争同一个哈希槽时epoch值更高的节点会抢夺到
node["configEpoch"] = nodeInfos[6]
// node-to-node集群总线使用的链接的状态我们使用这个链接与集群中其他节点进行通信.值可以是 connected 和 disconnected
node["linkState"] = nodeInfos[7]
// slave节点没有插槽信息
if len(nodeInfos) > 8 {
// slotmaster节点第9位为哈希槽值或者一个哈希槽范围代表当前节点可以提供服务的所有哈希槽值。如果只是一个值,那就是只有一个槽会被使用。
// 如果是一个范围,这个值表示为起始槽-结束槽,节点将处理包括起始槽和结束槽在内的所有哈希槽。
node["slot"] = nodeInfos[8]
}
nodesRes = append(nodesRes, node)
}
rc.ResData = map[string]interface{}{
"clusterInfo": info,
"clusterNodes": nodesRes,
}
}
// scan获取redis的key列表信息
func (r *Redis) Scan(rc *ctx.ReqCtx) {
g := rc.GinCtx
ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
keys, cursor := ri.Scan(uint64(ginx.PathParamInt(g, "cursor")), g.Query("match"), int64(ginx.PathParamInt(g, "count")))
form := &form.RedisScanForm{}
ginx.BindJsonAndValid(rc.GinCtx, form)
var keyInfoSplit []string
if len(keys) > 0 {
keyInfoLua := `
local result = {}
-- KEYS[1]为第1个参数lua数组下标从1开始
local ttl = redis.call('ttl', KEYS[1]);
local keyType = redis.call('type', KEYS[1]);
for i = 1, #KEYS do
local ttl = redis.call('ttl', KEYS[i]);
local keyType = redis.call('type', KEYS[i]);
table.insert(result, string.format("%d,%s", ttl, keyType['ok']));
end;
return table.concat(result, ".");`
// 通过lua获取 ttl,type.ttl2,type2格式以便下面切割获取ttl和type。避免多次调用ttl和type函数
keyInfos, _ := ri.Cli.Eval(keyInfoLua, keys).Result()
keyInfoSplit = strings.Split(keyInfos.(string), ".")
}
cmd := ri.GetCmdable()
ctx := context.Background()
kis := make([]*vo.KeyInfo, 0)
for i, k := range keys {
ttlType := strings.Split(keyInfoSplit[i], ",")
ttl, _ := strconv.Atoi(ttlType[0])
ki := &vo.KeyInfo{Key: k, Type: ttlType[1], Ttl: int64(ttl)}
kis = append(kis, ki)
var cursorRes map[string]uint64 = make(map[string]uint64)
if ri.Mode == "" || ri.Mode == entity.RedisModeStandalone {
redisAddr := ri.Cli.Options().Addr
keys, cursor := ri.Scan(form.Cursor[redisAddr], form.Match, form.Count)
cursorRes[redisAddr] = cursor
var keyInfoSplit []string
if len(keys) > 0 {
keyInfosLua := `local result = {}
-- KEYS[1]为第1个参数,lua数组下标从1开始
for i = 1, #KEYS do
local ttl = redis.call('ttl', KEYS[i]);
local keyType = redis.call('type', KEYS[i]);
table.insert(result, string.format("%d,%s", ttl, keyType['ok']));
end;
return table.concat(result, ".");`
// 通过lua获取 ttl,type.ttl2,type2格式以便下面切割获取ttl和type。避免多次调用ttl和type函数
keyInfos, err := cmd.Eval(ctx, keyInfosLua, keys).Result()
biz.ErrIsNilAppendErr(err, "执行lua脚本获取key信息失败: %s")
keyInfoSplit = strings.Split(keyInfos.(string), ".")
}
for i, k := range keys {
ttlType := strings.Split(keyInfoSplit[i], ",")
ttl, _ := strconv.Atoi(ttlType[0])
ki := &vo.KeyInfo{Key: k, Type: ttlType[1], Ttl: int64(ttl)}
kis = append(kis, ki)
}
} else if ri.Mode == entity.RedisModeCluster {
var keys []string
mu := &sync.Mutex{}
// 遍历所有master节点并执行scan命令合并keys
ri.ClusterCli.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error {
redisAddr := client.Options().Addr
ks, cursor, _ := client.Scan(ctx, form.Cursor[redisAddr], form.Match, form.Count).Result()
// 遍历节点的内部回调函数使用异步调用,如不加锁会导致集合并发错误
mu.Lock()
cursorRes[redisAddr] = cursor
keys = append(keys, ks...)
mu.Unlock()
return nil
})
// 因为redis集群模式执行lua脚本key必须位于同一slot中故单机获取的方式不适合
// 使用lua获取key的ttl以及类型减少网络调用
keyInfoLua := `local ttl = redis.call('ttl', KEYS[1]);
local keyType = redis.call('type', KEYS[1]);
return string.format("%d,%s", ttl, keyType['ok'])`
for _, k := range keys {
keyInfo, err := cmd.Eval(ctx, keyInfoLua, []string{k}).Result()
biz.ErrIsNilAppendErr(err, "执行lua脚本获取key信息失败: %s")
ttlType := strings.Split(keyInfo.(string), ",")
ttl, _ := strconv.Atoi(ttlType[0])
ki := &vo.KeyInfo{Key: k, Type: ttlType[1], Ttl: int64(ttl)}
kis = append(kis, ki)
}
}
size, _ := ri.Cli.DBSize().Result()
rc.ResData = &vo.Keys{Cursor: cursor, Keys: kis, DbSize: size}
size, _ := cmd.DBSize(context.TODO()).Result()
rc.ResData = &vo.Keys{Cursor: cursorRes, Keys: kis, DbSize: size}
}
func (r *Redis) DeleteKey(rc *ctx.ReqCtx) {
@@ -129,7 +248,7 @@ func (r *Redis) DeleteKey(rc *ctx.ReqCtx) {
biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
rc.ReqParam = key
ri.Cli.Del(key)
ri.GetCmdable().Del(context.Background(), key)
}
func (r *Redis) checkKey(rc *ctx.ReqCtx) (*application.RedisInstance, string) {
@@ -145,14 +264,14 @@ func (r *Redis) checkKey(rc *ctx.ReqCtx) (*application.RedisInstance, string) {
func (r *Redis) GetStringValue(rc *ctx.ReqCtx) {
ri, key := r.checkKey(rc)
str, err := ri.Cli.Get(key).Result()
str, err := ri.GetCmdable().Get(context.TODO(), key).Result()
biz.ErrIsNilAppendErr(err, "获取字符串值失败: %s")
rc.ResData = str
}
func (r *Redis) GetHashValue(rc *ctx.ReqCtx) {
ri, key := r.checkKey(rc)
res, err := ri.Cli.HGetAll(key).Result()
res, err := ri.GetCmdable().HGetAll(context.TODO(), key).Result()
biz.ErrIsNilAppendErr(err, "获取hash值失败: %s")
rc.ResData = res
}
@@ -165,7 +284,7 @@ func (r *Redis) SetStringValue(rc *ctx.ReqCtx) {
ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
str, err := ri.Cli.Set(keyValue.Key, keyValue.Value, time.Second*time.Duration(keyValue.Timed)).Result()
str, err := ri.GetCmdable().Set(context.TODO(), keyValue.Key, keyValue.Value, time.Second*time.Duration(keyValue.Timed)).Result()
biz.ErrIsNilAppendErr(err, "保存字符串值失败: %s")
rc.ResData = str
}
@@ -178,21 +297,22 @@ func (r *Redis) SetHashValue(rc *ctx.ReqCtx) {
ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
cmd := ri.GetCmdable()
key := hashValue.Key
// 简单处理->先删除,后新增
ri.Cli.Del(key)
cmd.Del(context.TODO(), key)
for _, v := range hashValue.Value {
res := ri.Cli.HSet(key, v["key"].(string), v["value"])
res := cmd.HSet(context.TODO(), key, v["key"].(string), v["value"])
biz.ErrIsNilAppendErr(res.Err(), "保存hash值失败: %s")
}
if hashValue.Timed != -1 {
ri.Cli.Expire(key, time.Second*time.Duration(hashValue.Timed))
cmd.Expire(context.TODO(), key, time.Second*time.Duration(hashValue.Timed))
}
}
func (r *Redis) GetSetValue(rc *ctx.ReqCtx) {
ri, key := r.checkKey(rc)
res, err := ri.Cli.SMembers(key).Result()
res, err := ri.GetCmdable().SMembers(context.TODO(), key).Result()
biz.ErrIsNilAppendErr(err, "获取set值失败: %s")
rc.ResData = res
}
@@ -204,13 +324,14 @@ func (r *Redis) SetSetValue(rc *ctx.ReqCtx) {
ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
cmd := ri.GetCmdable()
key := keyvalue.Key
// 简单处理->先删除,后新增
ri.Cli.Del(key)
ri.Cli.SAdd(key, keyvalue.Value...)
cmd.Del(context.TODO(), key)
cmd.SAdd(context.TODO(), key, keyvalue.Value...)
if keyvalue.Timed != -1 {
ri.Cli.Expire(key, time.Second*time.Duration(keyvalue.Timed))
cmd.Expire(context.TODO(), key, time.Second*time.Duration(keyvalue.Timed))
}
}

View File

@@ -9,6 +9,7 @@ type SelectDataDbVO struct {
Host *string `json:"host"`
Port *int `json:"port"`
Type *string `json:"type"`
Params *string `json:"params"`
Database *string `json:"database"`
Username *string `json:"username"`
ProjectId *int64 `json:"projectId"`

View File

@@ -9,6 +9,8 @@ type Redis struct {
Db int `json:"db"`
ProjectId *int64 `json:"projectId"`
Project *string `json:"project"`
Mode *string `json:"mode"`
Remark *string `json:"remark"`
Env *string `json:"env"`
EnvId *int64 `json:"envId"`
CreateTime *time.Time `json:"createTime"`
@@ -17,9 +19,9 @@ type Redis struct {
}
type Keys struct {
Cursor uint64 `json:"cursor"`
Keys []*KeyInfo `json:"keys"`
DbSize int64 `json:"dbSize"`
Cursor map[string]uint64 `json:"cursor"`
Keys []*KeyInfo `json:"keys"`
DbSize int64 `json:"dbSize"`
}
type KeyInfo struct {

View File

@@ -56,6 +56,7 @@ type MachineFileInfo struct {
Path string `json:"path"`
Size int64 `json:"size"`
Type string `json:"type"`
Mode string `json:"mode"`
}
type RoleVO struct {

View File

@@ -17,6 +17,8 @@ import (
"strings"
"sync"
"time"
_ "github.com/lib/pq"
)
type Db interface {
@@ -223,14 +225,11 @@ func (d *DbInstance) SelectData(execSql string) ([]string, []map[string]interfac
execSql = strings.Trim(execSql, " ")
isSelect := strings.HasPrefix(execSql, "SELECT") || strings.HasPrefix(execSql, "select")
isShow := strings.HasPrefix(execSql, "show")
isExplain := strings.HasPrefix(execSql, "explain")
if !isSelect && !isShow {
if !isSelect && !isShow && !isExplain {
return nil, nil, errors.New("该sql非查询语句")
}
// 没加limit则默认限制50条
if isSelect && !strings.Contains(execSql, "limit") && !strings.Contains(execSql, "LIMIT") {
execSql = execSql + " LIMIT 50"
}
rows, err := d.db.Query(execSql)
if err != nil {
@@ -272,14 +271,13 @@ func (d *DbInstance) SelectData(execSql string) ([]string, []map[string]interfac
colName := colType.Name()
// 字段类型名
colScanType := colType.ScanType().Name()
// 如果是密码字段,则脱敏显示
if colName == "password" {
v = []byte("******")
}
if isFirst {
colNames = append(colNames, colName)
}
if v == nil {
rowData[colName] = nil
continue
}
// 这里把[]byte数据转成string
stringV := string(v)
if stringV == "" {
@@ -335,8 +333,21 @@ func (d *DbInstance) Close() {
// 获取dataSourceName
func getDsn(d *entity.Db) string {
var dsn string
if d.Type == "mysql" {
return fmt.Sprintf("%s:%s@%s(%s:%d)/%s?timeout=8s", d.Username, d.Password, d.Network, d.Host, d.Port, d.Database)
dsn = fmt.Sprintf("%s:%s@%s(%s:%d)/%s?timeout=8s", d.Username, d.Password, d.Network, d.Host, d.Port, d.Database)
if d.Params != "" {
dsn = fmt.Sprintf("%s&%s", dsn, d.Params)
}
return dsn
}
if d.Type == "postgres" {
dsn = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", d.Host, d.Port, d.Username, d.Password, d.Database)
if d.Params != "" {
dsn = fmt.Sprintf("%s %s", dsn, strings.Join(strings.Split(d.Params, "&"), " "))
}
return dsn
}
return ""
}
@@ -352,37 +363,85 @@ const (
// mysql 表信息元数据
MYSQL_TABLE_MA = `SELECT table_name tableName, engine, table_comment tableComment,
create_time createTime from information_schema.tables
WHERE table_schema = (SELECT database())`
WHERE table_schema = (SELECT database()) LIMIT 2000`
// mysql 表信息
MYSQL_TABLE_INFO = `SELECT table_name tableName, table_comment tableComment, table_rows tableRows,
data_length dataLength, index_length indexLength, create_time createTime
FROM information_schema.tables
WHERE table_schema = (SELECT database())`
WHERE table_schema = (SELECT database()) LIMIT 2000`
// mysql 索引信息
MYSQL_INDEX_INFO = `SELECT index_name indexName, column_name columnName, index_type indexType,
SEQ_IN_INDEX seqInIndex, INDEX_COMMENT indexComment
FROM information_schema.STATISTICS
WHERE table_schema = (SELECT database()) AND table_name = '%s'`
WHERE table_schema = (SELECT database()) AND table_name = '%s' LIMIT 500`
// 默认每次查询列元信息数量
DEFAULT_COLUMN_SIZE = 2000
// mysql 列信息元数据
MYSQL_COLOUMN_MA = `SELECT table_name tableName, column_name columnName, column_type columnType,
MYSQL_COLUMN_MA = `SELECT table_name tableName, column_name columnName, column_type columnType,
column_comment columnComment, column_key columnKey, extra, is_nullable nullable from information_schema.columns
WHERE table_name in (%s) AND table_schema = (SELECT database()) ORDER BY tableName, ordinal_position limit %d, %d`
WHERE table_name in (%s) AND table_schema = (SELECT database()) ORDER BY tableName, ordinal_position LIMIT %d, %d`
// mysql 列信息元数据总数
MYSQL_COLOUMN_MA_COUNT = `SELECT COUNT(*) maNum from information_schema.columns
WHERE table_name in (%s) AND table_schema = (SELECT database())`
)
const (
// postgres 表信息元数据
PGSQL_TABLE_MA = `SELECT obj_description(c.oid) AS "tableComment", c.relname AS "tableName" FROM pg_class c
JOIN pg_namespace n ON c.relnamespace = n.oid WHERE n.nspname = (select current_schema()) AND c.reltype > 0`
PGSQL_TABLE_INFO = `SELECT obj_description(c.oid) AS "tableComment", c.relname AS "tableName" FROM pg_class c
JOIN pg_namespace n ON c.relnamespace = n.oid WHERE n.nspname = (select current_schema()) AND c.reltype > 0`
PGSQL_INDEX_INFO = `SELECT indexname AS "indexName", indexdef AS "indexComment"
FROM pg_indexes WHERE schemaname = (select current_schema()) AND tablename = '%s'`
PGSQL_COLUMN_MA = `SELECT
C.relname AS "tableName",
A.attname AS "columnName",
concat_ws ( '', t.typname, SUBSTRING ( format_type ( a.atttypid, a.atttypmod ) FROM '\(.*\)' ) ) AS "columnType",
d.description AS "columnComment"
FROM
pg_attribute a LEFT JOIN pg_description d ON d.objoid = a.attrelid
AND d.objsubid = A.attnum
LEFT JOIN pg_class c ON A.attrelid = c.oid
LEFT JOIN pg_namespace pn ON c.relnamespace = pn.oid
LEFT JOIN pg_type t ON a.atttypid = t.oid
WHERE
A.attnum >= 0
AND pn.nspname = (select current_schema())
AND C.relname in (%s)
ORDER BY
C.relname DESC,
A.attnum ASC
OFFSET %d LIMIT %d
`
PGSQL_COLUMN_MA_COUNT = `SELECT COUNT(*) "maNum"
FROM
pg_attribute a LEFT JOIN pg_description d ON d.objoid = a.attrelid
AND d.objsubid = A.attnum
LEFT JOIN pg_class c ON A.attrelid = c.oid
LEFT JOIN pg_namespace pn ON c.relnamespace = pn.oid
LEFT JOIN pg_type t ON a.atttypid = t.oid
WHERE
A.attnum >= 0
AND pn.nspname = (select current_schema())
AND C.relname in (%s)
`
)
func (d *DbInstance) GetTableMetedatas() []map[string]interface{} {
var sql string
if d.Type == "mysql" {
sql = MYSQL_TABLE_MA
} else if d.Type == "postgres" {
sql = PGSQL_TABLE_MA
}
_, res, _ := d.SelectData(sql)
return res
@@ -401,7 +460,10 @@ func (d *DbInstance) GetColumnMetadatas(tableNames ...string) []map[string]inter
var sqlTmp string
if d.Type == "mysql" {
countSqlTmp = MYSQL_COLOUMN_MA_COUNT
sqlTmp = MYSQL_COLOUMN_MA
sqlTmp = MYSQL_COLUMN_MA
} else if d.Type == "postgres" {
countSqlTmp = PGSQL_COLUMN_MA_COUNT
sqlTmp = PGSQL_COLUMN_MA
}
countSql := fmt.Sprintf(countSqlTmp, tableName)
@@ -433,6 +495,8 @@ func (d *DbInstance) GetTableInfos() []map[string]interface{} {
var sql string
if d.Type == "mysql" {
sql = MYSQL_TABLE_INFO
} else if d.Type == "postgres" {
sql = PGSQL_TABLE_INFO
}
_, res, _ := d.SelectData(sql)
return res
@@ -442,6 +506,8 @@ func (d *DbInstance) GetTableIndex(tableName string) []map[string]interface{} {
var sql string
if d.Type == "mysql" {
sql = fmt.Sprintf(MYSQL_INDEX_INFO, tableName)
} else if d.Type == "postgres" {
sql = fmt.Sprintf(PGSQL_INDEX_INFO, tableName)
}
_, res, _ := d.SelectData(sql)
return res

View File

@@ -1,6 +1,7 @@
package application
import (
"fmt"
"io"
"io/fs"
"mayfly-go/internal/devops/domain/entity"
@@ -30,6 +31,12 @@ type MachineFile interface {
/** sftp 相关操作 **/
// 创建目录
MkDir(fid uint64, path string)
// 创建文件
CreateFile(fid uint64, path string)
// 读取目录
ReadDir(fid uint64, path string) []fs.FileInfo
@@ -100,6 +107,25 @@ func (m *machineFileAppImpl) ReadDir(fid uint64, path string) []fs.FileInfo {
return fis
}
func (m *machineFileAppImpl) MkDir(fid uint64, path string) {
path, machineId := m.checkAndReturnPathMid(fid, path)
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
sftpCli := m.getSftpCli(machineId)
err := sftpCli.Mkdir(path)
biz.ErrIsNilAppendErr(err, "创建目录失败: %s")
}
func (m *machineFileAppImpl) CreateFile(fid uint64, path string) {
path, machineId := m.checkAndReturnPathMid(fid, path)
sftpCli := m.getSftpCli(machineId)
file, err := sftpCli.Create(path)
biz.ErrIsNilAppendErr(err, "创建文件失败: %s")
defer file.Close()
}
func (m *machineFileAppImpl) ReadFile(fileId uint64, path string) *sftp.File {
path, machineId := m.checkAndReturnPathMid(fileId, path)
sftpCli := m.getSftpCli(machineId)
@@ -148,6 +174,11 @@ func (m *machineFileAppImpl) RemoveFile(fileId uint64, path string) {
fi, _ := file.Stat()
if fi.IsDir() {
err = sftpCli.RemoveDirectory(path)
// 如果文件夹有内容会删除失败则使用rm -rf命令删除
if err != nil {
MachineApp.GetCli(machineId).Run(fmt.Sprintf("rm -rf %s", path))
err = nil
}
} else {
err = sftpCli.Remove(path)
}

View File

@@ -1,6 +1,7 @@
package application
import (
"context"
"fmt"
"mayfly-go/internal/devops/domain/entity"
"mayfly-go/internal/devops/domain/repository"
@@ -9,9 +10,10 @@ import (
"mayfly-go/pkg/cache"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/go-redis/redis/v8"
)
type Redis interface {
@@ -102,24 +104,53 @@ func (r *redisAppImpl) GetRedisInstance(id uint64) *RedisInstance {
// 缓存不存在则回调获取redis信息
re := r.GetById(id)
biz.NotNil(re, "redis信息不存在")
redisMode := re.Mode
ri := &RedisInstance{Id: id, ProjectId: re.ProjectId, Mode: redisMode}
if redisMode == "" || redisMode == entity.RedisModeStandalone {
rcli := getRedisCient(re)
// 测试连接
_, e := rcli.Ping(context.Background()).Result()
if e != nil {
rcli.Close()
panic(biz.NewBizErr(fmt.Sprintf("redis连接失败: %s", e.Error())))
}
ri.Cli = rcli
} else if redisMode == entity.RedisModeCluster {
ccli := getRedisClusterClient(re)
// 测试连接
_, e := ccli.Ping(context.Background()).Result()
if e != nil {
ccli.Close()
panic(biz.NewBizErr(fmt.Sprintf("redis集群连接失败: %s", e.Error())))
}
ri.ClusterCli = ccli
}
global.Log.Infof("连接redis: %s", re.Host)
rcli := redis.NewClient(&redis.Options{
Addr: re.Host,
Password: re.Password, // no password set
DB: re.Db, // use default DB
})
// 测试连接
_, e := rcli.Ping().Result()
biz.ErrIsNilAppendErr(e, "redis连接失败: %s")
ri := &RedisInstance{Id: id, ProjectId: re.ProjectId, Cli: rcli}
if needCache {
redisCache.Put(re.Id, ri)
}
return ri
}
func getRedisCient(re *entity.Redis) *redis.Client {
return redis.NewClient(&redis.Options{
Addr: re.Host,
Password: re.Password, // no password set
DB: re.Db, // use default DB
DialTimeout: 8 * time.Second,
})
}
func getRedisClusterClient(re *entity.Redis) *redis.ClusterClient {
return redis.NewClusterClient(&redis.ClusterOptions{
Addrs: strings.Split(re.Host, ","),
Password: re.Password,
DialTimeout: 8 * time.Second,
})
}
//------------------------------------------------------------------------------
// redis客户端连接缓存30分钟内没有访问则会被关闭
@@ -127,35 +158,64 @@ var redisCache = cache.NewTimedCache(30*time.Minute, 5*time.Second).
WithUpdateAccessTime(true).
OnEvicted(func(key interface{}, value interface{}) {
global.Log.Info(fmt.Sprintf("删除redis连接缓存 id = %d", key))
value.(*RedisInstance).Cli.Close()
value.(*RedisInstance).Close()
})
// redis实例
type RedisInstance struct {
Id uint64
ProjectId uint64
Cli *redis.Client
}
// 移除redis连接缓存并关闭redis连接
func CloseRedis(id uint64) {
redisCache.Delete(id)
}
func TestRedisConnection(re *entity.Redis) {
rcli := redis.NewClient(&redis.Options{
Addr: re.Host,
Password: re.Password, // no password set
DB: re.Db, // use default DB
})
defer rcli.Close()
var cmd redis.Cmdable
if re.Mode == "" || re.Mode == entity.RedisModeStandalone {
rcli := getRedisCient(re)
defer rcli.Close()
cmd = rcli
} else if re.Mode == entity.RedisModeCluster {
ccli := getRedisClusterClient(re)
defer ccli.Close()
cmd = ccli
}
// 测试连接
_, e := rcli.Ping().Result()
_, e := cmd.Ping(context.Background()).Result()
biz.ErrIsNilAppendErr(e, "Redis连接失败: %s")
}
// redis实例
type RedisInstance struct {
Id uint64
ProjectId uint64
Mode string
Cli *redis.Client
ClusterCli *redis.ClusterClient
}
// 获取命令执行接口的具体实现
func (r *RedisInstance) GetCmdable() redis.Cmdable {
redisMode := r.Mode
if redisMode == "" || redisMode == entity.RedisModeStandalone {
return r.Cli
}
if r.Mode == entity.RedisModeCluster {
return r.ClusterCli
}
return nil
}
func (r *RedisInstance) Scan(cursor uint64, match string, count int64) ([]string, uint64) {
keys, newcursor, err := r.Cli.Scan(cursor, match, count).Result()
keys, newcursor, err := r.GetCmdable().Scan(context.Background(), cursor, match, count).Result()
biz.ErrIsNilAppendErr(err, "scan失败: %s")
return keys, newcursor
}
func (r *RedisInstance) Close() {
if r.Mode == entity.RedisModeStandalone {
r.Cli.Close()
return
}
if r.Mode == entity.RedisModeCluster {
r.ClusterCli.Close()
}
}

View File

@@ -15,6 +15,7 @@ type Db struct {
Username string `orm:"column(username)" json:"username"`
Password string `orm:"column(password)" json:"-"`
Database string `orm:"column(database)" json:"database"`
Params string `json:"params"`
ProjectId uint64
Project string
EnvId uint64

View File

@@ -8,10 +8,17 @@ type Redis struct {
model.Model
Host string `orm:"column(host)" json:"host"`
Mode string `json:"mode"`
Password string `orm:"column(password)" json:"-"`
Db int `orm:"column(database)" json:"db"`
Remark string
ProjectId uint64
Project string
EnvId uint64
Env string
}
const (
RedisModeStandalone = "standalone"
RedisModeCluster = "cluster"
)

View File

@@ -61,6 +61,12 @@ func InitDbRouter(router *gin.RouterGroup) {
rc.Handle(d.ExecSqlFile)
})
db.GET(":dbId/dump", func(g *gin.Context) {
ctx.NewReqCtxWithGin(g).
WithLog(ctx.NewLogInfo("Sql文件dump")).
Handle(d.DumpSql)
})
db.GET(":dbId/t-metadata", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(d.TableMA)
})

View File

@@ -43,14 +43,14 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
getContent := ctx.NewLogInfo("读取机器文件内容")
machineFile.GET(":machineId/files/:fileId/read", func(c *gin.Context) {
rc := ctx.NewReqCtxWithGin(c).WithLog(getContent)
rc.Handle(mf.ReadFileContent)
ctx.NewReqCtxWithGin(c).WithLog(getContent).
Handle(mf.ReadFileContent)
})
getDir := ctx.NewLogInfo("读取机器目录")
machineFile.GET(":machineId/files/:fileId/read-dir", func(c *gin.Context) {
rc := ctx.NewReqCtxWithGin(c).WithLog(getDir)
rc.Handle(mf.GetDirEntry)
ctx.NewReqCtxWithGin(c).WithLog(getDir).
Handle(mf.GetDirEntry)
})
writeFile := ctx.NewLogInfo("写入or下载文件内容")
@@ -61,6 +61,13 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
Handle(mf.WriteFileContent)
})
createFile := ctx.NewLogInfo("创建机器文件or目录")
machineFile.POST(":machineId/files/:fileId/create-file", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).WithLog(createFile).
WithRequiredPermission(wfP).
Handle(mf.CreateFile)
})
uploadFile := ctx.NewLogInfo("文件上传")
ufP := ctx.NewPermission("machine:file:upload")
machineFile.POST(":machineId/files/:fileId/upload", func(c *gin.Context) {

View File

@@ -35,8 +35,12 @@ func InitRedisRouter(router *gin.RouterGroup) {
ctx.NewReqCtxWithGin(c).Handle(rs.RedisInfo)
})
redis.GET(":id/cluster-info", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(rs.ClusterInfo)
})
// 获取指定redis keys
redis.GET(":id/scan/:cursor/:count", func(c *gin.Context) {
redis.POST(":id/scan", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(rs.Scan)
})

View File

@@ -22,12 +22,13 @@ DROP TABLE IF EXISTS `t_db`;
CREATE TABLE `t_db` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库实例名称',
`host` varchar(20) COLLATE utf8mb4_bin NOT NULL,
`host` varchar(50) COLLATE utf8mb4_bin NOT NULL,
`port` int(8) NOT NULL,
`username` varchar(255) COLLATE utf8mb4_bin NOT NULL,
`password` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
`type` varchar(20) COLLATE utf8mb4_bin NOT NULL COMMENT '数据库实例类型(mysql...)',
`database` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库,空格分割多个数据库',
`params` varchar(125) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '其他连接参数',
`network` varchar(8) COLLATE utf8mb4_bin DEFAULT NULL,
`project_id` bigint(20) DEFAULT NULL,
`project` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL,
@@ -103,7 +104,7 @@ CREATE TABLE `t_machine` (
`project_id` bigint(20) DEFAULT NULL,
`project_name` varchar(36) COLLATE utf8mb4_bin DEFAULT NULL,
`name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
`ip` varchar(18) COLLATE utf8mb4_bin NOT NULL,
`ip` varchar(36) COLLATE utf8mb4_bin NOT NULL,
`port` int(12) NOT NULL,
`username` varchar(12) COLLATE utf8mb4_bin NOT NULL,
`password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
@@ -253,9 +254,11 @@ CREATE TABLE `t_project_member` (
DROP TABLE IF EXISTS `t_redis`;
CREATE TABLE `t_redis` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`host` varchar(32) COLLATE utf8mb4_bin NOT NULL,
`host` varchar(255) COLLATE utf8mb4_bin NOT NULL,
`password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
`db` int(32) DEFAULT NULL,
`mode` varchar(32) DEFAULT NULL,
`remark` varchar(125) DEFAULT NULL,
`project_id` bigint(20) DEFAULT NULL,
`project` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
`env_id` bigint(20) DEFAULT NULL,

View File

@@ -16,7 +16,6 @@ type HandlerFunc func(*ReqCtx)
type ReqCtx struct {
GinCtx *gin.Context // gin context
// NeedToken bool // 是否需要token
RequiredPermission *Permission // 需要的权限信息默认为nil需要校验token
LoginAccount *model.LoginAccount // 登录账号信息只有校验token后才会有值
@@ -26,7 +25,7 @@ type ReqCtx struct {
Err interface{} // 请求错误
timed int64 // 执行时间
noRes bool // 无需返回结果,即文件下载等
NoRes bool // 无需返回结果,即文件下载等
}
func (rc *ReqCtx) Handle(handler HandlerFunc) {
@@ -55,13 +54,13 @@ func (rc *ReqCtx) Handle(handler HandlerFunc) {
begin := time.Now()
handler(rc)
rc.timed = time.Now().Sub(begin).Milliseconds()
if !rc.noRes {
if !rc.NoRes {
ginx.SuccessRes(ginCtx, rc.ResData)
}
}
func (rc *ReqCtx) Download(reader io.Reader, filename string) {
rc.noRes = true
rc.NoRes = true
ginx.Download(rc.GinCtx, reader, filename)
}

View File

@@ -1,7 +1,7 @@
package global
import (
"github.com/go-redis/redis"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)

View File

@@ -1,10 +1,11 @@
package rediscli
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis"
"github.com/go-redis/redis/v8"
)
var cli *redis.Client
@@ -19,7 +20,7 @@ func GetCli() *redis.Client {
// get key value
func Get(key string) string {
val, err := cli.Get(key).Result()
val, err := cli.Get(context.TODO(), key).Result()
switch {
case err == redis.Nil:
fmt.Println("key does not exist")
@@ -33,32 +34,32 @@ func Get(key string) string {
// set key value
func Set(key string, val string, expiration time.Duration) {
cli.Set(key, val, expiration)
cli.Set(context.TODO(), key, val, expiration)
}
func HSet(key string, field string, val interface{}) {
cli.HSet(key, field, val)
cli.HSet(context.TODO(), key, field, val)
}
// hget
func HGet(key string, field string) string {
val, _ := cli.HGet(key, field).Result()
val, _ := cli.HGet(context.TODO(), key, field).Result()
return val
}
// hget
func HExist(key string, field string) bool {
val, _ := cli.HExists(key, field).Result()
val, _ := cli.HExists(context.TODO(), key, field).Result()
return val
}
// hgetall
func HGetAll(key string) map[string]string {
vals, _ := cli.HGetAll(key).Result()
vals, _ := cli.HGetAll(context.TODO(), key).Result()
return vals
}
// hdel
func HDel(key string, fields ...string) int {
return int(cli.HDel(key, fields...).Val())
return int(cli.HDel(context.TODO(), key, fields...).Val())
}

View File

@@ -1,11 +1,12 @@
package starter
import (
"context"
"fmt"
"mayfly-go/pkg/config"
"mayfly-go/pkg/global"
"github.com/go-redis/redis"
"github.com/go-redis/redis/v8"
)
func InitRedis() {
@@ -26,7 +27,7 @@ func ConnRedis() *redis.Client {
DB: redisConf.Db, // use default DB
})
// 测试连接
_, e := rdb.Ping().Result()
_, e := rdb.Ping(context.TODO()).Result()
if e != nil {
global.Log.Panic(fmt.Sprintf("连接redis失败! [%s:%d]", redisConf.Host, redisConf.Port))
}

View File

@@ -2,6 +2,8 @@ package utils
import (
"bytes"
"encoding/json"
"strconv"
"strings"
"text/template"
)
@@ -107,3 +109,45 @@ func ReverStrTemplate(temp, str string, res map[string]interface{}) {
ReverStrTemplate(next, StrTrim(SubString(str, UnicodeIndex(str, value)+StrLen(value), StrLen(str))), res)
}
}
func ToString(value interface{}) string {
// interface 转 string
var key string
if value == nil {
return key
}
switch it := value.(type) {
case float64:
return strconv.FormatFloat(it, 'f', -1, 64)
case float32:
return strconv.FormatFloat(float64(it), 'f', -1, 64)
case int:
return strconv.Itoa(it)
case uint:
return strconv.Itoa(int(it))
case int8:
return strconv.Itoa(int(it))
case uint8:
return strconv.Itoa(int(it))
case int16:
return strconv.Itoa(int(it))
case uint16:
return strconv.Itoa(int(it))
case int32:
return strconv.Itoa(int(it))
case uint32:
return strconv.Itoa(int(it))
case int64:
return strconv.FormatInt(it, 10)
case uint64:
return strconv.FormatUint(it, 10)
case string:
return it
case []byte:
return string(value.([]byte))
default:
newValue, _ := json.Marshal(value)
return string(newValue)
}
}