mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-03 07:50:25 +08:00
Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e925a808c4 | ||
|
|
6c197edddd | ||
|
|
c35e91b7b6 | ||
|
|
575947795a | ||
|
|
51f116c7d2 | ||
|
|
c28254855c | ||
|
|
e8f3671ffb | ||
|
|
ac62767a18 | ||
|
|
2db4c20dd3 | ||
|
|
cfb7fd5b29 | ||
|
|
22c401f9d8 | ||
|
|
be00b90c1d | ||
|
|
fb3f89c594 | ||
|
|
e7a66378ea | ||
|
|
2f88b48973 | ||
|
|
7761fe0288 | ||
|
|
09e6bdcf7e | ||
|
|
61a4d87f59 | ||
|
|
c219ec33b0 | ||
|
|
fd86f36218 | ||
|
|
efac41f392 | ||
|
|
52df61ae0d | ||
|
|
cf2bc6785c | ||
|
|
98a4c92576 | ||
|
|
b1ee9b65ff | ||
|
|
99cc4c5e5e | ||
|
|
226bb8f089 | ||
|
|
37ed5134e8 | ||
|
|
0f54d4a472 | ||
|
|
64805360d6 | ||
|
|
7f69fe2ad9 | ||
|
|
f913510d3c | ||
|
|
f2d9e7786d | ||
|
|
e1afb1ed54 | ||
|
|
12f8cf0111 | ||
|
|
daa2ef5203 | ||
|
|
1e3e183930 | ||
|
|
366563a0fe | ||
|
|
577802e5ad | ||
|
|
76d6fc3ba5 |
22
README.md
22
README.md
@@ -1,7 +1,25 @@
|
||||
# 🌈mayfly-go
|
||||
|
||||
<p align="center">
|
||||
<a href="https://gitee.com/objs/mayfly-go" target="_blank">
|
||||
<img src="https://gitee.com/objs/mayfly-go/badge/star.svg?theme=white" alt="star"/>
|
||||
<img src="https://gitee.com/objs/mayfly-go/badge/fork.svg" alt="fork"/>
|
||||
</a>
|
||||
<a href="https://github.com/may-fly/mayfly-go" target="_blank">
|
||||
<img src="https://img.shields.io/github/stars/may-fly/mayfly-go.svg?style=social" alt="github star"/>
|
||||
<img src="https://img.shields.io/github/forks/may-fly/mayfly-go.svg?style=social" alt="github fork"/>
|
||||
</a>
|
||||
<a href="https://github.com/golang/go" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Golang-1.18%2B-yellow.svg" alt="golang"/>
|
||||
</a>
|
||||
<a href="https://cn.vuejs.org" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Vue-3.x-green.svg" alt="vue">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
### 介绍
|
||||
简单基于DDD(领域驱动设计)分层架构实现的web版 **linux、数据库(mysql postgres)、redis(单机 集群)、mongo统一管理操作平台**
|
||||
web版 **linux(终端[终端回放] 文件 脚本 进程)、数据库(mysql postgres)、redis(单机 哨兵 集群)、mongo统一管理操作平台**
|
||||
|
||||
|
||||
### 开发语言与主要框架
|
||||
@@ -10,7 +28,7 @@
|
||||
|
||||
|
||||
### 交流及问题反馈加 QQ 群
|
||||
<a target="_blank" href="https://qm.qq.com/cgi-bin/qm/qr?jump_from=webapi">119699946</a>
|
||||
<a target="_blank" href="https://qm.qq.com/cgi-bin/qm/qr?k=IdJSHW0jTMhmWFHBUS9a83wxtrxDDhFj&jump_from=webapi">119699946</a>
|
||||
|
||||
|
||||
### 系统相关资料
|
||||
|
||||
@@ -30,9 +30,9 @@ function buildWeb() {
|
||||
|
||||
echo_yellow "-------------------打包前端开始-------------------"
|
||||
yarn run build
|
||||
if [ "${copy2Server}" == "1" ] ; then
|
||||
echo_green '将打包后的静态文件拷贝至server/static'
|
||||
rm -rf ${server_folder}/static && mkdir -p ${server_folder}/static && cp -r ${web_folder}/dist/* ${server_folder}/static
|
||||
if [ "${copy2Server}" == "2" ] ; then
|
||||
echo_green '将打包后的静态文件拷贝至server/static/static'
|
||||
rm -rf ${server_folder}/static/static && mkdir -p ${server_folder}/static/static && cp -r ${web_folder}/dist/* ${server_folder}/static/static
|
||||
fi
|
||||
echo_yellow ">>>>>>>>>>>>>>>>>>>打包前端结束<<<<<<<<<<<<<<<<<<<<\n"
|
||||
}
|
||||
@@ -44,6 +44,7 @@ function build() {
|
||||
toFolder=$1
|
||||
os=$2
|
||||
arch=$3
|
||||
copyStatic=$4
|
||||
|
||||
echo_yellow "-------------------${os}-${arch}打包构建开始-------------------"
|
||||
|
||||
@@ -67,8 +68,10 @@ function build() {
|
||||
echo_green "移动二进制文件至'${toFolder}'"
|
||||
mv ${server_folder}/${execFileName} ${toFolder}
|
||||
|
||||
echo_green "拷贝前端静态页面至'${toFolder}/static'"
|
||||
mkdir -p ${toFolder}/static && cp -r ${web_folder}/dist/* ${toFolder}/static
|
||||
if [ "${copy2Server}" == "1" ] ; then
|
||||
echo_green "拷贝前端静态页面至'${toFolder}/static'"
|
||||
mkdir -p ${toFolder}/static && cp -r ${web_folder}/dist/* ${toFolder}/static
|
||||
fi
|
||||
|
||||
echo_green "拷贝脚本等资源文件[config.yml、mayfly-go.sql、readme.txt、startup.sh、shutdown.sh]"
|
||||
cp ${server_folder}/config.yml ${toFolder}
|
||||
@@ -81,15 +84,19 @@ function build() {
|
||||
}
|
||||
|
||||
function buildLinuxAmd64() {
|
||||
build "$1/mayfly-go-linux-amd64" "linux" "amd64"
|
||||
build "$1/mayfly-go-linux-amd64" "linux" "amd64" $2
|
||||
}
|
||||
|
||||
function buildLinuxArm64() {
|
||||
build "$1/mayfly-go-linux-arm64" "linux" "arm64"
|
||||
build "$1/mayfly-go-linux-arm64" "linux" "arm64" $2
|
||||
}
|
||||
|
||||
function buildWindows() {
|
||||
build "$1/mayfly-go-windows" "windows" "amd64"
|
||||
build "$1/mayfly-go-windows" "windows" "amd64" $2
|
||||
}
|
||||
|
||||
function buildMac() {
|
||||
build "$1/mayfly-go-mac" "darwin" "amd64" $2
|
||||
}
|
||||
|
||||
function runBuild() {
|
||||
@@ -103,34 +110,34 @@ function runBuild() {
|
||||
cd ${toPath}
|
||||
toPath=`pwd`
|
||||
|
||||
read -p "是否构建前端[0|其他->否 1->是 2->构建并拷贝至server/static]: " runBuildWeb
|
||||
read -p "请选择构建版本[0|其他->全部 1->linux-amd64 2->linux-arm64 3->windows]: " buildType
|
||||
read -p "是否构建前端[0|其他->否 1->是 2->构建并拷贝至server/static/static]: " runBuildWeb
|
||||
read -p "请选择构建版本[0|其他->全部 1->linux-amd64 2->linux-arm64 3->windows 4->mac]: " buildType
|
||||
|
||||
if [ "${runBuildWeb}" == "1" ];then
|
||||
buildWeb
|
||||
fi
|
||||
if [ "${runBuildWeb}" == "2" ];then
|
||||
buildWeb 1
|
||||
|
||||
if [ "${runBuildWeb}" == "1" ] || [ "${runBuildWeb}" == "2" ] ; then
|
||||
buildWeb ${runBuildWeb}
|
||||
fi
|
||||
|
||||
if [ "${buildType}" == "1" ];then
|
||||
buildLinuxAmd64 ${toPath}
|
||||
exit;
|
||||
fi
|
||||
|
||||
if [ "${buildType}" == "2" ];then
|
||||
buildLinuxArm64 ${toPath}
|
||||
exit;
|
||||
fi
|
||||
|
||||
if [ "${buildType}" == "3" ];then
|
||||
buildWindows ${toPath}
|
||||
exit;
|
||||
fi
|
||||
|
||||
buildLinuxAmd64 ${toPath}
|
||||
buildLinuxArm64 ${toPath}
|
||||
buildWindows ${toPath}
|
||||
case ${buildType} in
|
||||
"1")
|
||||
buildLinuxAmd64 ${toPath} ${runBuildWeb}
|
||||
;;
|
||||
"2")
|
||||
buildLinuxArm64 ${toPath} ${runBuildWeb}
|
||||
;;
|
||||
"3")
|
||||
buildWindows ${toPath} ${runBuildWeb}
|
||||
;;
|
||||
"4")
|
||||
buildMac ${toPath} ${runBuildWeb}
|
||||
;;
|
||||
*)
|
||||
buildLinuxAmd64 ${toPath} ${runBuildWeb}
|
||||
buildLinuxArm64 ${toPath} ${runBuildWeb}
|
||||
buildWindows ${toPath} ${runBuildWeb}
|
||||
buildMac ${toPath} ${runBuildWeb}
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
runBuild
|
||||
@@ -18,8 +18,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="text/javascript" src="./config.js"></script>
|
||||
<script type="application/javascript" src="./config.js"></script>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
<!-- <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=wsijQt8sLXrCW71YesmispvYHitfG9gv&s=1"></script> -->
|
||||
</body>
|
||||
</html>
|
||||
|
||||
5123
mayfly_go_web/package-lock.json
generated
5123
mayfly_go_web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -7,27 +7,28 @@
|
||||
"lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.0.6",
|
||||
"axios": "^0.27.2",
|
||||
"@element-plus/icons-vue": "^2.0.9",
|
||||
"asciinema-player": "^3.0.1",
|
||||
"axios": "^1.1.2",
|
||||
"codemirror": "^5.65.5",
|
||||
"countup.js": "^2.0.7",
|
||||
"cropperjs": "^1.5.11",
|
||||
"echarts": "^5.3.3",
|
||||
"element-plus": "^2.2.9",
|
||||
"element-plus": "^2.2.18",
|
||||
"jsencrypt": "^3.2.1",
|
||||
"jsoneditor": "^9.9.0",
|
||||
"jsoneditor": "^9.9.2",
|
||||
"lodash": "^4.17.21",
|
||||
"mitt": "^3.0.0",
|
||||
"nprogress": "^0.2.0",
|
||||
"screenfull": "^5.1.0",
|
||||
"screenfull": "^6.0.2",
|
||||
"sortablejs": "^1.13.0",
|
||||
"sql-formatter": "^7.0.3",
|
||||
"vue": "^3.2.37",
|
||||
"sql-formatter": "^9.2.0",
|
||||
"vue": "^3.2.41",
|
||||
"vue-clipboard3": "^1.0.1",
|
||||
"vue-router": "^4.1.2",
|
||||
"vue-router": "^4.1.5",
|
||||
"vuex": "^4.0.2",
|
||||
"xterm": "^4.19.0",
|
||||
"xterm-addon-fit": "^0.5.0"
|
||||
"xterm": "^5.0.0",
|
||||
"xterm-addon-fit": "^0.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/lodash": "^4.14.178",
|
||||
|
||||
3
mayfly_go_web/shim.d.ts
vendored
3
mayfly_go_web/shim.d.ts
vendored
@@ -6,4 +6,5 @@ declare module '*.vue' {
|
||||
}
|
||||
declare module 'codemirror';
|
||||
declare module 'sql-formatter';
|
||||
declare module 'jsoneditor';
|
||||
declare module 'jsoneditor';
|
||||
declare module 'asciinema-player';
|
||||
@@ -11,6 +11,8 @@ import { useStore } from '@/store/index.ts';
|
||||
import { getLocal } from '@/common/utils/storage.ts';
|
||||
import LockScreen from '@/views/layout/lockScreen/index.vue';
|
||||
import Setings from '@/views/layout/navBars/breadcrumb/setings.vue';
|
||||
import Watermark from '@/common/utils/wartermark.ts';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'app',
|
||||
components: { LockScreen, Setings },
|
||||
@@ -57,6 +59,8 @@ export default defineComponent({
|
||||
() => route.path,
|
||||
() => {
|
||||
nextTick(() => {
|
||||
// 路由变化更新水印
|
||||
Watermark.use();
|
||||
document.title = `${route.meta.title} - ${getThemeConfig.value.globalTitle}` || getThemeConfig.value.globalTitle;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import request from './request'
|
||||
|
||||
export default {
|
||||
login: (param: any) => request.request('POST', '/sys/accounts/login', param, null),
|
||||
changePwd: (param: any) => request.request('POST', '/sys/accounts/change-pwd', param, null),
|
||||
getPublicKey: () => request.request('GET', '/common/public-key', null, null),
|
||||
captcha: () => request.request('GET', '/sys/captcha', null, null),
|
||||
logout: (param: any) => request.request('POST', '/sys/accounts/logout/{token}', param, null),
|
||||
getMenuRoute: (param: any) => request.request('Get', '/sys/resources/account', param, null)
|
||||
login: (param: any) => request.request('POST', '/sys/accounts/login', param),
|
||||
changePwd: (param: any) => request.request('POST', '/sys/accounts/change-pwd', param),
|
||||
getPublicKey: () => request.request('GET', '/common/public-key'),
|
||||
getConfigValue: (param: any) => request.request('GET', '/sys/configs/value', param),
|
||||
captcha: () => request.request('GET', '/sys/captcha'),
|
||||
logout: (param: any) => request.request('POST', '/sys/accounts/logout/{token}', param),
|
||||
getMenuRoute: (param: any) => request.request('Get', '/sys/resources/account', param)
|
||||
}
|
||||
@@ -28,7 +28,6 @@ export async function RsaEncrypt(value: any) {
|
||||
if (encryptor != null) {
|
||||
return encryptor.encrypt(value)
|
||||
}
|
||||
console.log(value)
|
||||
encryptor = new JSEncrypt()
|
||||
const publicKey = await getRsaPublicKey() as string;
|
||||
notBlank(publicKey, "获取公钥失败")
|
||||
|
||||
48
mayfly_go_web/src/common/sysconfig.ts
Normal file
48
mayfly_go_web/src/common/sysconfig.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import openApi from './openApi';
|
||||
|
||||
// 登录是否使用验证码配置key
|
||||
const UseLoginCaptchaConfigKey = "UseLoginCaptcha"
|
||||
const UseWartermarkConfigKey = "UseWartermark"
|
||||
|
||||
/**
|
||||
* 获取系统配置值
|
||||
*
|
||||
* @param key 配置key
|
||||
* @returns 配置值
|
||||
*/
|
||||
export async function getConfigValue(key: string) : Promise<string> {
|
||||
return await openApi.getConfigValue({key}) as string
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取bool类型系统配置值
|
||||
*
|
||||
* @param key 配置key
|
||||
* @param defaultValue 默认值
|
||||
* @returns 是否为ture,1: true;其他: false
|
||||
*/
|
||||
export async function getBoolConfigValue(key :string, defaultValue :boolean) : Promise<boolean> {
|
||||
const value = await getConfigValue(key)
|
||||
if (!value) {
|
||||
return defaultValue;
|
||||
}
|
||||
return value == "1";
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否使用登录验证码
|
||||
*
|
||||
* @returns
|
||||
*/
|
||||
export async function useLoginCaptcha() : Promise<boolean> {
|
||||
return await getBoolConfigValue(UseLoginCaptchaConfigKey, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否启用水印
|
||||
*
|
||||
* @returns
|
||||
*/
|
||||
export async function useWartermark() : Promise<boolean> {
|
||||
return await getBoolConfigValue(UseWartermarkConfigKey, true)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export function dateFormat(fmt: string, date: Date) {
|
||||
export function dateFormat2(fmt: string, date: Date) {
|
||||
let ret;
|
||||
const opt = {
|
||||
"y+": date.getFullYear().toString(), // 年
|
||||
@@ -19,5 +19,9 @@ export function dateFormat(fmt: string, date: Date) {
|
||||
}
|
||||
|
||||
export function dateStrFormat(fmt: string, dateStr: string) {
|
||||
return dateFormat(fmt, new Date(dateStr))
|
||||
return dateFormat2(fmt, new Date(dateStr))
|
||||
}
|
||||
|
||||
export function dateFormat(dateStr: string) {
|
||||
return dateFormat2('yyyy-MM-dd HH:mm:ss',new Date(dateStr))
|
||||
}
|
||||
@@ -35,3 +35,22 @@ export function removeSession(key: string) {
|
||||
export function clearSession() {
|
||||
window.sessionStorage.clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function getUserInfo4Session() {
|
||||
return getSession("userInfo")
|
||||
}
|
||||
|
||||
export function setUserInfo2Session(userinfo: any) {
|
||||
setSession("userInfo", userinfo)
|
||||
}
|
||||
|
||||
// 获取是否开启水印
|
||||
export function getUseWatermark4Session() {
|
||||
return getSession("useWatermark")
|
||||
}
|
||||
|
||||
export function setUseWatermark2Session(useWatermark: boolean) {
|
||||
setSession("useWatermark", useWatermark)
|
||||
}
|
||||
@@ -1,21 +1,26 @@
|
||||
import { getUseWatermark4Session, getUserInfo4Session } from '@/common/utils/storage.ts';
|
||||
import { dateFormat2 } from '@/common/utils/date.ts'
|
||||
|
||||
// 页面添加水印效果
|
||||
const setWatermark = (str: any) => {
|
||||
const id = '1.23452384164.123412416';
|
||||
if (document.getElementById(id) !== null) document.body.removeChild(document.getElementById(id) as any);
|
||||
const can = document.createElement('canvas');
|
||||
can.width = 250;
|
||||
can.height = 180;
|
||||
can.width = 400;
|
||||
can.height = 250;
|
||||
const cans: any = can.getContext('2d');
|
||||
cans.rotate((-20 * Math.PI) / 180);
|
||||
cans.font = '12px Vedana';
|
||||
cans.fillStyle = 'rgba(200, 200, 200, 0.30)';
|
||||
cans.textAlign = 'center';
|
||||
cans.font = '14px Vedana';
|
||||
cans.fillStyle = 'rgba(200, 200, 200, 0.35)';
|
||||
cans.textAlign = 'left';
|
||||
cans.textBaseline = 'Middle';
|
||||
cans.fillText(str, can.width / 10, can.height / 2);
|
||||
// cans.fillText('mayfly go', can.width / 4, can.height )
|
||||
cans.fillText(str, can.width / 8, can.height / 2);
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.id = id;
|
||||
div.style.pointerEvents = 'none';
|
||||
div.style.top = '35px';
|
||||
div.style.top = '30px';
|
||||
div.style.left = '0px';
|
||||
div.style.position = 'fixed';
|
||||
div.style.zIndex = '10000000';
|
||||
@@ -26,16 +31,34 @@ const setWatermark = (str: any) => {
|
||||
return id;
|
||||
};
|
||||
|
||||
function set(str: any) {
|
||||
let id = setWatermark(str);
|
||||
if (document.getElementById(id) === null) id = setWatermark(str);
|
||||
}
|
||||
|
||||
function del() {
|
||||
let id = '1.23452384164.123412416';
|
||||
if (document.getElementById(id) !== null) document.body.removeChild(document.getElementById(id) as any);
|
||||
}
|
||||
|
||||
const watermark = {
|
||||
use: () => {
|
||||
setTimeout(() => {
|
||||
const userinfo = getUserInfo4Session()
|
||||
if (userinfo && getUseWatermark4Session()) {
|
||||
set(`${userinfo.username} ${dateFormat2('yyyy-MM-dd HH:mm:ss', new Date())}`)
|
||||
} else {
|
||||
del();
|
||||
}
|
||||
}, 1500)
|
||||
},
|
||||
// 设置水印
|
||||
set: (str: any) => {
|
||||
let id = setWatermark(str);
|
||||
if (document.getElementById(id) === null) id = setWatermark(str);
|
||||
set(str)
|
||||
},
|
||||
// 删除水印
|
||||
del: () => {
|
||||
let id = '1.23452384164.123412416';
|
||||
if (document.getElementById(id) !== null) document.body.removeChild(document.getElementById(id) as any);
|
||||
del();
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ const CodeMirror = (window as any).CodeMirror || _CodeMirror;
|
||||
|
||||
export default defineComponent({
|
||||
name: 'CodeMirror',
|
||||
components: {
|
||||
components: {
|
||||
ElOption,
|
||||
ElSelect,
|
||||
},
|
||||
@@ -61,11 +61,11 @@ export default defineComponent({
|
||||
},
|
||||
height: {
|
||||
type: String,
|
||||
default: "500px",
|
||||
default: '500px',
|
||||
},
|
||||
width: {
|
||||
type: String,
|
||||
default: "auto",
|
||||
default: 'auto',
|
||||
},
|
||||
canChangeMode: {
|
||||
type: Boolean,
|
||||
@@ -300,7 +300,7 @@ export default defineComponent({
|
||||
coder.setValue(newVal);
|
||||
state.content = newVal;
|
||||
coder.scrollTo(scrollInfo.left, scrollInfo.top);
|
||||
refresh()
|
||||
refresh();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -327,7 +327,6 @@ export default defineComponent({
|
||||
}
|
||||
font-family: 'JetBrainsMono';
|
||||
}
|
||||
|
||||
.code-mode-select {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
@@ -336,4 +335,26 @@ export default defineComponent({
|
||||
max-width: 130px;
|
||||
}
|
||||
}
|
||||
.CodeMirror-hints {
|
||||
position: absolute;
|
||||
z-index: 10000;
|
||||
overflow: hidden;
|
||||
list-style: none;
|
||||
|
||||
margin: 0;
|
||||
padding: 2px;
|
||||
|
||||
-webkit-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.2);
|
||||
-moz-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.2);
|
||||
box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.2);
|
||||
border-radius: 3px;
|
||||
border: 1px solid silver;
|
||||
|
||||
background: white;
|
||||
font-size: 90%;
|
||||
font-family: 'JetBrainsMono';
|
||||
|
||||
max-height: 20em;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -2,6 +2,7 @@ import RouterParent from '@/views/layout/routerView/parent.vue';
|
||||
|
||||
export const imports = {
|
||||
'RouterParent': RouterParent,
|
||||
|
||||
"Home": () => import('@/views/home/index.vue'),
|
||||
'Personal': () => import('@/views/personal/index.vue'),
|
||||
// machine
|
||||
@@ -11,8 +12,11 @@ export const imports = {
|
||||
"RoleList": () => import('@/views/system/role'),
|
||||
"AccountList": () => import('@/views/system/account'),
|
||||
"SyslogList": () => import('@/views/system/syslog/SyslogList.vue'),
|
||||
// project
|
||||
"ProjectList": () => import('@/views/ops/project/ProjectList.vue'),
|
||||
"ConfigList": () => import('@/views/system/config/ConfigList.vue'),
|
||||
|
||||
// tag
|
||||
"TagTreeList": () => import('@/views/ops/tag/TagTreeList.vue'),
|
||||
"TeamList": () => import('@/views/ops/tag/TeamList.vue'),
|
||||
// db
|
||||
"DbList": () => import('@/views/ops/db/DbList.vue'),
|
||||
"SqlExec": () => import('@/views/ops/db'),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { RouteRecordRaw } from 'vue-router';
|
||||
import Layout from '@/views/layout/index.vue'
|
||||
import RouterParent from '@/views/layout/routerView/parent.vue';
|
||||
// import RouterParent from '@/views/layout/routerView/parent.vue';
|
||||
|
||||
// 定义动态路由
|
||||
export const dynamicRoutes = [
|
||||
@@ -12,119 +12,108 @@ export const dynamicRoutes = [
|
||||
meta: {
|
||||
isKeepAlive: true,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '/home',
|
||||
name: 'home',
|
||||
component: () => import('@/views/home/index.vue'),
|
||||
meta: {
|
||||
title: '首页',
|
||||
// iframe链接
|
||||
link: '',
|
||||
// 是否在菜单栏显示,默认显示
|
||||
isHide: false,
|
||||
isKeepAlive: true,
|
||||
// tag标签是否不可删除
|
||||
isAffix: true,
|
||||
// 是否为iframe
|
||||
isIframe: false,
|
||||
icon: 'el-icon-s-home',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/sys',
|
||||
name: 'Resource',
|
||||
redirect: '/sys/resources',
|
||||
meta: {
|
||||
title: '系统管理',
|
||||
// 资源code,用于校验用户是否拥有该资源权限
|
||||
code: 'sys',
|
||||
// isKeepAlive: true,
|
||||
icon: 'el-icon-monitor',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'sys/resources',
|
||||
name: 'ResourceList',
|
||||
component: () => import('@/views/system/resource'),
|
||||
meta: {
|
||||
title: '资源管理',
|
||||
code: 'resource:list',
|
||||
isKeepAlive: true,
|
||||
icon: 'el-icon-menu',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'sys/roles',
|
||||
name: 'RoleList',
|
||||
component: () => import('@/views/system/role'),
|
||||
meta: {
|
||||
title: '角色管理',
|
||||
code: 'role:list',
|
||||
isKeepAlive: true,
|
||||
icon: 'el-icon-menu',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'sys/accounts',
|
||||
name: 'ResourceList',
|
||||
component: () => import('@/views/system/account'),
|
||||
meta: {
|
||||
title: '账号管理',
|
||||
code: 'account:list',
|
||||
isKeepAlive: true,
|
||||
icon: 'el-icon-menu',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/machine',
|
||||
name: 'Machine',
|
||||
redirect: '/machine/list',
|
||||
meta: {
|
||||
title: '机器管理',
|
||||
// 资源code,用于校验用户是否拥有该资源权限
|
||||
code: 'machine',
|
||||
// isKeepAlive: true,
|
||||
icon: 'el-icon-monitor',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '/list',
|
||||
name: 'MachineList',
|
||||
component: () => import('@/views/ops/machine'),
|
||||
meta: {
|
||||
title: '机器列表',
|
||||
code: 'machine:list',
|
||||
isKeepAlive: true,
|
||||
icon: 'el-icon-menu',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/personal',
|
||||
name: 'personal',
|
||||
component: () => import('@/views/personal/index.vue'),
|
||||
meta: {
|
||||
title: '个人中心',
|
||||
isKeepAlive: true,
|
||||
icon: 'el-icon-user',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/iframes',
|
||||
name: 'layoutIfameView',
|
||||
component: RouterParent,
|
||||
meta: {
|
||||
title: 'iframe',
|
||||
link: 'https://gitee.com/lyt-top/vue-next-admin',
|
||||
isIframe: true,
|
||||
icon: 'el-icon-menu',
|
||||
},
|
||||
},
|
||||
],
|
||||
// children: [
|
||||
// {
|
||||
// path: '/home',
|
||||
// name: 'home',
|
||||
// component: () => import('@/views/home/index.vue'),
|
||||
// meta: {
|
||||
// title: '首页',
|
||||
// // iframe链接
|
||||
// link: '',
|
||||
// // 是否在菜单栏显示,默认显示
|
||||
// isHide: false,
|
||||
// isKeepAlive: true,
|
||||
// // tag标签是否不可删除
|
||||
// isAffix: true,
|
||||
// // 是否为iframe
|
||||
// isIframe: false,
|
||||
// icon: 'el-icon-s-home',
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// path: '/sys',
|
||||
// name: 'Resource',
|
||||
// redirect: '/sys/resources',
|
||||
// meta: {
|
||||
// title: '系统管理',
|
||||
// // 资源code,用于校验用户是否拥有该资源权限
|
||||
// code: 'sys',
|
||||
// // isKeepAlive: true,
|
||||
// icon: 'el-icon-monitor',
|
||||
// },
|
||||
// children: [
|
||||
// {
|
||||
// path: 'sys/resources',
|
||||
// name: 'ResourceList',
|
||||
// component: () => import('@/views/system/resource'),
|
||||
// meta: {
|
||||
// title: '资源管理',
|
||||
// code: 'resource:list',
|
||||
// isKeepAlive: true,
|
||||
// icon: 'el-icon-menu',
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// path: 'sys/roles',
|
||||
// name: 'RoleList',
|
||||
// component: () => import('@/views/system/role'),
|
||||
// meta: {
|
||||
// title: '角色管理',
|
||||
// code: 'role:list',
|
||||
// isKeepAlive: true,
|
||||
// icon: 'el-icon-menu',
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// path: 'sys/accounts',
|
||||
// name: 'ResourceList',
|
||||
// component: () => import('@/views/system/account'),
|
||||
// meta: {
|
||||
// title: '账号管理',
|
||||
// code: 'account:list',
|
||||
// isKeepAlive: true,
|
||||
// icon: 'el-icon-menu',
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// path: '/machine',
|
||||
// name: 'Machine',
|
||||
// redirect: '/machine/list',
|
||||
// meta: {
|
||||
// title: '机器管理',
|
||||
// // 资源code,用于校验用户是否拥有该资源权限
|
||||
// code: 'machine',
|
||||
// // isKeepAlive: true,
|
||||
// icon: 'el-icon-monitor',
|
||||
// },
|
||||
// children: [
|
||||
// {
|
||||
// path: '/list',
|
||||
// name: 'MachineList',
|
||||
// component: () => import('@/views/ops/machine'),
|
||||
// meta: {
|
||||
// title: '机器列表',
|
||||
// code: 'machine:list',
|
||||
// isKeepAlive: true,
|
||||
// icon: 'el-icon-menu',
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// path: '/personal',
|
||||
// name: 'personal',
|
||||
// component: () => import('@/views/personal/index.vue'),
|
||||
// meta: {
|
||||
// title: '个人中心',
|
||||
// isKeepAlive: true,
|
||||
// icon: 'el-icon-user',
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -163,7 +152,6 @@ export const staticRoutes: Array<RouteRecordRaw> = [
|
||||
title: '终端 | {name}',
|
||||
// 是否根据query对标题名进行参数替换,即最终显示为‘终端_机器名’
|
||||
titleRename: true,
|
||||
icon: 'iconfont icon-caidan',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -52,6 +52,7 @@ export interface ThemeConfigState {
|
||||
terminalBackground: string;
|
||||
terminalCursor: string;
|
||||
terminalFontSize: number;
|
||||
terminalFontWeight: string;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,7 @@ const themeConfigModule: Module<ThemeConfigState, RootStateTypes> = {
|
||||
// ssh终端cursor色
|
||||
terminalCursor: '#268F81',
|
||||
terminalFontSize: 15,
|
||||
terminalFontWeight: 'normal',
|
||||
|
||||
|
||||
/* 后端控制路由
|
||||
|
||||
@@ -14,7 +14,7 @@ body,
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
font-family: Microsoft YaHei, Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, SimSun, sans-serif;
|
||||
font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
|
||||
font-weight: 450;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
|
||||
@@ -947,12 +947,6 @@
|
||||
.el-select-dropdown .el-scrollbar__wrap {
|
||||
overflow-x: scroll !important;
|
||||
}
|
||||
.el-select-dropdown__wrap {
|
||||
max-height: 274px !important; /*修复Select 选择器高度问题*/
|
||||
}
|
||||
.el-cascader-menu__wrap.el-scrollbar__wrap {
|
||||
height: 204px !important; /*修复Cascader 级联选择器高度问题*/
|
||||
}
|
||||
|
||||
/* Drawer 抽屉
|
||||
------------------------------- */
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
@import './base.scss';
|
||||
@import './other.scss';
|
||||
@import './element.scss';
|
||||
@import './iconSelector.scss';
|
||||
@import './media/media.scss';
|
||||
@import './waves.scss';
|
||||
@import './iconSelector.scss';
|
||||
@@ -43,25 +43,25 @@ export default {
|
||||
const state = reactive({
|
||||
topCardItemList: [
|
||||
{
|
||||
title: '项目数',
|
||||
id: 'projectNum',
|
||||
color: '#FEBB50',
|
||||
},
|
||||
{
|
||||
title: 'Linux机器数',
|
||||
title: 'Linux机器',
|
||||
id: 'machineNum',
|
||||
color: '#F95959',
|
||||
},
|
||||
{
|
||||
title: '数据库总数',
|
||||
title: '数据库',
|
||||
id: 'dbNum',
|
||||
color: '#8595F4',
|
||||
},
|
||||
{
|
||||
title: 'redis总数',
|
||||
title: 'redis',
|
||||
id: 'redisNum',
|
||||
color: '#1abc9c',
|
||||
},
|
||||
{
|
||||
title: 'Mongo',
|
||||
id: 'mongoNum',
|
||||
color: '#FEBB50',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -74,7 +74,7 @@ export default {
|
||||
const initNumCountUp = async () => {
|
||||
const res: any = await indexApi.getIndexCount.request();
|
||||
nextTick(() => {
|
||||
new CountUp('projectNum', res.projectNum).start();
|
||||
new CountUp('mongoNum', res.mongoNum).start();
|
||||
new CountUp('machineNum', res.machineNum).start();
|
||||
new CountUp('dbNum', res.dbNum).start();
|
||||
new CountUp('redisNum', res.redisNum).start();
|
||||
@@ -87,20 +87,20 @@ export default {
|
||||
router.push('/personal');
|
||||
break;
|
||||
}
|
||||
case 'projectNum': {
|
||||
router.push('/ops/projects');
|
||||
case 'mongoNum': {
|
||||
router.push('/mongo/mongo-data-operation');
|
||||
break;
|
||||
}
|
||||
case 'machineNum': {
|
||||
router.push('/ops/machines');
|
||||
router.push('/machine/machines');
|
||||
break;
|
||||
}
|
||||
case 'dbNum': {
|
||||
router.push('/ops/dbms/dbs');
|
||||
router.push('/dbms/sql-exec');
|
||||
break;
|
||||
}
|
||||
case 'redisNum': {
|
||||
router.push('/ops/redis/manage');
|
||||
router.push('/redis/data-operation');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
</el-input-number>
|
||||
</div>
|
||||
</div>
|
||||
<!-- <div class="layout-breadcrumb-seting-bar-flex mt15">
|
||||
<div class="layout-breadcrumb-seting-bar-flex mt15">
|
||||
<div class="layout-breadcrumb-seting-bar-flex-label">字体粗细</div>
|
||||
<div class="layout-breadcrumb-seting-bar-flex-value">
|
||||
<el-select @change="setLocalThemeConfig" v-model="getThemeConfig.terminalFontWeight" size="small" style="width: 90px">
|
||||
@@ -48,7 +48,7 @@
|
||||
<el-option label="bold" value="bold"> </el-option>
|
||||
</el-select>
|
||||
</div>
|
||||
</div> -->
|
||||
</div>
|
||||
|
||||
<!-- 全局主题 -->
|
||||
<el-divider content-position="left">全局主题</el-divider>
|
||||
@@ -273,23 +273,6 @@
|
||||
<el-switch v-model="getThemeConfig.isInvert" @change="onAddFilterChange('invert')"></el-switch>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout-breadcrumb-seting-bar-flex mt15">
|
||||
<div class="layout-breadcrumb-seting-bar-flex-label">开启水印</div>
|
||||
<div class="layout-breadcrumb-seting-bar-flex-value">
|
||||
<el-switch v-model="getThemeConfig.isWartermark" @change="onWartermarkChange"></el-switch>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout-breadcrumb-seting-bar-flex mt14">
|
||||
<div class="layout-breadcrumb-seting-bar-flex-label">水印文案</div>
|
||||
<div class="layout-breadcrumb-seting-bar-flex-value">
|
||||
<el-input
|
||||
v-model="getThemeConfig.wartermarkText"
|
||||
size="small"
|
||||
style="width: 90px"
|
||||
@input="onWartermarkTextInput($event)"
|
||||
></el-input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 其它设置 -->
|
||||
<el-divider content-position="left">其他设置</el-divider>
|
||||
@@ -440,8 +423,6 @@ import { ElMessage } from 'element-plus';
|
||||
import ClipboardJS from 'clipboard';
|
||||
import { useStore } from '@/store/index.ts';
|
||||
import { getLightColor } from '@/common/utils/theme.ts';
|
||||
import Watermark from '@/common/utils/wartermark.ts';
|
||||
import { verifyAndSpace } from '@/common/utils/toolsValidate.ts';
|
||||
import { setLocal, getLocal, removeLocal } from '@/common/utils/storage.ts';
|
||||
export default defineComponent({
|
||||
name: 'layoutBreadcrumbSeting',
|
||||
@@ -572,18 +553,6 @@ export default defineComponent({
|
||||
setLocalThemeConfig();
|
||||
setLocal('appFilterStyle', appEle.style.cssText);
|
||||
};
|
||||
// 4、界面显示 --> 开启水印
|
||||
const onWartermarkChange = () => {
|
||||
getThemeConfig.value.isWartermark ? Watermark.set(getThemeConfig.value.wartermarkText) : Watermark.del();
|
||||
setLocalThemeConfig();
|
||||
};
|
||||
// 4、界面显示 --> 水印文案
|
||||
const onWartermarkTextInput = (val: string) => {
|
||||
getThemeConfig.value.wartermarkText = verifyAndSpace(val);
|
||||
if (getThemeConfig.value.wartermarkText === '') return false;
|
||||
if (getThemeConfig.value.isWartermark) Watermark.set(getThemeConfig.value.wartermarkText);
|
||||
setLocalThemeConfig();
|
||||
};
|
||||
// 5、布局切换
|
||||
const onSetLayout = (layout: string) => {
|
||||
setLocal('oldLayout', layout);
|
||||
@@ -735,8 +704,6 @@ export default defineComponent({
|
||||
const appEl: any = document.querySelector('#app');
|
||||
appEl.style.cssText = getLocal('appFilterStyle');
|
||||
}
|
||||
// 开启水印
|
||||
onWartermarkChange();
|
||||
// // 语言国际化
|
||||
// if (getLocal('themeConfig')) proxy.$i18n.locale = getLocal('themeConfig').globalI18n;
|
||||
}, 1100);
|
||||
@@ -762,8 +729,6 @@ export default defineComponent({
|
||||
getThemeConfig,
|
||||
onDrawerClose,
|
||||
onAddFilterChange,
|
||||
onWartermarkChange,
|
||||
onWartermarkTextInput,
|
||||
onSetLayout,
|
||||
setLocalThemeConfig,
|
||||
onClassicSplitMenuChange,
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<div class="layout-navbars-breadcrumb-user-icon" @click="onSearchClick">
|
||||
<!-- <div class="layout-navbars-breadcrumb-user-icon" @click="onSearchClick">
|
||||
<el-icon title="菜单搜索">
|
||||
<search />
|
||||
</el-icon>
|
||||
</div>
|
||||
</div> -->
|
||||
<div class="layout-navbars-breadcrumb-user-icon" @click="onLayoutSetingClick">
|
||||
<el-icon title="布局设置">
|
||||
<setting />
|
||||
@@ -28,7 +28,7 @@
|
||||
<el-popover
|
||||
placement="bottom"
|
||||
trigger="click"
|
||||
v-model:visible="isShowUserNewsPopover"
|
||||
:visible="isShowUserNewsPopover"
|
||||
:width="300"
|
||||
popper-class="el-popover-pupop-user-news"
|
||||
>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<el-input type="password" placeholder="请输入密码" prefix-icon="lock" v-model="loginForm.password" autocomplete="off" show-password>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="captcha">
|
||||
<el-form-item v-if="useLoginCaptcha" prop="captcha">
|
||||
<el-row :gutter="15">
|
||||
<el-col :span="16">
|
||||
<el-input
|
||||
@@ -73,15 +73,16 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { onMounted, ref, toRefs, reactive, defineComponent, computed } from 'vue';
|
||||
import { nextTick, onMounted, ref, toRefs, reactive, defineComponent, computed } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { initBackEndControlRoutesFun } from '@/router/index.ts';
|
||||
import { useStore } from '@/store/index.ts';
|
||||
import { setSession } from '@/common/utils/storage.ts';
|
||||
import { setSession, setUserInfo2Session, setUseWatermark2Session } from '@/common/utils/storage.ts';
|
||||
import { formatAxis } from '@/common/utils/formatTime.ts';
|
||||
import openApi from '@/common/openApi';
|
||||
import { RsaEncrypt } from '@/common/rsa';
|
||||
import { useLoginCaptcha, useWartermark } from '@/common/sysconfig';
|
||||
import { letterAvatar } from '@/common/utils/string';
|
||||
|
||||
export default defineComponent({
|
||||
@@ -94,6 +95,7 @@ export default defineComponent({
|
||||
const changePwdFormRef: any = ref(null);
|
||||
|
||||
const state = reactive({
|
||||
useLoginCaptcha: false,
|
||||
captchaImage: '',
|
||||
loginForm: {
|
||||
username: '',
|
||||
@@ -130,11 +132,19 @@ export default defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
getCaptcha();
|
||||
onMounted(async () => {
|
||||
nextTick(async () => {
|
||||
state.useLoginCaptcha = await useLoginCaptcha();
|
||||
getCaptcha();
|
||||
});
|
||||
// 移除公钥, 方便后续重新获取
|
||||
sessionStorage.removeItem('RsaPublicKey');
|
||||
});
|
||||
|
||||
const getCaptcha = async () => {
|
||||
if (!state.useLoginCaptcha) {
|
||||
return;
|
||||
}
|
||||
let res: any = await openApi.captcha();
|
||||
state.captchaImage = res.base64Captcha;
|
||||
state.loginForm.cid = res.cid;
|
||||
@@ -196,7 +206,7 @@ export default defineComponent({
|
||||
};
|
||||
|
||||
// 存储用户信息到浏览器缓存
|
||||
setSession('userInfo', userInfos);
|
||||
setUserInfo2Session(userInfos);
|
||||
// 1、请注意执行顺序(存储用户信息到vuex)
|
||||
store.dispatch('userInfos/setUserInfos', userInfos);
|
||||
if (!store.state.themeConfig.themeConfig.isRequestRoutes) {
|
||||
@@ -222,10 +232,13 @@ export default defineComponent({
|
||||
// 如果是复制粘贴的路径,非首页/登录页,那么登录成功后重定向到对应的路径中
|
||||
route.query?.redirect ? router.push(route.query.redirect as string) : router.push('/');
|
||||
// 登录成功提示
|
||||
setTimeout(() => {
|
||||
setTimeout(async () => {
|
||||
// 关闭 loading
|
||||
state.loading.signIn = true;
|
||||
ElMessage.success(`${currentTimeInfo},欢迎回来!`);
|
||||
if (await useWartermark()) {
|
||||
setUseWatermark2Session(true);
|
||||
}
|
||||
}, 300);
|
||||
};
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="env" label="env" label-width="33px">
|
||||
<el-select style="width: 80px" v-model="envId" placeholder="环境" @change="changeEnv" filterable>
|
||||
<el-select style="width: 85px" v-model="envId" placeholder="环境" @change="changeEnv" filterable>
|
||||
<el-option v-for="item in envs" :key="item.id" :label="item.name" :value="item.id">
|
||||
<span style="float: left">{{ item.name }}</span>
|
||||
<span style="float: right; color: #8492a6; font-size: 13px">{{ item.remark }}</span>
|
||||
|
||||
81
mayfly_go_web/src/views/ops/component/TagSelect.vue
Normal file
81
mayfly_go_web/src/views/ops/component/TagSelect.vue
Normal file
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-tree-select
|
||||
@check="changeTag"
|
||||
style="width: 100%"
|
||||
v-model="selectTags"
|
||||
:data="tags"
|
||||
:render-after-expand="true"
|
||||
:default-expanded-keys="[selectTags]"
|
||||
show-checkbox
|
||||
check-strictly
|
||||
node-key="id"
|
||||
:props="{
|
||||
value: 'id',
|
||||
label: 'codePath',
|
||||
children: 'children',
|
||||
}"
|
||||
>
|
||||
<template #default="{ data }">
|
||||
<span class="custom-tree-node">
|
||||
<span style="font-size: 13px">
|
||||
{{ data.code }}
|
||||
<span style="color: #3c8dbc">【</span>
|
||||
{{ data.name }}
|
||||
<span style="color: #3c8dbc">】</span>
|
||||
<el-tag v-if="data.children !== null" size="small">{{ data.children.length }}</el-tag>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree-select>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, reactive, defineComponent, onMounted } from 'vue';
|
||||
import { tagApi } from '../tag/api';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'TagSelect',
|
||||
props: {
|
||||
tagId: {
|
||||
type: Number,
|
||||
},
|
||||
tagPath: {
|
||||
type: String,
|
||||
},
|
||||
},
|
||||
setup(props: any, { emit }) {
|
||||
const state = reactive({
|
||||
tags: [],
|
||||
// 单选则为id,多选为id数组
|
||||
selectTags: null as any,
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
if (props.tagId) {
|
||||
state.selectTags = props.tagId;
|
||||
}
|
||||
state.tags = await tagApi.getTagTrees.request(null);
|
||||
});
|
||||
|
||||
const changeTag = (tag: any, checkInfo: any) => {
|
||||
if (checkInfo.checkedNodes.length > 0) {
|
||||
emit('update:tagId', tag.id);
|
||||
emit('update:tagPath', tag.codePath);
|
||||
emit('changeTag', tag);
|
||||
} else {
|
||||
emit('update:tagId', null);
|
||||
emit('update:tagPath', null);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
changeTag,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
</style>
|
||||
@@ -2,17 +2,10 @@
|
||||
<div>
|
||||
<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>
|
||||
</el-select>
|
||||
<el-form-item prop="tagId" label="标签:" required>
|
||||
<tag-select v-model:tag-id="form.tagId" v-model:tag-path="form.tagPath" style="width: 100%" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="envId" label="环境:" required>
|
||||
<el-select @change="changeEnv" style="width: 100%" v-model="form.envId" placeholder="请选择环境">
|
||||
<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="name" label="别名:" required>
|
||||
<el-input v-model.trim="form.name" placeholder="请输入数据库别名" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
@@ -24,7 +17,7 @@
|
||||
</el-form-item>
|
||||
<el-form-item prop="host" label="host:" required>
|
||||
<el-col :span="18">
|
||||
<el-input v-model.trim="form.host" placeholder="请输入主机ip" auto-complete="off"></el-input>
|
||||
<el-input :disabled="form.id" v-model.trim="form.host" placeholder="请输入主机ip" auto-complete="off"></el-input>
|
||||
</el-col>
|
||||
<el-col style="text-align: center" :span="1">:</el-col>
|
||||
<el-col :span="5">
|
||||
@@ -41,34 +34,43 @@
|
||||
v-model.trim="form.password"
|
||||
placeholder="请输入密码,修改操作可不填"
|
||||
autocomplete="new-password"
|
||||
></el-input>
|
||||
>
|
||||
<template v-if="form.id && form.id != 0" #suffix>
|
||||
<el-popover @hide="pwd = ''" placement="right" title="原密码" :width="200" trigger="click" :content="pwd">
|
||||
<template #reference>
|
||||
<el-link @click="getDbPwd" :underline="false" type="primary" class="mr5">原密码</el-link>
|
||||
</template>
|
||||
</el-popover>
|
||||
</template>
|
||||
</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"
|
||||
:key="db"
|
||||
class="ml5 mt5"
|
||||
type="success"
|
||||
effect="plain"
|
||||
closable
|
||||
:disable-transitions="false"
|
||||
@close="handleClose(db)"
|
||||
>
|
||||
{{ db }}
|
||||
</el-tag>
|
||||
<el-input
|
||||
v-if="inputDbVisible"
|
||||
ref="InputDbRef"
|
||||
v-model="inputDbValue"
|
||||
style="width: 120px; margin-left: 5px; margin-top: 5px"
|
||||
size="small"
|
||||
@keyup.enter="handleInputDbConfirm"
|
||||
@blur="handleInputDbConfirm"
|
||||
/>
|
||||
<el-button v-else class="ml5 mt5" size="small" @click="showInputDb"> + 添加数据库 </el-button>
|
||||
<el-col :span="19">
|
||||
<el-select
|
||||
@change="changeDatabase"
|
||||
v-model="databaseList"
|
||||
multiple
|
||||
collapse-tags
|
||||
collapse-tags-tooltip
|
||||
filterable
|
||||
allow-create
|
||||
placeholder="请确保数据库实例信息填写完整后获取库名"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option v-for="db in allDatabases" :key="db" :label="db" :value="db" />
|
||||
</el-select>
|
||||
</el-col>
|
||||
<el-col style="text-align: center" :span="1"><el-divider direction="vertical" border-style="dashed" /></el-col>
|
||||
<el-col :span="4">
|
||||
<el-link @click="getAllDatabase" :underline="false" type="success">获取库名</el-link>
|
||||
</el-col>
|
||||
</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-item prop="enableSshTunnel" label="SSH隧道:">
|
||||
@@ -101,17 +103,19 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, reactive, nextTick, watch, defineComponent, ref } from 'vue';
|
||||
import { toRefs, reactive, watch, defineComponent, ref } from 'vue';
|
||||
import { dbApi } from './api';
|
||||
import { projectApi } from '../project/api.ts';
|
||||
import { machineApi } from '../machine/api.ts';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import type { ElInput } from 'element-plus';
|
||||
import { notBlank } from '@/common/assert';
|
||||
import { RsaEncrypt } from '@/common/rsa';
|
||||
import TagSelect from '../component/TagSelect.vue';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'DbEdit',
|
||||
components: {
|
||||
TagSelect,
|
||||
},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
@@ -128,19 +132,21 @@ export default defineComponent({
|
||||
},
|
||||
setup(props: any, { emit }) {
|
||||
const dbForm: any = ref(null);
|
||||
const InputDbRef = ref<InstanceType<typeof ElInput>>();
|
||||
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
projects: [],
|
||||
envs: [],
|
||||
allDatabases: [] as any,
|
||||
databaseList: [] as any,
|
||||
sshTunnelMachineList: [],
|
||||
inputDbVisible: false,
|
||||
inputDbValue: '',
|
||||
sshTunnelMachineList: [] as any,
|
||||
form: {
|
||||
id: null,
|
||||
tagId: null as any,
|
||||
tagPath: null as any,
|
||||
type: null,
|
||||
name: null,
|
||||
host: '',
|
||||
port: 3306,
|
||||
username: null,
|
||||
password: null,
|
||||
@@ -150,9 +156,12 @@ export default defineComponent({
|
||||
projectId: null,
|
||||
envId: null,
|
||||
env: null,
|
||||
remark: '',
|
||||
enableSshTunnel: null,
|
||||
sshTunnelMachineId: null,
|
||||
},
|
||||
// 原密码
|
||||
pwd: '',
|
||||
btnLoading: false,
|
||||
rules: {
|
||||
projectId: [
|
||||
@@ -214,7 +223,6 @@ export default defineComponent({
|
||||
}
|
||||
state.projects = newValue.projects;
|
||||
if (newValue.db) {
|
||||
getEnvs(newValue.db.projectId);
|
||||
state.form = { ...newValue.db };
|
||||
// 将数据库名使用空格切割,获取所有数据库列表
|
||||
state.databaseList = newValue.db.database.split(' ');
|
||||
@@ -226,27 +234,6 @@ export default defineComponent({
|
||||
getSshTunnelMachines();
|
||||
});
|
||||
|
||||
const handleClose = (db: string) => {
|
||||
state.databaseList.splice(state.databaseList.indexOf(db), 1);
|
||||
changeDatabase();
|
||||
};
|
||||
|
||||
const showInputDb = () => {
|
||||
state.inputDbVisible = true;
|
||||
nextTick(() => {
|
||||
InputDbRef.value!.input!.focus();
|
||||
});
|
||||
};
|
||||
|
||||
const handleInputDbConfirm = () => {
|
||||
if (state.inputDbValue) {
|
||||
state.databaseList.push(state.inputDbValue);
|
||||
changeDatabase();
|
||||
}
|
||||
state.inputDbVisible = false;
|
||||
state.inputDbValue = '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 改变表单中的数据库字段,方便表单错误提示。如全部删光,可提示请添加数据库
|
||||
*/
|
||||
@@ -261,22 +248,6 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const getEnvs = async (projectId: any) => {
|
||||
state.envs = await projectApi.projectEnvs.request({ projectId });
|
||||
};
|
||||
|
||||
const changeProject = (projectId: number) => {
|
||||
for (let p of state.projects as any) {
|
||||
if (p.id == projectId) {
|
||||
state.form.project = p.name;
|
||||
}
|
||||
}
|
||||
state.form.envId = null;
|
||||
state.form.env = null;
|
||||
state.envs = [];
|
||||
getEnvs(projectId);
|
||||
};
|
||||
|
||||
const changeEnv = (envId: number) => {
|
||||
for (let p of state.envs as any) {
|
||||
if (p.id == envId) {
|
||||
@@ -285,6 +256,17 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const getAllDatabase = async () => {
|
||||
const reqForm = { ...state.form };
|
||||
reqForm.password = await RsaEncrypt(reqForm.password);
|
||||
state.allDatabases = await dbApi.getAllDatabase.request(reqForm);
|
||||
ElMessage.success('获取成功, 请选择需要管理操作的数据库');
|
||||
};
|
||||
|
||||
const getDbPwd = async () => {
|
||||
state.pwd = await dbApi.getDbPwd.request({ id: state.form.id });
|
||||
};
|
||||
|
||||
const btnOk = async () => {
|
||||
if (!state.form.id) {
|
||||
notBlank(state.form.password, '新增操作,密码不可为空');
|
||||
@@ -293,7 +275,6 @@ export default defineComponent({
|
||||
if (valid) {
|
||||
const reqForm = { ...state.form };
|
||||
reqForm.password = await RsaEncrypt(reqForm.password);
|
||||
// reqForm.ssh_pass = await RsaEncrypt(reqForm.ssh_pass);
|
||||
dbApi.saveDb.request(reqForm).then(() => {
|
||||
ElMessage.success('保存成功');
|
||||
emit('val-change', state.form);
|
||||
@@ -312,9 +293,8 @@ export default defineComponent({
|
||||
};
|
||||
|
||||
const resetInputDb = () => {
|
||||
state.inputDbVisible = false;
|
||||
state.databaseList = [];
|
||||
state.inputDbValue = '';
|
||||
state.allDatabases = [];
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
@@ -328,12 +308,10 @@ export default defineComponent({
|
||||
return {
|
||||
...toRefs(state),
|
||||
dbForm,
|
||||
InputDbRef,
|
||||
handleClose,
|
||||
showInputDb,
|
||||
handleInputDbConfirm,
|
||||
getAllDatabase,
|
||||
getDbPwd,
|
||||
changeDatabase,
|
||||
getSshTunnelMachines,
|
||||
changeProject,
|
||||
changeEnv,
|
||||
btnOk,
|
||||
cancel,
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
>删除</el-button
|
||||
>
|
||||
<div style="float: right">
|
||||
<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 @focus="getTags" v-model="query.tagPath" placeholder="请选择标签" filterable clearable>
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-button v-waves type="primary" icon="search" @click="search()" class="ml5">查询</el-button>
|
||||
</div>
|
||||
@@ -20,8 +20,7 @@
|
||||
</el-radio>
|
||||
</template>
|
||||
</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="tagPath" label="标签路径" min-width="150" show-overflow-tooltip></el-table-column>
|
||||
<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">
|
||||
@@ -29,24 +28,30 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="type" label="类型" min-width="90"></el-table-column>
|
||||
<el-table-column prop="database" label="数据库" min-width="160">
|
||||
<el-table-column prop="database" label="数据库" min-width="80">
|
||||
<template #default="scope">
|
||||
<el-tag
|
||||
@click="showTableInfo(scope.row, db)"
|
||||
effect="plain"
|
||||
type="success"
|
||||
size="small"
|
||||
v-for="db in scope.row.dbs"
|
||||
:key="db"
|
||||
style="cursor: pointer; margin-left: 3px"
|
||||
>{{ db }}</el-tag
|
||||
>
|
||||
<el-popover :width="250" placement="right" trigger="click">
|
||||
<template #reference>
|
||||
<el-link type="primary" :underline="false" plain>查看</el-link>
|
||||
</template>
|
||||
<el-tag
|
||||
@click="showTableInfo(scope.row, db)"
|
||||
effect="plain"
|
||||
type="success"
|
||||
size="small"
|
||||
v-for="db in scope.row.dbs"
|
||||
:key="db"
|
||||
style="cursor: pointer; margin-left: 3px; margin-bottom: 3px"
|
||||
>{{ db }}</el-tag
|
||||
>
|
||||
</el-popover>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="username" label="用户名" min-width="100"></el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
|
||||
|
||||
<el-table-column min-width="115" prop="creator" label="创建账号"></el-table-column>
|
||||
<el-table-column min-width="160" prop="createTime" label="创建时间">
|
||||
<el-table-column min-width="160" prop="createTime" label="创建时间" show-overflow-tooltip>
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
@@ -100,9 +105,17 @@
|
||||
|
||||
<el-button type="primary" size="small" @click="tableCreateDialog.visible = true">创建表</el-button>
|
||||
</el-row>
|
||||
<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 v-loading="tableInfoDialog.loading" border stripe :data="filterTableInfos" size="small">
|
||||
<el-table-column property="tableName" label="表名" min-width="150" show-overflow-tooltip>
|
||||
<template #header>
|
||||
<el-input v-model="tableInfoDialog.tableNameSearch" size="small" placeholder="表名: 输入可过滤" clearable />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column property="tableComment" label="备注" min-width="150" show-overflow-tooltip>
|
||||
<template #header>
|
||||
<el-input v-model="tableInfoDialog.tableCommentSearch" size="small" placeholder="备注: 输入可过滤" clearable />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="tableRows"
|
||||
label="Rows"
|
||||
@@ -153,8 +166,10 @@
|
||||
v-model="sqlExecLogDialog.visible"
|
||||
>
|
||||
<div class="toolbar">
|
||||
<el-input v-model="sqlExecLogDialog.query.db" placeholder="请输入数据库名" clearable style="width: 150px" />
|
||||
<el-input v-model="sqlExecLogDialog.query.table" placeholder="请输入表名" clearable class="ml5" style="width: 150px" />
|
||||
<el-select v-model="sqlExecLogDialog.query.db" placeholder="请选择数据库" filterable clearable>
|
||||
<el-option v-for="item in sqlExecLogDialog.dbs" :key="item" :label="`${item}`" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-input v-model="sqlExecLogDialog.query.table" placeholder="请输入表名" clearable class="ml5" style="width: 180px" />
|
||||
<el-select v-model="sqlExecLogDialog.query.type" placeholder="请选择操作类型" clearable class="ml5">
|
||||
<el-option v-for="item in enums.DbSqlExecTypeEnum" :key="item.value" :label="item.label" :value="item.value"> </el-option>
|
||||
</el-select>
|
||||
@@ -175,7 +190,7 @@
|
||||
<el-table-column prop="creator" label="执行人" min-width="60" show-overflow-tooltip> </el-table-column>
|
||||
<el-table-column prop="createTime" label="执行时间" show-overflow-tooltip>
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
{{ dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="60" show-overflow-tooltip> </el-table-column>
|
||||
@@ -234,28 +249,28 @@
|
||||
|
||||
<db-edit
|
||||
@val-change="valChange"
|
||||
:projects="projects"
|
||||
:title="dbEditDialog.title"
|
||||
v-model:visible="dbEditDialog.visible"
|
||||
v-model:db="dbEditDialog.data"
|
||||
></db-edit>
|
||||
<create-table :dbId="dbId" v-model:visible="tableCreateDialog.visible"></create-table>
|
||||
<create-table :dbId="dbId" :db="db" v-model:visible="tableCreateDialog.visible"></create-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang='ts'>
|
||||
import { toRefs, reactive, onMounted, defineComponent } from 'vue';
|
||||
import { toRefs, reactive, computed, onMounted, defineComponent } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { formatByteSize } from '@/common/utils/format';
|
||||
import DbEdit from './DbEdit.vue';
|
||||
import CreateTable from './CreateTable.vue';
|
||||
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';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'DbList',
|
||||
@@ -271,7 +286,7 @@ export default defineComponent({
|
||||
saveDb: 'db:save',
|
||||
delDb: 'db:del',
|
||||
},
|
||||
projects: [],
|
||||
tags: [],
|
||||
chooseId: null,
|
||||
/**
|
||||
* 选中的数据
|
||||
@@ -281,6 +296,7 @@ export default defineComponent({
|
||||
* 查询条件
|
||||
*/
|
||||
query: {
|
||||
tagPath: null,
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
},
|
||||
@@ -299,6 +315,7 @@ export default defineComponent({
|
||||
visible: false,
|
||||
data: [],
|
||||
total: 0,
|
||||
dbs: [],
|
||||
query: {
|
||||
dbId: 0,
|
||||
db: '',
|
||||
@@ -317,6 +334,8 @@ export default defineComponent({
|
||||
loading: false,
|
||||
visible: false,
|
||||
infos: [],
|
||||
tableNameSearch: '',
|
||||
tableCommentSearch: '',
|
||||
},
|
||||
columnDialog: {
|
||||
visible: false,
|
||||
@@ -342,7 +361,26 @@ export default defineComponent({
|
||||
|
||||
onMounted(async () => {
|
||||
search();
|
||||
state.projects = await projectApi.accountProjects.request(null);
|
||||
});
|
||||
|
||||
const filterTableInfos = computed(() => {
|
||||
const infos = state.tableInfoDialog.infos;
|
||||
const tableNameSearch = state.tableInfoDialog.tableNameSearch;
|
||||
const tableCommentSearch = state.tableInfoDialog.tableCommentSearch;
|
||||
if (!tableNameSearch && !tableCommentSearch) {
|
||||
return infos;
|
||||
}
|
||||
return infos.filter((data: any) => {
|
||||
let tnMatch = true;
|
||||
let tcMatch = true;
|
||||
if (tableNameSearch) {
|
||||
tnMatch = data.tableName.toLowerCase().includes(tableNameSearch.toLowerCase());
|
||||
}
|
||||
if (tableCommentSearch) {
|
||||
tcMatch = data.tableComment.includes(tableCommentSearch);
|
||||
}
|
||||
return tnMatch && tcMatch;
|
||||
});
|
||||
});
|
||||
|
||||
const choose = (item: any) => {
|
||||
@@ -369,7 +407,11 @@ export default defineComponent({
|
||||
search();
|
||||
};
|
||||
|
||||
const editDb = (isAdd = false) => {
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const editDb = async (isAdd = false) => {
|
||||
if (isAdd) {
|
||||
state.dbEditDialog.data = null;
|
||||
state.dbEditDialog.title = '新增数据库资源';
|
||||
@@ -404,6 +446,7 @@ export default defineComponent({
|
||||
const onShowSqlExec = async (row: any) => {
|
||||
state.sqlExecLogDialog.title = `${row.name}[${row.host}:${row.port}]`;
|
||||
state.sqlExecLogDialog.query.dbId = row.id;
|
||||
state.sqlExecLogDialog.dbs = row.database.split(' ');
|
||||
searchSqlExecLog();
|
||||
state.sqlExecLogDialog.visible = true;
|
||||
};
|
||||
@@ -411,6 +454,7 @@ export default defineComponent({
|
||||
const onBeforeCloseSqlExecDialog = () => {
|
||||
state.sqlExecLogDialog.visible = false;
|
||||
state.sqlExecLogDialog.data = [];
|
||||
state.sqlExecLogDialog.dbs = [];
|
||||
state.sqlExecLogDialog.total = 0;
|
||||
state.sqlExecLogDialog.query.dbId = 0;
|
||||
state.sqlExecLogDialog.query.pageNum = 1;
|
||||
@@ -502,6 +546,8 @@ export default defineComponent({
|
||||
state.tableInfoDialog.infos = await dbApi.tableInfos.request({ id: row.id, db });
|
||||
state.dbId = row.id;
|
||||
state.db = db;
|
||||
} catch (e) {
|
||||
state.tableInfoDialog.visible = false;
|
||||
} finally {
|
||||
state.tableInfoDialog.loading = false;
|
||||
}
|
||||
@@ -570,6 +616,9 @@ export default defineComponent({
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
dateFormat,
|
||||
getTags,
|
||||
filterTableInfos,
|
||||
enums,
|
||||
search,
|
||||
choose,
|
||||
|
||||
@@ -1,52 +1,58 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-button-group :style="btnStyle">
|
||||
<el-button @click="onRunSql" type="success" icon="video-play" size="small" plain>执行</el-button>
|
||||
<el-button @click="formatSql" type="primary" icon="magic-stick" size="small" plain>格式化</el-button>
|
||||
</el-button-group>
|
||||
<div class="toolbar">
|
||||
<el-row type="flex" justify="space-between">
|
||||
<el-col :span="24">
|
||||
<project-env-select @changeProjectEnv="changeProjectEnv">
|
||||
<template #default>
|
||||
<el-form-item label="资源">
|
||||
<el-select v-model="dbId" placeholder="请选择资源实例" @change="changeDbInstance" filterable style="width: 150px">
|
||||
<el-option v-for="item in dbs" :key="item.id" :label="item.name" :value="item.id">
|
||||
<span style="float: left">{{ item.name }}</span>
|
||||
<span style="float: right; color: #8492a6; margin-left: 6px; font-size: 13px">{{
|
||||
`${item.host}:${item.port} ${item.type}`
|
||||
}}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form class="search-form" label-position="right" :inline="true">
|
||||
<el-form-item label="标签">
|
||||
<el-select @change="changeTag" @focus="getTags" v-model="params.tagPath" placeholder="请选择标签" filterable style="width: 220px">
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="数据库">
|
||||
<el-select
|
||||
v-model="db"
|
||||
placeholder="请选择数据库"
|
||||
@change="changeDb"
|
||||
@clear="clearDb"
|
||||
clearable
|
||||
filterable
|
||||
style="width: 150px"
|
||||
<el-form-item label="资源">
|
||||
<el-select v-model="dbId" placeholder="请选择资源实例" @change="changeDbInstance" filterable style="width: 220px">
|
||||
<el-option v-for="item in dbs" :key="item.id" :label="`${item.name} [${item.tagPath}]`" :value="item.id">
|
||||
<span style="float: left">{{ `${item.name} [${item.tagPath}]` }}</span>
|
||||
<span style="float: rignt; color: #8492a6; margin-left: 10px; font-size: 13px">{{
|
||||
`${item.host}:${item.port} ${item.type}`
|
||||
}}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="数据库">
|
||||
<el-select
|
||||
v-model="db"
|
||||
placeholder="请选择数据库"
|
||||
@change="changeDb"
|
||||
@clear="clearDb"
|
||||
clearable
|
||||
filterable
|
||||
style="width: 150px"
|
||||
>
|
||||
<el-option v-for="item in databaseList" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label-width="20" label="表">
|
||||
<el-select v-model="tableName" placeholder="选择表查看表数据" @change="changeTable" filterable style="width: 250px">
|
||||
<el-option
|
||||
v-for="item in tableMetadata"
|
||||
:key="item.tableName"
|
||||
:label="item.tableName + (item.tableComment != '' ? `【${item.tableComment}】` : '')"
|
||||
:value="item.tableName"
|
||||
>
|
||||
<el-option v-for="item in databaseList" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-form-item label-width="20" label="表">
|
||||
<el-select v-model="tableName" placeholder="选择表查看表数据" @change="changeTable" filterable style="width: 250px">
|
||||
<el-option
|
||||
v-for="item in tableMetadata"
|
||||
:key="item.tableName"
|
||||
:label="item.tableName + (item.tableComment != '' ? `【${item.tableComment}】` : '')"
|
||||
:value="item.tableName"
|
||||
>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<!-- <project-env-select @changeTag="changeTag">
|
||||
<template #default>
|
||||
|
||||
</template>
|
||||
</project-env-select>
|
||||
</project-env-select> -->
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
@@ -58,6 +64,19 @@
|
||||
<div>
|
||||
<div class="toolbar">
|
||||
<div class="fl">
|
||||
<el-link @click="onRunSql" :underline="false" class="ml15" icon="VideoPlay"></el-link>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-tooltip class="box-item" effect="dark" content="format sql" placement="top">
|
||||
<el-link @click="formatSql" type="primary" :underline="false" icon="MagicStick"></el-link>
|
||||
</el-tooltip>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-tooltip class="box-item" effect="dark" content="commit" placement="top">
|
||||
<el-link @click="onCommit" type="success" :underline="false" icon="CircleCheck"></el-link>
|
||||
</el-tooltip>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-upload
|
||||
style="display: inline-block"
|
||||
:before-upload="beforeUpload"
|
||||
@@ -72,11 +91,10 @@
|
||||
multiple
|
||||
:limit="100"
|
||||
>
|
||||
<el-button type="success" icon="video-play" plain size="small">sql脚本执行</el-button>
|
||||
<el-tooltip class="box-item" effect="dark" content="SQL脚本执行" placement="top">
|
||||
<el-link type="success" :underline="false" icon="Document"></el-link>
|
||||
</el-tooltip>
|
||||
</el-upload>
|
||||
<el-button @click="onCommit" class="ml5 mb5" type="success" icon="CircleCheck" plain size="small"
|
||||
>commit</el-button
|
||||
>
|
||||
</div>
|
||||
|
||||
<div style="float: right" class="fl">
|
||||
@@ -101,13 +119,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div @click="closeExecBtns" class="mt5 sqlEditor" @contextmenu="showExecBtns">
|
||||
<div class="mt5 sqlEditor">
|
||||
<textarea ref="codeTextarea"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="mt5">
|
||||
<el-row v-if="queryTab.nowTableName">
|
||||
<el-link @click="onDeleteData" class="ml5" type="danger" icon="delete" :underline="false"></el-link>
|
||||
<el-row>
|
||||
<el-link
|
||||
v-if="queryTab.nowTableName"
|
||||
@click="onDeleteData"
|
||||
class="ml5"
|
||||
type="danger"
|
||||
icon="delete"
|
||||
:underline="false"
|
||||
></el-link>
|
||||
|
||||
<span v-if="queryTab.execRes.data.length > 0">
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
<el-link type="success" :underline="false" @click="exportData"><span style="font-size: 12px">导出</span></el-link>
|
||||
</span>
|
||||
</el-row>
|
||||
<el-table
|
||||
@cell-dblclick="cellClick"
|
||||
@@ -145,46 +175,60 @@
|
||||
|
||||
<el-tab-pane closable v-for="dt in dataTabs" :key="dt.name" :label="dt.label" :name="dt.name">
|
||||
<el-row v-if="dbId">
|
||||
<el-link @click="onRefresh(dt.name)" icon="refresh" :underline="false" class="ml5"></el-link>
|
||||
<el-link @click="addRow" class="ml5" type="primary" icon="plus" :underline="false"></el-link>
|
||||
<el-link @click="onDeleteData" class="ml5" type="danger" icon="delete" :underline="false"></el-link>
|
||||
<el-col :span="8">
|
||||
<el-link @click="onRefresh(dt.name)" icon="refresh" :underline="false" class="ml5"></el-link>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-tooltip class="box-item" effect="dark" content="commit" placement="top">
|
||||
<el-link @click="onCommit" class="ml5" type="success" icon="check" :underline="false"></el-link>
|
||||
</el-tooltip>
|
||||
</el-row>
|
||||
<el-row class="mt5">
|
||||
<el-input
|
||||
v-model="dt.condition"
|
||||
placeholder="若需条件过滤,可选择列并点击对应的字段并输入需要过滤的内容点击查询按钮即可"
|
||||
clearable
|
||||
size="small"
|
||||
>
|
||||
<template #prepend>
|
||||
<el-popover trigger="click" :width="270" placement="right">
|
||||
<template #reference>
|
||||
<el-link type="success" :underline="false">选择列</el-link>
|
||||
</template>
|
||||
<el-table
|
||||
:data="getColumns4Map(dt.name)"
|
||||
max-height="500"
|
||||
size="small"
|
||||
@row-click="
|
||||
(...event) => {
|
||||
onConditionRowClick(event, dt);
|
||||
}
|
||||
"
|
||||
>
|
||||
<el-table-column property="columnName" label="列名" show-overflow-tooltip> </el-table-column>
|
||||
<el-table-column property="columnComment" label="备注" show-overflow-tooltip> </el-table-column>
|
||||
</el-table>
|
||||
</el-popover>
|
||||
</template>
|
||||
<el-link @click="addRow" type="primary" icon="plus" :underline="false"></el-link>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<template #append>
|
||||
<el-button @click="selectByCondition(dt.name, dt.condition)" icon="search" size="small"></el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-link @click="onDeleteData" type="danger" icon="delete" :underline="false"></el-link>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-tooltip class="box-item" effect="dark" content="commit" placement="top">
|
||||
<el-link @click="onCommit" type="success" icon="CircleCheck" :underline="false"></el-link>
|
||||
</el-tooltip>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-tooltip class="box-item" effect="dark" content="生成insert sql" placement="top">
|
||||
<el-link @click="onGenerateInsertSql" type="success" :underline="false">gi</el-link>
|
||||
</el-tooltip>
|
||||
</el-col>
|
||||
<el-col :span="16">
|
||||
<el-input
|
||||
v-model="dt.condition"
|
||||
placeholder="若需条件过滤,可选择列并点击对应的字段并输入需要过滤的内容点击查询按钮即可"
|
||||
clearable
|
||||
size="small"
|
||||
style="width: 100%"
|
||||
>
|
||||
<template #prepend>
|
||||
<el-popover trigger="click" :width="320" placement="right">
|
||||
<template #reference>
|
||||
<el-link type="success" :underline="false">选择列</el-link>
|
||||
</template>
|
||||
<el-table
|
||||
:data="getColumns4Map(dt.name)"
|
||||
max-height="500"
|
||||
size="small"
|
||||
@row-click="
|
||||
(...event) => {
|
||||
onConditionRowClick(event, dt);
|
||||
}
|
||||
"
|
||||
style="cursor: pointer"
|
||||
>
|
||||
<el-table-column property="columnName" label="列名" show-overflow-tooltip> </el-table-column>
|
||||
<el-table-column property="columnComment" label="备注" show-overflow-tooltip> </el-table-column>
|
||||
</el-table>
|
||||
</el-popover>
|
||||
</template>
|
||||
|
||||
<template #append>
|
||||
<el-button @click="selectByCondition(dt.name, dt.condition)" icon="search" size="small"></el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-table
|
||||
@cell-dblclick="cellClick"
|
||||
@@ -233,6 +277,34 @@
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</el-container>
|
||||
|
||||
<el-dialog v-model="conditionDialog.visible" :title="conditionDialog.title" width="420px">
|
||||
<el-row>
|
||||
<el-col :span="5">
|
||||
<el-select v-model="conditionDialog.condition">
|
||||
<el-option label="=" value="="> </el-option>
|
||||
<el-option label="LIKE" value="LIKE"> </el-option>
|
||||
<el-option label=">" value=">"> </el-option>
|
||||
<el-option label=">=" value=">="> </el-option>
|
||||
<el-option label="<" value="<"> </el-option>
|
||||
<el-option label="<=" value="<="> </el-option>
|
||||
</el-select>
|
||||
</el-col>
|
||||
<el-col :span="19">
|
||||
<el-input v-model="conditionDialog.value" :placeholder="conditionDialog.placeholder" />
|
||||
</el-col>
|
||||
</el-row>
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="onCancelCondition">取消</el-button>
|
||||
<el-button type="primary" @click="onConfirmCondition">确定</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog @close="genSqlDialog.visible = false" v-model="genSqlDialog.visible" title="SQL" width="1000px">
|
||||
<el-input v-model="genSqlDialog.sql" type="textarea" rows="20" />
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -254,16 +326,15 @@ import 'codemirror/addon/hint/sql-hint.js';
|
||||
import { format as sqlFormatter } from 'sql-formatter';
|
||||
import { notBlank, notEmpty, isTrue } from '@/common/assert';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import ProjectEnvSelect from '../component/ProjectEnvSelect.vue';
|
||||
import config from '@/common/config';
|
||||
import { getSession } from '@/common/utils/storage';
|
||||
import SqlExecBox from './component/SqlExecBox';
|
||||
import { dateStrFormat } from '@/common/utils/date.ts';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'SqlExec',
|
||||
components: {
|
||||
ProjectEnvSelect,
|
||||
},
|
||||
components: {},
|
||||
setup() {
|
||||
const codeTextarea: any = ref(null);
|
||||
const token = getSession('token');
|
||||
@@ -273,11 +344,12 @@ export default defineComponent({
|
||||
const state = reactive({
|
||||
token: token,
|
||||
defalutLimit: 20, // 默认查询数量
|
||||
dbs: [], // 数据库实例列表
|
||||
tags: [],
|
||||
dbs: [] as any, // 数据库实例列表
|
||||
databaseList: [], // 数据库实例拥有的数据库列表,1数据库实例 -> 多数据库
|
||||
db: '', // 当前操作的数据库
|
||||
dbType: '',
|
||||
tables: [],
|
||||
tables: [] as any,
|
||||
dbId: null, // 当前选中操作的数据库实例
|
||||
tableName: '',
|
||||
tableMetadata: [],
|
||||
@@ -286,7 +358,7 @@ export default defineComponent({
|
||||
activeName: 'Query',
|
||||
queryTabName: 'Query',
|
||||
nowTableName: '', // 当前表格数据操作的数据库表名,用于双击编辑表内容使用
|
||||
dataTabs: {}, // 点击表信息后执行结果数据展示tabs
|
||||
dataTabs: {} as any, // 点击表信息后执行结果数据展示tabs
|
||||
dataTabsTableHeight: 600,
|
||||
// 查询tab
|
||||
queryTab: {
|
||||
@@ -303,15 +375,21 @@ export default defineComponent({
|
||||
},
|
||||
params: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
envId: null,
|
||||
pageSize: 100,
|
||||
tagPath: null,
|
||||
},
|
||||
btnStyle: {
|
||||
position: 'absolute',
|
||||
zIndex: 1000,
|
||||
display: 'none',
|
||||
left: '',
|
||||
top: '',
|
||||
conditionDialog: {
|
||||
title: '',
|
||||
placeholder: '',
|
||||
columnRow: null,
|
||||
dataTab: null,
|
||||
visible: false,
|
||||
condition: '=',
|
||||
value: null,
|
||||
},
|
||||
genSqlDialog: {
|
||||
visible: false,
|
||||
sql: '',
|
||||
},
|
||||
cmOptions: {
|
||||
tabSize: 4,
|
||||
@@ -365,22 +443,23 @@ export default defineComponent({
|
||||
const setHeight = () => {
|
||||
// 默认300px
|
||||
codemirror.setSize('auto', `${window.innerHeight - 538}px`);
|
||||
state.dataTabsTableHeight = window.innerHeight - 258 - 33;
|
||||
state.dataTabsTableHeight = window.innerHeight - 274;
|
||||
};
|
||||
|
||||
/**
|
||||
* 项目及环境更改后的回调事件
|
||||
*/
|
||||
const changeProjectEnv = (projectId: any, envId: any) => {
|
||||
const changeTag = () => {
|
||||
state.dbs = [];
|
||||
state.dbId = null;
|
||||
state.db = '';
|
||||
state.databaseList = [];
|
||||
clearDb();
|
||||
if (envId != null) {
|
||||
state.params.envId = envId;
|
||||
search();
|
||||
}
|
||||
search();
|
||||
};
|
||||
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const onBeforeChange = (instance: any, changeObj: any) => {
|
||||
@@ -434,7 +513,6 @@ export default defineComponent({
|
||||
} catch (e: any) {
|
||||
state.queryTab.loading = false;
|
||||
}
|
||||
closeExecBtns();
|
||||
|
||||
// 即只有以该字符串开头的sql才可修改表数据内容
|
||||
if (sql.startsWith('SELECT *') || sql.startsWith('select *') || sql.startsWith('SELECT\n *')) {
|
||||
@@ -454,6 +532,36 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const exportData = () => {
|
||||
const dataList = state.queryTab.execRes.data;
|
||||
isTrue(dataList.length > 0, '没有数据可导出');
|
||||
|
||||
const tableColumn = state.queryTab.execRes.tableColumn;
|
||||
// 二维数组
|
||||
const cvsData = [tableColumn];
|
||||
for (let data of dataList) {
|
||||
// 数据值组成的一维数组
|
||||
let dataValueArr: any = [];
|
||||
for (let column of tableColumn) {
|
||||
dataValueArr.push(data[column]);
|
||||
}
|
||||
cvsData.push(dataValueArr);
|
||||
}
|
||||
const csvString = cvsData.map((e) => e.join(',')).join('\n');
|
||||
|
||||
// 导出
|
||||
let link = document.createElement('a');
|
||||
let exportContent = '\uFEFF';
|
||||
let blob = new Blob([exportContent + csvString], {
|
||||
type: 'text/plain;charset=utrf-8',
|
||||
});
|
||||
link.id = 'download-csv';
|
||||
link.setAttribute('href', URL.createObjectURL(blob));
|
||||
link.setAttribute('download', `查询数据导出-${dateStrFormat('yyyyMMddHHmmss', new Date())}.csv`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
};
|
||||
|
||||
/**
|
||||
* 执行sql str
|
||||
*
|
||||
@@ -717,23 +825,34 @@ export default defineComponent({
|
||||
*/
|
||||
const onConditionRowClick = (event: any, dataTab: any) => {
|
||||
const row = event[0];
|
||||
ElMessageBox.prompt(`请输入 [${row.columnName}] 的值`, '查询条件', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
inputPlaceholder: `${row.columnType} ${row.columnComment}`,
|
||||
})
|
||||
.then(({ value }) => {
|
||||
if (!value) {
|
||||
value = '';
|
||||
}
|
||||
let condition = dataTab.condition;
|
||||
if (condition) {
|
||||
condition += ` AND `;
|
||||
}
|
||||
condition += `${row.columnName} = `;
|
||||
dataTab.condition = condition + wrapColumnValue(row, value);
|
||||
})
|
||||
.catch(() => {});
|
||||
state.conditionDialog.title = `请输入 [${row.columnName}] 的值`;
|
||||
state.conditionDialog.placeholder = `${row.columnType} ${row.columnComment}`;
|
||||
state.conditionDialog.columnRow = row;
|
||||
state.conditionDialog.dataTab = dataTab;
|
||||
state.conditionDialog.visible = true;
|
||||
};
|
||||
|
||||
// 确认条件
|
||||
const onConfirmCondition = () => {
|
||||
const conditionDialog = state.conditionDialog;
|
||||
const dataTab = state.conditionDialog.dataTab as any;
|
||||
let condition = dataTab.condition;
|
||||
if (condition) {
|
||||
condition += ` AND `;
|
||||
}
|
||||
const row = conditionDialog.columnRow as any;
|
||||
condition += `${row.columnName} ${conditionDialog.condition} `;
|
||||
dataTab.condition = condition + wrapColumnValue(row, conditionDialog.value);
|
||||
onCancelCondition();
|
||||
};
|
||||
|
||||
const onCancelCondition = () => {
|
||||
state.conditionDialog.visible = false;
|
||||
state.conditionDialog.title = ``;
|
||||
state.conditionDialog.placeholder = ``;
|
||||
state.conditionDialog.value = null;
|
||||
state.conditionDialog.columnRow = null;
|
||||
state.conditionDialog.dataTab = null;
|
||||
};
|
||||
|
||||
const onRefresh = async (tableName: string) => {
|
||||
@@ -793,10 +912,10 @@ export default defineComponent({
|
||||
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};`
|
||||
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} OFFSET ${(pageNum - 1) * state.defalutLimit} LIMIT ${state.defalutLimit};`;
|
||||
}
|
||||
return baseSql;
|
||||
};
|
||||
@@ -928,7 +1047,6 @@ export default defineComponent({
|
||||
state.queryTab.execRes.tableColumn = [];
|
||||
state.cmOptions.hintOptions.tables = [];
|
||||
tableMap.clear();
|
||||
closeExecBtns();
|
||||
};
|
||||
|
||||
const onDataSelectionChange = (datas: []) => {
|
||||
@@ -963,6 +1081,38 @@ export default defineComponent({
|
||||
});
|
||||
};
|
||||
|
||||
const onGenerateInsertSql = async () => {
|
||||
const queryTab = isQueryTab();
|
||||
const datas = queryTab ? state.queryTab.selectionDatas : state.dataTabs[state.activeName].selectionDatas;
|
||||
isTrue(datas && datas.length > 0, '请先选择要生成insert语句的数据');
|
||||
const tableName = state.nowTableName;
|
||||
const columns: any = await getColumns(tableName);
|
||||
|
||||
const sqls = [];
|
||||
for (let data of datas) {
|
||||
let colNames = [];
|
||||
let values = [];
|
||||
for (let column of columns) {
|
||||
const colName = column.columnName;
|
||||
colNames.push(colName);
|
||||
values.push(wrapValueByType(data[colName]));
|
||||
}
|
||||
sqls.push(`INSERT INTO ${tableName} (${colNames.join(', ')}) VALUES(${values.join(', ')})`);
|
||||
}
|
||||
state.genSqlDialog.sql = sqls.join(';\n') + ';';
|
||||
state.genSqlDialog.visible = true;
|
||||
};
|
||||
|
||||
const wrapValueByType = (val: any) => {
|
||||
if (val == null) {
|
||||
return 'NULL';
|
||||
}
|
||||
if (typeof val == 'number') {
|
||||
return val;
|
||||
}
|
||||
return `'${val}'`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 是否为查询tab
|
||||
*/
|
||||
@@ -1072,7 +1222,6 @@ export default defineComponent({
|
||||
let selectSql = codemirror.getSelection();
|
||||
isTrue(selectSql, '请选中需要格式化的sql');
|
||||
codemirror.replaceSelection(sqlFormatter(selectSql));
|
||||
closeExecBtns();
|
||||
};
|
||||
|
||||
const search = async () => {
|
||||
@@ -1080,38 +1229,15 @@ export default defineComponent({
|
||||
state.dbs = res.list;
|
||||
};
|
||||
|
||||
/**
|
||||
* 显示执行sql和格式化按钮
|
||||
*/
|
||||
const showExecBtns = (event: any) => {
|
||||
if (event.preventDefault) {
|
||||
event.preventDefault();
|
||||
} else {
|
||||
event.returnValue = false;
|
||||
}
|
||||
state.btnStyle.display = 'inline';
|
||||
state.btnStyle.left = event.offsetX + 15 + 'px';
|
||||
state.btnStyle.top = event.clientY - 80 + 'px';
|
||||
};
|
||||
|
||||
/**
|
||||
* 关闭执行sql和格式化按钮
|
||||
*/
|
||||
const closeExecBtns = () => {
|
||||
if (state.btnStyle.left) {
|
||||
state.btnStyle.display = 'none';
|
||||
state.btnStyle.left = '';
|
||||
state.btnStyle.top = '';
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
getTags,
|
||||
codeTextarea,
|
||||
changeProjectEnv,
|
||||
changeTag,
|
||||
changeTable,
|
||||
cellClick,
|
||||
onRunSql,
|
||||
exportData,
|
||||
removeDataTab,
|
||||
onDataTabClick,
|
||||
beforeUpload,
|
||||
@@ -1121,6 +1247,8 @@ export default defineComponent({
|
||||
getColumnTip,
|
||||
getColumns4Map,
|
||||
onConditionRowClick,
|
||||
onConfirmCondition,
|
||||
onCancelCondition,
|
||||
changeSqlTemplate,
|
||||
deleteSql,
|
||||
saveSql,
|
||||
@@ -1137,8 +1265,7 @@ export default defineComponent({
|
||||
onDataSelectionChange,
|
||||
onDeleteData,
|
||||
onTableSortChange,
|
||||
showExecBtns,
|
||||
closeExecBtns,
|
||||
onGenerateInsertSql,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@ export const dbApi = {
|
||||
// 获取权限列表
|
||||
dbs: Api.create("/dbs", 'get'),
|
||||
saveDb: Api.create("/dbs", 'post'),
|
||||
getAllDatabase: Api.create("/dbs/databases", 'post'),
|
||||
getDbPwd: Api.create("/dbs/{id}/pwd", 'get'),
|
||||
deleteDb: Api.create("/dbs/{id}", 'delete'),
|
||||
dumpDb: Api.create("/dbs/{id}/dump", 'post'),
|
||||
tableInfos: Api.create("/dbs/{id}/t-infos", 'get'),
|
||||
|
||||
@@ -88,27 +88,24 @@ export default defineComponent({
|
||||
|
||||
try {
|
||||
state.btnLoading = true;
|
||||
const res = await dbApi.sqlExec.request({
|
||||
await dbApi.sqlExec.request({
|
||||
id: state.dbId,
|
||||
db: state.db,
|
||||
remark: state.remark,
|
||||
sql: state.sqlValue.trim(),
|
||||
});
|
||||
if (parseInt(res.res[0].影响条数) >= 1) {
|
||||
ElMessage.success('执行成功');
|
||||
runSuccess = true;
|
||||
} else {
|
||||
ElMessage.error('执行失败');
|
||||
runSuccess = false;
|
||||
}
|
||||
ElMessage.success('执行成功');
|
||||
runSuccess = true;
|
||||
} catch (e) {
|
||||
runSuccess = false;
|
||||
}
|
||||
if (runSuccess && runSuccessCallback) {
|
||||
runSuccessCallback();
|
||||
if (runSuccess) {
|
||||
if (runSuccessCallback) {
|
||||
runSuccessCallback();
|
||||
}
|
||||
cancel();
|
||||
}
|
||||
state.btnLoading = false;
|
||||
cancel();
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
</el-row>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog :title="tree.title" v-model="tree.visible" :close-on-click-modal="false" width="680px">
|
||||
<el-dialog :title="tree.title" v-model="tree.visible" :close-on-click-modal="false" width="70%">
|
||||
<el-progress
|
||||
v-if="uploadProgressShow"
|
||||
style="width: 90%; margin-left: 20px"
|
||||
@@ -66,7 +66,16 @@
|
||||
:percentage="progressNum"
|
||||
/>
|
||||
<div style="height: 45vh; overflow: auto">
|
||||
<el-tree v-if="tree.visible" ref="fileTree" :load="loadNode" :props="props" lazy node-key="id" :expand-on-click-node="true">
|
||||
<el-tree
|
||||
v-if="tree.visible"
|
||||
ref="fileTree"
|
||||
:highlight-current="true"
|
||||
:load="loadNode"
|
||||
:props="props"
|
||||
lazy
|
||||
node-key="id"
|
||||
:expand-on-click-node="true"
|
||||
>
|
||||
<template #default="{ node, data }">
|
||||
<span class="custom-tree-node">
|
||||
<el-dropdown size="small" @visible-change="getFilePath(data, $event)" trigger="contextmenu">
|
||||
@@ -81,9 +90,8 @@
|
||||
<SvgIcon name="document" />
|
||||
</span>
|
||||
|
||||
<span style="display: inline-block">
|
||||
<span>
|
||||
{{ node.label }}
|
||||
<span style="color: #67c23a" v-if="data.type == '-'"> [{{ formatFileSize(data.size) }}]</span>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
@@ -133,6 +141,10 @@
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<span style="display: inline-block" class="ml15">
|
||||
<span style="color: #67c23a" v-if="data.type == '-'">[{{ formatFileSize(data.size) }}]</span>
|
||||
<span v-if="data.mode" style="color: #67c23a"> [{{ data.mode }} {{ data.modTime }}]</span>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
@@ -161,7 +173,7 @@
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<div>
|
||||
<el-button @click="closeCreateFileDialog">关闭</el-button>
|
||||
<el-button v-auth="'machine:file:write'" type="primary" @click="createFile">确定</el-button>
|
||||
</div>
|
||||
@@ -277,9 +289,9 @@ export default defineComponent({
|
||||
file: null as any,
|
||||
});
|
||||
|
||||
watch(props, (newValue) => {
|
||||
if (newValue.machineId) {
|
||||
getFiles();
|
||||
watch(props, async (newValue) => {
|
||||
if (newValue.machineId && newValue.visible) {
|
||||
await getFiles();
|
||||
}
|
||||
state.dialogVisible = newValue.visible;
|
||||
});
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :close-on-click-modal="false" :destroy-on-close="true" :before-close="cancel" width="35%">
|
||||
<el-dialog :title="title" v-model="dialogVisible" :close-on-click-modal="false" :destroy-on-close="true" :before-close="cancel" width="38%">
|
||||
<el-form :model="form" ref="machineForm" :rules="rules" label-width="85px">
|
||||
<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>
|
||||
</el-select>
|
||||
<el-form-item prop="tagId" label="标签:" required>
|
||||
<tag-select v-model:tag-id="form.tagId" v-model:tag-path="form.tagPath" style="width: 100%" />
|
||||
</el-form-item>
|
||||
<el-form-item prop="name" label="名称:" required>
|
||||
<el-input v-model.trim="form.name" placeholder="请输入机器别名" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="ip" label="ip:" required>
|
||||
<el-col :span="18">
|
||||
<el-input v-model.trim="form.ip" placeholder="主机ip" auto-complete="off"></el-input>
|
||||
<el-input :disabled="form.id != 0" v-model.trim="form.ip" placeholder="主机ip" auto-complete="off"></el-input>
|
||||
</el-col>
|
||||
<el-col style="text-align: center" :span="1">:</el-col>
|
||||
<el-col :span="5">
|
||||
@@ -35,7 +33,15 @@
|
||||
v-model.trim="form.password"
|
||||
placeholder="请输入密码,修改操作可不填"
|
||||
autocomplete="new-password"
|
||||
></el-input>
|
||||
>
|
||||
<template v-if="form.id && form.id != 0" #suffix>
|
||||
<el-popover @hide="pwd = ''" placement="right" title="原密码" :width="200" trigger="click" :content="pwd">
|
||||
<template #reference>
|
||||
<el-link @click="getPwd" :underline="false" type="primary" class="mr5">原密码</el-link>
|
||||
</template>
|
||||
</el-popover>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="form.authMethod == 2" prop="password" label="秘钥:">
|
||||
<el-input type="textarea" :rows="3" v-model="form.password" placeholder="请将私钥文件内容拷贝至此,修改操作可不填"></el-input>
|
||||
@@ -43,6 +49,28 @@
|
||||
<el-form-item prop="remark" label="备注:">
|
||||
<el-input type="textarea" v-model="form.remark"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="enableRecorder" label="终端回放:">
|
||||
<el-checkbox v-model="form.enableRecorder" :true-label="1" :false-label="-1"></el-checkbox>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="enableSshTunnel" label="SSH隧道:">
|
||||
<el-col :span="3">
|
||||
<el-checkbox @change="getSshTunnelMachines" v-model="form.enableSshTunnel" :true-label="1" :false-label="-1"></el-checkbox>
|
||||
</el-col>
|
||||
<el-col :span="2" v-if="form.enableSshTunnel == 1"> 机器: </el-col>
|
||||
<el-col :span="19" v-if="form.enableSshTunnel == 1">
|
||||
<el-select style="width: 100%" v-model="form.sshTunnelMachineId" placeholder="请选择SSH隧道机器">
|
||||
<el-option
|
||||
v-for="item in sshTunnelMachineList"
|
||||
:key="item.id"
|
||||
:label="`${item.ip}:${item.port} [${item.name}]`"
|
||||
:value="item.id"
|
||||
>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-col>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<template #footer>
|
||||
@@ -61,9 +89,13 @@ import { machineApi } from './api';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { notBlank } from '@/common/assert';
|
||||
import { RsaEncrypt } from '@/common/rsa';
|
||||
import TagSelect from '../component/TagSelect.vue';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'MachineEdit',
|
||||
components: {
|
||||
TagSelect,
|
||||
},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
@@ -82,31 +114,32 @@ export default defineComponent({
|
||||
const machineForm: any = ref(null);
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
projects: [],
|
||||
projects: [] as any,
|
||||
sshTunnelMachineList: [] as any,
|
||||
tags: [],
|
||||
selectTags: [],
|
||||
form: {
|
||||
id: null,
|
||||
projectId: null,
|
||||
projectName: null,
|
||||
tagId: null as any,
|
||||
tagPath: '',
|
||||
ip: null,
|
||||
name: null,
|
||||
authMethod: 1,
|
||||
port: 22,
|
||||
username: '',
|
||||
password: '',
|
||||
remark: '',
|
||||
enableSshTunnel: null,
|
||||
sshTunnelMachineId: null,
|
||||
enableRecorder: -1,
|
||||
},
|
||||
pwd: '',
|
||||
btnLoading: false,
|
||||
rules: {
|
||||
projectId: [
|
||||
tagId: [
|
||||
{
|
||||
required: true,
|
||||
message: '请选择项目',
|
||||
trigger: ['change', 'blur'],
|
||||
},
|
||||
],
|
||||
envId: [
|
||||
{
|
||||
required: true,
|
||||
message: '请选择环境',
|
||||
message: '请选择标签',
|
||||
trigger: ['change', 'blur'],
|
||||
},
|
||||
],
|
||||
@@ -152,23 +185,40 @@ export default defineComponent({
|
||||
} else {
|
||||
state.form = { port: 22, authMethod: 1 } as any;
|
||||
}
|
||||
getSshTunnelMachines();
|
||||
});
|
||||
|
||||
const changeProject = (projectId: number) => {
|
||||
for (let p of state.projects as any) {
|
||||
if (p.id == projectId) {
|
||||
state.form.projectName = p.name;
|
||||
}
|
||||
const getSshTunnelMachines = async () => {
|
||||
if (state.form.enableSshTunnel == 1 && state.sshTunnelMachineList.length == 0) {
|
||||
const res = await machineApi.list.request({ pageNum: 1, pageSize: 100 });
|
||||
state.sshTunnelMachineList = res.list;
|
||||
}
|
||||
};
|
||||
|
||||
const getSshTunnelMachine = (machineId: any) => {
|
||||
notBlank(machineId, '请选择或先创建一台隧道机器');
|
||||
return state.sshTunnelMachineList.find((x: any) => x.id == machineId);
|
||||
};
|
||||
|
||||
const getPwd = async () => {
|
||||
state.pwd = await machineApi.getMachinePwd.request({ id: state.form.id });
|
||||
};
|
||||
|
||||
const btnOk = async () => {
|
||||
if (!state.form.id) {
|
||||
notBlank(state.form.password, '新增操作,密码不可为空');
|
||||
}
|
||||
machineForm.value.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
const reqForm = { ...state.form };
|
||||
const form: any = state.form;
|
||||
if (form.enableSshTunnel == 1) {
|
||||
const tunnelMachine: any = getSshTunnelMachine(form.sshTunnelMachineId);
|
||||
if (tunnelMachine.ip == form.ip && tunnelMachine.port == form.port) {
|
||||
ElMessage.error('隧道机器不能与本机器一致');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const reqForm: any = { ...form };
|
||||
if (reqForm.authMethod == 1) {
|
||||
reqForm.password = await RsaEncrypt(state.form.password);
|
||||
}
|
||||
@@ -196,7 +246,8 @@ export default defineComponent({
|
||||
return {
|
||||
...toRefs(state),
|
||||
machineForm,
|
||||
changeProject,
|
||||
getSshTunnelMachines,
|
||||
getPwd,
|
||||
btnOk,
|
||||
cancel,
|
||||
};
|
||||
|
||||
@@ -3,21 +3,15 @@
|
||||
<el-card>
|
||||
<div>
|
||||
<el-button v-auth="'machine:add'" type="primary" icon="plus" @click="openFormDialog(false)" plain>添加</el-button>
|
||||
<el-button
|
||||
v-auth="'machine:update'"
|
||||
type="primary"
|
||||
icon="edit"
|
||||
:disabled="currentId == null"
|
||||
@click="openFormDialog(currentData)"
|
||||
plain
|
||||
<el-button v-auth="'machine:update'" type="primary" icon="edit" :disabled="!currentId" @click="openFormDialog(currentData)" plain
|
||||
>编辑</el-button
|
||||
>
|
||||
<el-button v-auth="'machine:del'" :disabled="currentId == null" @click="deleteMachine(currentId)" type="danger" icon="delete"
|
||||
<el-button v-auth="'machine:del'" :disabled="!currentId" @click="deleteMachine(currentId)" type="danger" icon="delete"
|
||||
>删除</el-button
|
||||
>
|
||||
<div style="float: right">
|
||||
<el-select v-model="params.projectId" placeholder="请选择项目" @clear="search" filterable clearable>
|
||||
<el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
|
||||
<el-select @focus="getTags" v-model="params.tagPath" placeholder="请选择标签" @clear="search" filterable clearable>
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-input
|
||||
class="ml5"
|
||||
@@ -42,7 +36,7 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="name" label="名称" min-width="140" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="ip" label="ip:port" min-width="140">
|
||||
<el-table-column prop="ip" label="ip:port" min-width="150">
|
||||
<template #default="scope">
|
||||
<el-link :disabled="scope.row.status == -1" @click="showMachineStats(scope.row)" type="primary" :underline="false">{{
|
||||
`${scope.row.ip}:${scope.row.port}`
|
||||
@@ -66,43 +60,42 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="username" label="用户名" min-width="90"></el-table-column>
|
||||
<el-table-column prop="projectName" label="项目" min-width="120"></el-table-column>
|
||||
<el-table-column prop="tagPath" label="标签路径" min-width="150" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="250" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="ip" label="hasCli" width="70">
|
||||
<template #default="scope">
|
||||
{{ `${scope.row.hasCli ? '是' : '否'}` }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createTime" label="创建时间" min-width="165">
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
{{ dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="creator" label="创建者" min-width="80"></el-table-column>
|
||||
<el-table-column label="操作" min-width="280" fixed="right">
|
||||
<el-table-column label="操作" min-width="235" fixed="right">
|
||||
<template #default="scope">
|
||||
<el-link
|
||||
v-auth="'machine:terminal'"
|
||||
:disabled="scope.row.status == -1"
|
||||
type="primary"
|
||||
@click="showTerminal(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>终端</el-link
|
||||
>
|
||||
<el-divider v-auth="'machine:terminal'" direction="vertical" border-style="dashed" />
|
||||
<el-link
|
||||
v-auth="'machine:file'"
|
||||
type="success"
|
||||
:disabled="scope.row.status == -1"
|
||||
@click="fileManage(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>文件</el-link
|
||||
>
|
||||
<el-divider v-auth="'machine:file'" direction="vertical" border-style="dashed" />
|
||||
<span v-auth="'machine:terminal'">
|
||||
<el-link
|
||||
:disabled="scope.row.status == -1"
|
||||
type="primary"
|
||||
@click="showTerminal(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>终端</el-link
|
||||
>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
</span>
|
||||
|
||||
<span v-auth="'machine:file'">
|
||||
<el-link
|
||||
type="success"
|
||||
:disabled="scope.row.status == -1"
|
||||
@click="fileManage(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>文件</el-link
|
||||
>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
</span>
|
||||
|
||||
<el-link
|
||||
:disabled="scope.row.status == -1"
|
||||
type="warning"
|
||||
@@ -113,19 +106,47 @@
|
||||
>脚本</el-link
|
||||
>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
<el-link @click="showProcess(scope.row)" :disabled="scope.row.status == -1" plain :underline="false" size="small"
|
||||
>进程</el-link
|
||||
>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
<el-link
|
||||
:disabled="!scope.row.hasCli || scope.row.status == -1"
|
||||
type="danger"
|
||||
@click="closeCli(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>关闭连接</el-link
|
||||
>
|
||||
|
||||
<el-dropdown>
|
||||
<span class="el-dropdown-link-machine-list">
|
||||
更多
|
||||
<el-icon class="el-icon--right">
|
||||
<arrow-down />
|
||||
</el-icon>
|
||||
</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
><el-link
|
||||
@click="showProcess(scope.row)"
|
||||
:disabled="scope.row.status == -1"
|
||||
plain
|
||||
:underline="false"
|
||||
size="small"
|
||||
>进程</el-link
|
||||
></el-dropdown-item
|
||||
>
|
||||
|
||||
<el-dropdown-item v-if="scope.row.enableRecorder == 1"
|
||||
><el-link v-auth="'machine:update'" @click="showRec(scope.row)" plain :underline="false" size="small"
|
||||
>终端回放</el-link
|
||||
></el-dropdown-item
|
||||
>
|
||||
|
||||
<el-dropdown-item
|
||||
><el-link
|
||||
:disabled="!scope.row.hasCli || scope.row.status == -1"
|
||||
type="danger"
|
||||
@click="closeCli(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>关闭连接</el-link
|
||||
></el-dropdown-item
|
||||
>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
@@ -143,7 +164,6 @@
|
||||
|
||||
<machine-edit
|
||||
:title="machineEditDialog.title"
|
||||
:projects="projects"
|
||||
v-model:visible="machineEditDialog.visible"
|
||||
v-model:machine="machineEditDialog.data"
|
||||
@valChange="submitSuccess"
|
||||
@@ -160,6 +180,8 @@
|
||||
:machineId="machineStatsDialog.machineId"
|
||||
:title="machineStatsDialog.title"
|
||||
></machine-stats>
|
||||
|
||||
<machine-rec v-model:visible="machineRecDialog.visible" :machineId="machineRecDialog.machineId" :title="machineRecDialog.title"></machine-rec>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -168,12 +190,14 @@ import { toRefs, reactive, onMounted, defineComponent } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { machineApi } from './api';
|
||||
import { projectApi } from '../project/api.ts';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
import ServiceManage from './ServiceManage.vue';
|
||||
import FileManage from './FileManage.vue';
|
||||
import MachineEdit from './MachineEdit.vue';
|
||||
import ProcessList from './ProcessList.vue';
|
||||
import MachineStats from './MachineStats.vue';
|
||||
import MachineRec from './MachineRec.vue';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'MachineList',
|
||||
@@ -183,17 +207,19 @@ export default defineComponent({
|
||||
FileManage,
|
||||
MachineEdit,
|
||||
MachineStats,
|
||||
MachineRec,
|
||||
},
|
||||
setup() {
|
||||
const router = useRouter();
|
||||
const state = reactive({
|
||||
projects: [],
|
||||
tags: [] as any,
|
||||
stats: '',
|
||||
params: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
ip: null,
|
||||
name: null,
|
||||
tagPath: null,
|
||||
},
|
||||
// 列表数据
|
||||
data: {
|
||||
@@ -201,7 +227,7 @@ export default defineComponent({
|
||||
total: 10,
|
||||
},
|
||||
// 当前选中数据id
|
||||
currentId: null,
|
||||
currentId: 0,
|
||||
currentData: null,
|
||||
serviceDialog: {
|
||||
visible: false,
|
||||
@@ -225,14 +251,18 @@ export default defineComponent({
|
||||
},
|
||||
machineEditDialog: {
|
||||
visible: false,
|
||||
data: null,
|
||||
data: null as any,
|
||||
title: '新增机器',
|
||||
},
|
||||
machineRecDialog: {
|
||||
visible: false,
|
||||
machineId: 0,
|
||||
title: '',
|
||||
},
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
search();
|
||||
state.projects = await projectApi.accountProjects.request(null);
|
||||
});
|
||||
|
||||
const choose = (item: any) => {
|
||||
@@ -255,12 +285,21 @@ export default defineComponent({
|
||||
};
|
||||
|
||||
const closeCli = async (row: any) => {
|
||||
await ElMessageBox.confirm(`确定关闭该机器客户端连接?`, '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
});
|
||||
await machineApi.closeCli.request({ id: row.id });
|
||||
ElMessage.success('关闭成功');
|
||||
search();
|
||||
};
|
||||
|
||||
const openFormDialog = (machine: any) => {
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const openFormDialog = async (machine: any) => {
|
||||
let dialogTitle;
|
||||
if (machine) {
|
||||
state.machineEditDialog.data = state.currentData as any;
|
||||
@@ -283,7 +322,7 @@ export default defineComponent({
|
||||
});
|
||||
await machineApi.del.request({ id });
|
||||
ElMessage.success('操作成功');
|
||||
state.currentId = null;
|
||||
state.currentId = 0;
|
||||
state.currentData = null;
|
||||
search();
|
||||
} catch (err) {}
|
||||
@@ -312,7 +351,7 @@ export default defineComponent({
|
||||
};
|
||||
|
||||
const submitSuccess = () => {
|
||||
state.currentId = null;
|
||||
state.currentId = 0;
|
||||
state.currentData = null;
|
||||
search();
|
||||
};
|
||||
@@ -338,9 +377,17 @@ export default defineComponent({
|
||||
state.processDialog.visible = true;
|
||||
};
|
||||
|
||||
const showRec = (row: any) => {
|
||||
state.machineRecDialog.title = `${row.name}[${row.ip}]-终端回放记录`;
|
||||
state.machineRecDialog.machineId = row.id;
|
||||
state.machineRecDialog.visible = true;
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
dateFormat,
|
||||
choose,
|
||||
getTags,
|
||||
showTerminal,
|
||||
openFormDialog,
|
||||
deleteMachine,
|
||||
@@ -352,6 +399,7 @@ export default defineComponent({
|
||||
submitSuccess,
|
||||
fileManage,
|
||||
search,
|
||||
showRec,
|
||||
handlePageChange,
|
||||
};
|
||||
},
|
||||
@@ -362,4 +410,11 @@ export default defineComponent({
|
||||
.el-dialog__body {
|
||||
padding: 2px 2px;
|
||||
}
|
||||
.el-dropdown-link-machine-list {
|
||||
cursor: pointer;
|
||||
color: var(--el-color-primary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 6px;
|
||||
}
|
||||
</style>
|
||||
|
||||
137
mayfly_go_web/src/views/ops/machine/MachineRec.vue
Normal file
137
mayfly_go_web/src/views/ops/machine/MachineRec.vue
Normal file
@@ -0,0 +1,137 @@
|
||||
<template>
|
||||
<div id="terminalRecDialog">
|
||||
<el-dialog
|
||||
:title="title"
|
||||
v-model="dialogVisible"
|
||||
:before-close="handleClose"
|
||||
:close-on-click-modal="false"
|
||||
:destroy-on-close="true"
|
||||
width="70%"
|
||||
>
|
||||
<div class="toolbar">
|
||||
<el-select @change="getUsers" v-model="operateDate" placeholder="操作日期" filterable>
|
||||
<el-option v-for="item in operateDates" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-select class="ml10" @change="getRecs" filterable v-model="user" placeholder="请选择操作人">
|
||||
<el-option v-for="item in users" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-select class="ml10" @change="playRec" filterable v-model="rec" placeholder="请选择操作记录">
|
||||
<el-option v-for="item in recs" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
快捷键-> space[空格键]: 暂停/播放
|
||||
</div>
|
||||
<div ref="playerRef" id="rc-player"></div>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, watch, ref, reactive, defineComponent } from 'vue';
|
||||
import { machineApi } from './api';
|
||||
import * as AsciinemaPlayer from 'asciinema-player';
|
||||
import 'asciinema-player/dist/bundle/asciinema-player.css';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'MachineRec',
|
||||
components: {},
|
||||
props: {
|
||||
visible: { type: Boolean },
|
||||
machineId: { type: Number },
|
||||
title: { type: String },
|
||||
},
|
||||
setup(props: any, context) {
|
||||
const playerRef = ref(null);
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
title: '',
|
||||
machineId: 0,
|
||||
operateDates: [],
|
||||
users: [],
|
||||
recs: [],
|
||||
operateDate: '',
|
||||
user: '',
|
||||
rec: '',
|
||||
});
|
||||
|
||||
watch(props, async (newValue) => {
|
||||
const visible = newValue.visible;
|
||||
if (visible) {
|
||||
state.machineId = newValue.machineId;
|
||||
state.title = newValue.title;
|
||||
await getOperateDate();
|
||||
}
|
||||
state.dialogVisible = visible;
|
||||
});
|
||||
|
||||
const getOperateDate = async () => {
|
||||
const res = await machineApi.recDirNames.request({ path: state.machineId });
|
||||
state.operateDates = res as any;
|
||||
};
|
||||
|
||||
const getUsers = async (operateDate: string) => {
|
||||
state.users = [];
|
||||
state.user = '';
|
||||
state.recs = [];
|
||||
state.rec = '';
|
||||
const res = await machineApi.recDirNames.request({ path: `${state.machineId}/${operateDate}` });
|
||||
state.users = res as any;
|
||||
};
|
||||
|
||||
const getRecs = async (user: string) => {
|
||||
state.recs = [];
|
||||
state.rec = '';
|
||||
const res = await machineApi.recDirNames.request({ path: `${state.machineId}/${state.operateDate}/${user}` });
|
||||
state.recs = res as any;
|
||||
};
|
||||
|
||||
let player: any = null;
|
||||
|
||||
const playRec = async (rec: string) => {
|
||||
if (player) {
|
||||
player.dispose();
|
||||
}
|
||||
const content = await machineApi.recDirNames.request({
|
||||
isFile: '1',
|
||||
path: `${state.machineId}/${state.operateDate}/${state.user}/${rec}`,
|
||||
});
|
||||
player = AsciinemaPlayer.create(`data:text/plain;base64,${content}`, playerRef.value, {
|
||||
autoPlay: true,
|
||||
speed: 1.0,
|
||||
idleTimeLimit: 2,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 关闭取消按钮触发的事件
|
||||
*/
|
||||
const handleClose = () => {
|
||||
context.emit('update:visible', false);
|
||||
context.emit('update:machineId', null);
|
||||
context.emit('cancel');
|
||||
state.operateDates = [];
|
||||
state.users = [];
|
||||
state.recs = [];
|
||||
state.operateDate = '';
|
||||
state.user = '';
|
||||
state.rec = '';
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
playerRef,
|
||||
getUsers,
|
||||
getRecs,
|
||||
playRec,
|
||||
handleClose,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
#terminalRecDialog {
|
||||
.el-overlay .el-overlay-dialog .el-dialog .el-dialog__body {
|
||||
padding: 0px !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -7,9 +7,9 @@
|
||||
:before-close="cancel"
|
||||
:show-close="true"
|
||||
:destroy-on-close="true"
|
||||
width="800px"
|
||||
width="900px"
|
||||
>
|
||||
<el-form :model="form" ref="mockDataForm" label-width="70px">
|
||||
<el-form :model="form" ref="scriptForm" label-width="50px" size="small">
|
||||
<el-form-item prop="method" label="名称">
|
||||
<el-input v-model.trim="form.name" placeholder="请输入名称"></el-input>
|
||||
</el-form-item>
|
||||
@@ -24,8 +24,23 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="params" label="参数">
|
||||
<el-input v-model="form.params" placeholder="参数数组json,若无可不填"></el-input>
|
||||
<el-row style="margin-left: 30px; margin-bottom: 5px">
|
||||
<el-button @click="onAddParam" size="small" type="success">新增占位符参数</el-button>
|
||||
</el-row>
|
||||
<el-form-item :key="param" v-for="(param, index) in params" prop="params" :label="`参数${index + 1}`">
|
||||
<el-row>
|
||||
<el-col :span="5"><el-input v-model="param.model" placeholder="内容中用{{.model}}替换"></el-input></el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="4"><el-input v-model="param.name" placeholder="字段名"></el-input></el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="4"><el-input v-model="param.placeholder" placeholder="字段说明"></el-input></el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="4">
|
||||
<el-input v-model="param.options" placeholder="可选值 ,分割"></el-input>
|
||||
</el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="2"><el-button @click="onDeleteParam(index)" size="small" type="danger">删除</el-button></el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="script" label="内容" id="content">
|
||||
@@ -35,13 +50,12 @@
|
||||
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()" :disabled="submitDisabled" size="small">关 闭</el-button>
|
||||
<el-button @click="cancel()" :disabled="submitDisabled">关 闭</el-button>
|
||||
<el-button
|
||||
v-auth="'machine:script:save'"
|
||||
type="primary"
|
||||
:loading="btnLoading"
|
||||
@click="btnOk"
|
||||
size="small"
|
||||
:disabled="submitDisabled"
|
||||
>保 存</el-button
|
||||
>
|
||||
@@ -84,41 +98,59 @@ export default defineComponent({
|
||||
},
|
||||
setup(props: any, { emit }) {
|
||||
const { isCommon, machineId } = toRefs(props);
|
||||
const mockDataForm: any = ref(null);
|
||||
const scriptForm: any = ref(null);
|
||||
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
submitDisabled: false,
|
||||
params: [] as any,
|
||||
form: {
|
||||
id: null,
|
||||
name: '',
|
||||
machineId: 0,
|
||||
description: '',
|
||||
script: '',
|
||||
params: null,
|
||||
params: '',
|
||||
type: null,
|
||||
},
|
||||
btnLoading: false,
|
||||
});
|
||||
|
||||
watch(props, (newValue) => {
|
||||
state.dialogVisible = newValue.visible;
|
||||
if (!newValue.visible) {
|
||||
return;
|
||||
}
|
||||
if (newValue.data) {
|
||||
state.form = { ...newValue.data };
|
||||
if (state.form.params) {
|
||||
state.params = JSON.parse(state.form.params);
|
||||
}
|
||||
} else {
|
||||
state.form = {} as any;
|
||||
state.form.script = '';
|
||||
}
|
||||
state.dialogVisible = newValue.visible;
|
||||
});
|
||||
|
||||
const onAddParam = () => {
|
||||
state.params.push({ name: '', model: '', placeholder: '' });
|
||||
};
|
||||
|
||||
const onDeleteParam = (idx: number) => {
|
||||
state.params.splice(idx, 1);
|
||||
};
|
||||
|
||||
const btnOk = () => {
|
||||
state.form.machineId = isCommon.value ? 9999999 : (machineId.value as any);
|
||||
console.log('machineid:', machineId);
|
||||
mockDataForm.value.validate((valid: any) => {
|
||||
scriptForm.value.validate((valid: any) => {
|
||||
if (valid) {
|
||||
notEmpty(state.form.name, '名称不能为空');
|
||||
notEmpty(state.form.description, '描述不能为空');
|
||||
notEmpty(state.form.script, '内容不能为空');
|
||||
if (state.params) {
|
||||
state.form.params = JSON.stringify(state.params);
|
||||
}
|
||||
machineApi.saveScript.request(state.form).then(
|
||||
() => {
|
||||
ElMessage.success('保存成功');
|
||||
@@ -139,12 +171,15 @@ export default defineComponent({
|
||||
const cancel = () => {
|
||||
emit('update:visible', false);
|
||||
emit('cancel');
|
||||
state.params = [];
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
enums,
|
||||
mockDataForm,
|
||||
onAddParam,
|
||||
onDeleteParam,
|
||||
scriptForm,
|
||||
btnOk,
|
||||
cancel,
|
||||
};
|
||||
@@ -152,11 +187,6 @@ export default defineComponent({
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
// .m-dialog {
|
||||
// .el-cascader {
|
||||
// width: 100%;
|
||||
// }
|
||||
// }
|
||||
#content {
|
||||
.CodeMirror {
|
||||
height: 300px !important;
|
||||
|
||||
@@ -76,7 +76,24 @@
|
||||
<el-dialog title="脚本参数" v-model="scriptParamsDialog.visible" width="400px">
|
||||
<el-form ref="paramsForm" :model="scriptParamsDialog.params" label-width="70px" size="small">
|
||||
<el-form-item v-for="item in scriptParamsDialog.paramsFormItem" :key="item.name" :prop="item.model" :label="item.name" required>
|
||||
<el-input v-model="scriptParamsDialog.params[item.model]" :placeholder="item.placeholder" autocomplete="off"></el-input>
|
||||
<el-input
|
||||
v-if="!item.options"
|
||||
v-model="scriptParamsDialog.params[item.model]"
|
||||
:placeholder="item.placeholder"
|
||||
autocomplete="off"
|
||||
clearable
|
||||
></el-input>
|
||||
<el-select
|
||||
v-else
|
||||
v-model="scriptParamsDialog.params[item.model]"
|
||||
:placeholder="item.placeholder"
|
||||
filterable
|
||||
autocomplete="off"
|
||||
clearable
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option v-for="option in item.options.split(',')" :key="option" :label="option" :value="option" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
@@ -88,7 +105,6 @@
|
||||
|
||||
<el-dialog title="执行结果" v-model="resultDialog.visible" width="50%">
|
||||
<div style="white-space: pre-line; padding: 10px; color: #000000">
|
||||
<!-- {{ resultDialog.result }} -->
|
||||
<el-input v-model="resultDialog.result" :rows="20" type="textarea" />
|
||||
</div>
|
||||
</el-dialog>
|
||||
@@ -97,12 +113,12 @@
|
||||
v-if="terminalDialog.visible"
|
||||
title="终端"
|
||||
v-model="terminalDialog.visible"
|
||||
width="70%"
|
||||
width="80%"
|
||||
:close-on-click-modal="false"
|
||||
:modal="false"
|
||||
@close="closeTermnial"
|
||||
>
|
||||
<ssh-terminal ref="terminal" :cmd="terminalDialog.cmd" :machineId="terminalDialog.machineId" height="600px" />
|
||||
<ssh-terminal ref="terminal" :cmd="terminalDialog.cmd" :machineId="terminalDialog.machineId" height="560px" />
|
||||
</el-dialog>
|
||||
|
||||
<script-edit
|
||||
@@ -171,9 +187,9 @@ export default defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
watch(props, (newValue) => {
|
||||
if (props.machineId) {
|
||||
getScripts();
|
||||
watch(props, async (newValue) => {
|
||||
if (props.machineId && newValue.visible) {
|
||||
await getScripts();
|
||||
}
|
||||
state.dialogVisible = newValue.visible;
|
||||
});
|
||||
@@ -196,8 +212,10 @@ export default defineComponent({
|
||||
// 如果存在参数,则弹窗输入参数后执行
|
||||
if (script.params) {
|
||||
state.scriptParamsDialog.paramsFormItem = JSON.parse(script.params);
|
||||
state.scriptParamsDialog.visible = true;
|
||||
return;
|
||||
if (state.scriptParamsDialog.paramsFormItem && state.scriptParamsDialog.paramsFormItem.length > 0) {
|
||||
state.scriptParamsDialog.visible = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
run(script);
|
||||
@@ -268,8 +286,6 @@ export default defineComponent({
|
||||
const closeTermnial = () => {
|
||||
state.terminalDialog.visible = false;
|
||||
state.terminalDialog.machineId = 0;
|
||||
// const t: any = this.$refs['terminal']
|
||||
// t.closeAll()
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -295,8 +311,6 @@ export default defineComponent({
|
||||
};
|
||||
|
||||
const submitSuccess = () => {
|
||||
// this.delChoose()
|
||||
// this.search()
|
||||
getScripts();
|
||||
};
|
||||
|
||||
@@ -326,6 +340,7 @@ export default defineComponent({
|
||||
context.emit('update:machineId', null);
|
||||
context.emit('cancel');
|
||||
state.scriptTable = [];
|
||||
state.scriptParamsDialog.paramsFormItem = [];
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { FitAddon } from 'xterm-addon-fit';
|
||||
import { getSession } from '@/common/utils/storage.ts';
|
||||
import config from '@/common/config';
|
||||
import { useStore } from '@/store/index.ts';
|
||||
import { toRefs, watch, computed, reactive, defineComponent, onMounted, onBeforeUnmount } from 'vue';
|
||||
import { nextTick, toRefs, watch, computed, reactive, defineComponent, onMounted, onBeforeUnmount } from 'vue';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'SshTerminal',
|
||||
@@ -27,22 +27,20 @@ export default defineComponent({
|
||||
socket: null as any,
|
||||
});
|
||||
|
||||
const resize = 1;
|
||||
const data = 2;
|
||||
const ping = 3;
|
||||
|
||||
watch(props, (newValue) => {
|
||||
state.machineId = newValue.machineId;
|
||||
state.cmd = newValue.cmd;
|
||||
state.height = newValue.height;
|
||||
if (state.machineId) {
|
||||
initSocket();
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
state.machineId = props.machineId;
|
||||
state.height = props.height;
|
||||
state.cmd = props.cmd;
|
||||
if (state.machineId) {
|
||||
initSocket();
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -56,18 +54,23 @@ export default defineComponent({
|
||||
return store.state.themeConfig.themeConfig;
|
||||
});
|
||||
|
||||
nextTick(() => {
|
||||
initXterm();
|
||||
initSocket();
|
||||
});
|
||||
|
||||
function initXterm() {
|
||||
const term: any = new Terminal({
|
||||
fontSize: getThemeConfig.value.terminalFontSize || 15,
|
||||
// fontWeight: getThemeConfig.value.terminalFontWeight || 'normal',
|
||||
fontFamily: 'JetBrainsMono, Consolas, Menlo, Monaco',
|
||||
fontWeight: getThemeConfig.value.terminalFontWeight || 'normal',
|
||||
fontFamily: 'JetBrainsMono, monaco, Consolas, Lucida Console, monospace',
|
||||
cursorBlink: true,
|
||||
// cursorStyle: 'underline', //光标样式
|
||||
disableStdin: false,
|
||||
theme: {
|
||||
foreground: getThemeConfig.value.terminalForeground || '#7e9192', //字体
|
||||
background: getThemeConfig.value.terminalBackground || '#002833', //背景色
|
||||
cursor: getThemeConfig.value.terminalCursor || '#268F81', //设置光标
|
||||
// cursorAccent: "red", // 光标停止颜色
|
||||
} as any,
|
||||
});
|
||||
const fitAddon = new FitAddon();
|
||||
@@ -82,6 +85,14 @@ export default defineComponent({
|
||||
try {
|
||||
// 窗口大小改变时,触发xterm的resize方法使自适应
|
||||
fitAddon.fit();
|
||||
if (state.term) {
|
||||
state.term.focus();
|
||||
send({
|
||||
type: resize,
|
||||
Cols: parseInt(state.term.cols),
|
||||
Rows: parseInt(state.term.rows),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
@@ -104,69 +115,52 @@ export default defineComponent({
|
||||
term.onData((key: any) => {
|
||||
sendCmd(key);
|
||||
});
|
||||
// 为解决窗体resize方法才会向后端发送列数和行数,所以页面加载时也要触发此方法
|
||||
send({
|
||||
type: 'resize',
|
||||
Cols: parseInt(term.cols),
|
||||
Rows: parseInt(term.rows),
|
||||
});
|
||||
// 如果有初始要执行的命令,则发送执行命令
|
||||
if (state.cmd) {
|
||||
sendCmd(state.cmd + ' \r');
|
||||
}
|
||||
}
|
||||
|
||||
let pingInterval: any;
|
||||
function initSocket() {
|
||||
state.socket = new WebSocket(`${config.baseWsUrl}/machines/${state.machineId}/terminal?token=${getSession('token')}`);
|
||||
state.socket = new WebSocket(
|
||||
`${config.baseWsUrl}/machines/${state.machineId}/terminal?token=${getSession('token')}&cols=${state.term.cols}&rows=${
|
||||
state.term.rows
|
||||
}`
|
||||
);
|
||||
|
||||
// 监听socket连接
|
||||
state.socket.onopen = open;
|
||||
state.socket.onopen = () => {
|
||||
// 如果有初始要执行的命令,则发送执行命令
|
||||
if (state.cmd) {
|
||||
sendCmd(state.cmd + ' \r');
|
||||
}
|
||||
// 开启心跳
|
||||
pingInterval = setInterval(() => {
|
||||
send({ type: ping, msg: 'ping' });
|
||||
}, 8000);
|
||||
};
|
||||
|
||||
// 监听socket错误信息
|
||||
state.socket.onerror = error;
|
||||
// 监听socket消息
|
||||
state.socket.onmessage = getMessage;
|
||||
state.socket.onerror = (e: any) => {
|
||||
console.log('连接错误', e);
|
||||
};
|
||||
|
||||
state.socket.onclose = () => {
|
||||
if (state.term) {
|
||||
state.term.writeln('\r\n\x1b[31m提示: 连接已关闭...');
|
||||
}
|
||||
if (pingInterval) {
|
||||
clearInterval(pingInterval);
|
||||
}
|
||||
};
|
||||
|
||||
// 发送socket消息
|
||||
state.socket.onsend = send;
|
||||
|
||||
// 监听socket消息
|
||||
state.socket.onmessage = getMessage;
|
||||
}
|
||||
|
||||
function open() {
|
||||
console.log('socket连接成功');
|
||||
initXterm();
|
||||
//开启心跳
|
||||
// this.start();
|
||||
}
|
||||
|
||||
function error() {
|
||||
console.log('连接错误');
|
||||
//重连
|
||||
// reconnect();
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (state.socket) {
|
||||
state.socket.close();
|
||||
console.log('socket关闭');
|
||||
}
|
||||
|
||||
//重连
|
||||
// this.reconnect()
|
||||
}
|
||||
|
||||
function getMessage(msg: string) {
|
||||
// console.log(msg)
|
||||
state.term.write(msg['data']);
|
||||
//msg是返回的数据
|
||||
// msg = JSON.parse(msg.data);
|
||||
// this.socket.send("ping");//有事没事ping一下,看看ws还活着没
|
||||
// //switch用于处理返回的数据,根据返回数据的格式去判断
|
||||
// switch (msg["operation"]) {
|
||||
// case "stdout":
|
||||
// this.term.write(msg["data"]);//这里write也许不是固定的,失败后找后端看一下该怎么往term里面write
|
||||
// break;
|
||||
// default:
|
||||
// console.error("Unexpected message type:", msg);//但是错误是固定的。。。。
|
||||
// }
|
||||
//收到服务器信息,心跳重置
|
||||
// this.reset();
|
||||
function getMessage(msg: any) {
|
||||
// msg.data是真正后端返回的数据
|
||||
state.term.write(msg.data);
|
||||
}
|
||||
|
||||
function send(msg: any) {
|
||||
@@ -175,11 +169,18 @@ export default defineComponent({
|
||||
|
||||
function sendCmd(key: any) {
|
||||
send({
|
||||
type: 'cmd',
|
||||
type: data,
|
||||
msg: key,
|
||||
});
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (state.socket) {
|
||||
state.socket.close();
|
||||
console.log('socket关闭');
|
||||
}
|
||||
}
|
||||
|
||||
function closeAll() {
|
||||
close();
|
||||
if (state.term) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import Api from '@/common/Api';
|
||||
export const machineApi = {
|
||||
// 获取权限列表
|
||||
list: Api.create("/machines", 'get'),
|
||||
getMachinePwd: Api.create("/machines/{id}/pwd", 'get'),
|
||||
info: Api.create("/machines/{id}/sysinfo", 'get'),
|
||||
stats: Api.create("/machines/{id}/stats", 'get'),
|
||||
process: Api.create("/machines/{id}/process", 'get'),
|
||||
@@ -32,5 +33,6 @@ export const machineApi = {
|
||||
addConf: Api.create("/machines/{machineId}/files", 'post'),
|
||||
// 删除配置的文件or目录
|
||||
delConf: Api.create("/machines/{machineId}/files/{id}", 'delete'),
|
||||
terminal: Api.create("/api/machines/{id}/terminal", 'get')
|
||||
terminal: Api.create("/api/machines/{id}/terminal", 'get'),
|
||||
recDirNames: Api.create("/machines/rec/names", 'get')
|
||||
}
|
||||
@@ -3,36 +3,45 @@
|
||||
<div class="toolbar">
|
||||
<el-row type="flex" justify="space-between">
|
||||
<el-col :span="24">
|
||||
<project-env-select @changeProjectEnv="changeProjectEnv">
|
||||
<template #default>
|
||||
<el-form-item label="实例" label-width="40px">
|
||||
<el-select v-model="mongoId" placeholder="请选择mongo" @change="changeMongo">
|
||||
<el-option v-for="item in mongoList" :key="item.id" :label="item.name" :value="item.id">
|
||||
<span style="float: left">{{ item.name }}</span>
|
||||
<span style="float: right; color: #8492a6; margin-left: 6px; font-size: 13px">{{ ` [${item.uri}]` }}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form class="search-form" label-position="right" :inline="true">
|
||||
<el-form-item label="标签">
|
||||
<el-select
|
||||
@change="changeTag"
|
||||
@focus="getTags"
|
||||
v-model="query.tagPath"
|
||||
placeholder="请选择标签"
|
||||
filterable
|
||||
style="width: 250px"
|
||||
>
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="实例" label-width="40px">
|
||||
<el-select v-model="mongoId" placeholder="请选择mongo" @change="changeMongo">
|
||||
<el-option v-for="item in mongoList" :key="item.id" :label="item.name" :value="item.id">
|
||||
<span style="float: left">{{ item.name }}</span>
|
||||
<span style="float: right; color: #8492a6; margin-left: 6px; font-size: 13px">{{ ` [${item.uri}]` }}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="库" label-width="20px">
|
||||
<el-select v-model="database" placeholder="请选择库" @change="changeDatabase" filterable>
|
||||
<el-option v-for="item in databases" :key="item.Name" :label="item.Name" :value="item.Name">
|
||||
<span style="float: left">{{ item.Name }}</span>
|
||||
<span style="float: right; color: #8492a6; margin-left: 4px; font-size: 13px">{{
|
||||
` [${formatByteSize(item.SizeOnDisk)}]`
|
||||
}}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="库" label-width="20px">
|
||||
<el-select v-model="database" placeholder="请选择库" @change="changeDatabase" filterable>
|
||||
<el-option v-for="item in databases" :key="item.Name" :label="item.Name" :value="item.Name">
|
||||
<span style="float: left">{{ item.Name }}</span>
|
||||
<span style="float: right; color: #8492a6; margin-left: 4px; font-size: 13px">{{
|
||||
` [${formatByteSize(item.SizeOnDisk)}]`
|
||||
}}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="集合" label-width="40px">
|
||||
<el-select v-model="collection" placeholder="请选择集合" @change="changeCollection" filterable>
|
||||
<el-option v-for="item in collections" :key="item" :label="item" :value="item">
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</template>
|
||||
</project-env-select>
|
||||
<el-form-item label="集合" label-width="40px">
|
||||
<el-select v-model="collection" placeholder="请选择集合" @change="changeCollection" filterable>
|
||||
<el-option v-for="item in collections" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
@@ -64,12 +73,7 @@
|
||||
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
<el-link
|
||||
@click="onSaveDoc(item.value)"
|
||||
:underline="false"
|
||||
type="warning"
|
||||
icon="DocumentChecked"
|
||||
></el-link>
|
||||
<el-link @click="onSaveDoc(item.value)" :underline="false" type="warning" icon="DocumentChecked"></el-link>
|
||||
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
|
||||
@@ -120,7 +124,7 @@
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog width="800px" title="json编辑器" v-model="jsoneditorDialog.visible" @close="onCloseJsonEditDialog" :close-on-click-modal="false">
|
||||
<el-dialog width="70%" title="json编辑器" v-model="jsoneditorDialog.visible" @close="onCloseJsonEditDialog" :close-on-click-modal="false">
|
||||
<json-edit v-model="jsoneditorDialog.doc" />
|
||||
</el-dialog>
|
||||
|
||||
@@ -132,36 +136,38 @@
|
||||
import { mongoApi } from './api';
|
||||
import { toRefs, ref, reactive, defineComponent } from 'vue';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import ProjectEnvSelect from '../component/ProjectEnvSelect.vue';
|
||||
|
||||
import { isTrue, notBlank, notNull } from '@/common/assert';
|
||||
import { formatByteSize } from '@/common/utils/format';
|
||||
import JsonEdit from '@/components/jsonedit/index.vue';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'MongoDataOp',
|
||||
components: {
|
||||
ProjectEnvSelect,
|
||||
JsonEdit,
|
||||
},
|
||||
setup() {
|
||||
const findParamInputRef: any = ref(null);
|
||||
const state = reactive({
|
||||
loading: false,
|
||||
mongoList: [],
|
||||
tags: [],
|
||||
mongoList: [] as any,
|
||||
query: {
|
||||
envId: 0,
|
||||
tagPath: null,
|
||||
},
|
||||
mongoId: null, // 当前选择操作的mongo
|
||||
database: '', // 当前选择操作的库
|
||||
collection: '', //当前选中的collection
|
||||
activeName: '', // 当前操作的tab
|
||||
databases: [],
|
||||
collections: [],
|
||||
dataTabs: {}, // 数据tabs
|
||||
databases: [] as any,
|
||||
collections: [] as any,
|
||||
dataTabs: {} as any, // 数据tabs
|
||||
findDialog: {
|
||||
visible: false,
|
||||
findParam: {
|
||||
limit: 0,
|
||||
skip: 0,
|
||||
filter: '',
|
||||
sort: '',
|
||||
},
|
||||
@@ -178,24 +184,27 @@ export default defineComponent({
|
||||
});
|
||||
|
||||
const searchMongo = async () => {
|
||||
notNull(state.query.envId, '请先选择项目环境');
|
||||
notNull(state.query.tagPath, '请先选择标签');
|
||||
const res = await mongoApi.mongoList.request(state.query);
|
||||
state.mongoList = res.list;
|
||||
};
|
||||
|
||||
const changeProjectEnv = (projectId: any, envId: any) => {
|
||||
const changeTag = (tagPath: string) => {
|
||||
state.databases = [];
|
||||
state.collections = [];
|
||||
state.mongoId = null;
|
||||
state.collection = '';
|
||||
state.database = '';
|
||||
state.dataTabs = {};
|
||||
if (envId != null) {
|
||||
state.query.envId = envId;
|
||||
if (tagPath != null) {
|
||||
searchMongo();
|
||||
}
|
||||
};
|
||||
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const changeMongo = () => {
|
||||
state.databases = [];
|
||||
state.collections = [];
|
||||
@@ -419,7 +428,8 @@ export default defineComponent({
|
||||
return {
|
||||
...toRefs(state),
|
||||
findParamInputRef,
|
||||
changeProjectEnv,
|
||||
getTags,
|
||||
changeTag,
|
||||
changeMongo,
|
||||
changeDatabase,
|
||||
changeCollection,
|
||||
|
||||
@@ -2,17 +2,10 @@
|
||||
<div>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :close-on-click-modal="false" width="38%" :destroy-on-close="true">
|
||||
<el-form :model="form" ref="mongoForm" :rules="rules" label-width="85px">
|
||||
<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>
|
||||
</el-select>
|
||||
<el-form-item prop="tagId" label="标签:" required>
|
||||
<tag-select v-model:tag-id="form.tagId" v-model:tag-path="form.tagPath" style="width: 100%" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="envId" label="环境" required>
|
||||
<el-select @change="changeEnv" style="width: 100%" v-model="form.envId" placeholder="请选择环境">
|
||||
<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="name" label="名称" required>
|
||||
<el-input v-model.trim="form.name" placeholder="请输入名称" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
@@ -58,20 +51,19 @@
|
||||
<script lang="ts">
|
||||
import { toRefs, reactive, watch, defineComponent, ref } from 'vue';
|
||||
import { mongoApi } from './api';
|
||||
import { projectApi } from '../project/api.ts';
|
||||
import { machineApi } from '../machine/api.ts';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { RsaEncrypt } from '@/common/rsa';
|
||||
import TagSelect from '../component/TagSelect.vue';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'MongoEdit',
|
||||
components: {
|
||||
TagSelect,
|
||||
},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
projects: {
|
||||
type: Array,
|
||||
},
|
||||
mongo: {
|
||||
type: [Boolean, Object],
|
||||
},
|
||||
@@ -83,33 +75,22 @@ export default defineComponent({
|
||||
const mongoForm: any = ref(null);
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
projects: [],
|
||||
envs: [],
|
||||
sshTunnelMachineList: [],
|
||||
sshTunnelMachineList: [] as any,
|
||||
form: {
|
||||
id: null,
|
||||
name: null,
|
||||
uri: null,
|
||||
enableSshTunnel: -1,
|
||||
sshTunnelMachineId: null,
|
||||
project: null,
|
||||
projectId: null,
|
||||
envId: null,
|
||||
env: null,
|
||||
tagId: null as any,
|
||||
tagPath: null as any,
|
||||
},
|
||||
btnLoading: false,
|
||||
rules: {
|
||||
projectId: [
|
||||
tagId: [
|
||||
{
|
||||
required: true,
|
||||
message: '请选择项目',
|
||||
trigger: ['change', 'blur'],
|
||||
},
|
||||
],
|
||||
envId: [
|
||||
{
|
||||
required: true,
|
||||
message: '请选择环境',
|
||||
message: '请选择标签',
|
||||
trigger: ['change', 'blur'],
|
||||
},
|
||||
],
|
||||
@@ -135,12 +116,9 @@ export default defineComponent({
|
||||
if (!state.dialogVisible) {
|
||||
return;
|
||||
}
|
||||
state.projects = newValue.projects;
|
||||
if (newValue.mongo) {
|
||||
getEnvs(newValue.mongo.projectId);
|
||||
state.form = { ...newValue.mongo };
|
||||
} else {
|
||||
state.envs = [];
|
||||
state.form = { db: 0 } as any;
|
||||
}
|
||||
getSshTunnelMachines();
|
||||
@@ -153,35 +131,11 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const getEnvs = async (projectId: any) => {
|
||||
state.envs = await projectApi.projectEnvs.request({ projectId });
|
||||
};
|
||||
|
||||
const changeProject = (projectId: number) => {
|
||||
for (let p of state.projects as any) {
|
||||
if (p.id == projectId) {
|
||||
state.form.project = p.name;
|
||||
}
|
||||
}
|
||||
state.form.envId = null;
|
||||
state.form.env = null;
|
||||
state.envs = [];
|
||||
getEnvs(projectId);
|
||||
};
|
||||
|
||||
const changeEnv = (envId: number) => {
|
||||
for (let p of state.envs as any) {
|
||||
if (p.id == envId) {
|
||||
state.form.env = p.name;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const btnOk = async () => {
|
||||
mongoForm.value.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
const reqForm = { ...state.form };
|
||||
reqForm.uri = await RsaEncrypt(reqForm.uri);
|
||||
// reqForm.uri = await RsaEncrypt(reqForm.uri);
|
||||
mongoApi.saveMongo.request(reqForm).then(() => {
|
||||
ElMessage.success('保存成功');
|
||||
emit('val-change', state.form);
|
||||
@@ -207,9 +161,7 @@ export default defineComponent({
|
||||
return {
|
||||
...toRefs(state),
|
||||
mongoForm,
|
||||
changeProject,
|
||||
getSshTunnelMachines,
|
||||
changeEnv,
|
||||
btnOk,
|
||||
cancel,
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<el-button type="primary" icon="edit" :disabled="currentId == null" @click="editMongo(false)" plain>编辑</el-button>
|
||||
<el-button type="danger" icon="delete" :disabled="currentId == null" @click="deleteMongo" plain>删除</el-button>
|
||||
<div style="float: right">
|
||||
<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 @focus="getTags" v-model="query.tagPath" placeholder="请选择标签" filterable clearable>
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-button class="ml5" @click="search" type="success" icon="search"></el-button>
|
||||
</div>
|
||||
@@ -18,8 +18,7 @@
|
||||
</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="tagPath" label="标签路径" min-width="150" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="name" label="名称" width></el-table-column>
|
||||
<el-table-column prop="uri" label="连接uri" min-width="150" show-overflow-tooltip>
|
||||
<template #default="scope">
|
||||
@@ -28,7 +27,7 @@
|
||||
</el-table-column>
|
||||
<el-table-column prop="createTime" label="创建时间" min-width="150">
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
{{ dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="creator" label="创建人"></el-table-column>
|
||||
@@ -180,7 +179,6 @@
|
||||
|
||||
<mongo-edit
|
||||
@val-change="valChange"
|
||||
:projects="projects"
|
||||
:title="mongoEditDialog.title"
|
||||
v-model:visible="mongoEditDialog.visible"
|
||||
v-model:mongo="mongoEditDialog.data"
|
||||
@@ -192,9 +190,10 @@
|
||||
import { mongoApi } from './api';
|
||||
import { toRefs, reactive, defineComponent, onMounted } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { projectApi } from '../project/api.ts';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
import MongoEdit from './MongoEdit.vue';
|
||||
import { formatByteSize } from '@/common/utils/format';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'MongoList',
|
||||
@@ -203,7 +202,7 @@ export default defineComponent({
|
||||
},
|
||||
setup() {
|
||||
const state = reactive({
|
||||
projects: [],
|
||||
tags: [],
|
||||
list: [],
|
||||
total: 0,
|
||||
currentId: null,
|
||||
@@ -211,12 +210,11 @@ export default defineComponent({
|
||||
query: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
prjectId: null,
|
||||
clusterId: null,
|
||||
tagPath: null,
|
||||
},
|
||||
mongoEditDialog: {
|
||||
visible: false,
|
||||
data: null,
|
||||
data: null as any,
|
||||
title: '新增mongo',
|
||||
},
|
||||
databaseDialog: {
|
||||
@@ -225,7 +223,7 @@ export default defineComponent({
|
||||
title: '',
|
||||
statsDialog: {
|
||||
visible: false,
|
||||
data: {},
|
||||
data: {} as any,
|
||||
title: '',
|
||||
},
|
||||
},
|
||||
@@ -236,7 +234,7 @@ export default defineComponent({
|
||||
title: '',
|
||||
statsDialog: {
|
||||
visible: false,
|
||||
data: {},
|
||||
data: {} as any,
|
||||
title: '',
|
||||
},
|
||||
},
|
||||
@@ -250,7 +248,6 @@ export default defineComponent({
|
||||
|
||||
onMounted(async () => {
|
||||
search();
|
||||
state.projects = await projectApi.accountProjects.request(null);
|
||||
});
|
||||
|
||||
const handlePageChange = (curPage: number) => {
|
||||
@@ -371,7 +368,11 @@ export default defineComponent({
|
||||
state.total = res.total;
|
||||
};
|
||||
|
||||
const editMongo = (isAdd = false) => {
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const editMongo = async (isAdd = false) => {
|
||||
if (isAdd) {
|
||||
state.mongoEditDialog.data = null;
|
||||
state.mongoEditDialog.title = '新增mongo';
|
||||
@@ -390,6 +391,8 @@ export default defineComponent({
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
dateFormat,
|
||||
getTags,
|
||||
search,
|
||||
handlePageChange,
|
||||
choose,
|
||||
|
||||
@@ -1,415 +0,0 @@
|
||||
<template>
|
||||
<div class="project-list">
|
||||
<el-card>
|
||||
<div>
|
||||
<el-button @click="showAddProjectDialog" v-auth="permissions.saveProject" type="primary" icon="plus">添加</el-button>
|
||||
<el-button
|
||||
@click="showAddProjectDialog(chooseData)"
|
||||
v-auth="permissions.saveProject"
|
||||
:disabled="chooseId == null"
|
||||
type="primary"
|
||||
icon="edit"
|
||||
>编辑</el-button
|
||||
>
|
||||
<el-button @click="showMembers(chooseData)" :disabled="chooseId == null" type="success" icon="user">成员管理</el-button>
|
||||
|
||||
<el-button @click="showEnv(chooseData)" :disabled="chooseId == null" type="info" icon="setting">环境管理</el-button>
|
||||
|
||||
<el-button v-auth="permissions.delProject" @click="delProject" :disabled="chooseId == null" type="danger" icon="delete"
|
||||
>删除</el-button
|
||||
>
|
||||
|
||||
<div style="float: right">
|
||||
<el-input class="mr2" placeholder="请输入项目名!" style="width: 200px" v-model="query.name" @clear="search" clearable></el-input>
|
||||
<el-button @click="search" type="success" icon="search"></el-button>
|
||||
</div>
|
||||
</div>
|
||||
<el-table :data="projects" @current-change="choose" ref="table" style="width: 100%">
|
||||
<el-table-column label="选择" width="50px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
</el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="name" label="项目名"></el-table-column>
|
||||
<el-table-column prop="remark" label="描述" min-width="180px" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="createTime" label="创建时间">
|
||||
<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="查看更多" min-width="80px">
|
||||
<template #default="scope">
|
||||
<el-link @click.prevent="showMembers(scope.row)" type="success">成员</el-link>
|
||||
|
||||
<el-link class="ml5" @click.prevent="showEnv(scope.row)" type="info">环境</el-link>
|
||||
</template>
|
||||
</el-table-column> -->
|
||||
</el-table>
|
||||
<el-row style="margin-top: 20px" type="flex" justify="end">
|
||||
<el-pagination
|
||||
style="text-align: right"
|
||||
@current-change="handlePageChange"
|
||||
:total="total"
|
||||
layout="prev, pager, next, total, jumper"
|
||||
v-model:current-page="query.pageNum"
|
||||
:page-size="query.pageSize"
|
||||
></el-pagination>
|
||||
</el-row>
|
||||
</el-card>
|
||||
|
||||
<el-dialog width="400px" title="项目编辑" :before-close="cancelAddProject" v-model="addProjectDialog.visible">
|
||||
<el-form :model="addProjectDialog.form" label-width="70px">
|
||||
<el-form-item prop="name" label="项目名:" required>
|
||||
<el-input :disabled="addProjectDialog.form.id ? true : false" v-model="addProjectDialog.form.name" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="描述:">
|
||||
<el-input v-model="addProjectDialog.form.remark" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancelAddProject()">取 消</el-button>
|
||||
<el-button @click="addProject" type="primary">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog width="500px" :title="showEnvDialog.title" v-model="showEnvDialog.visible">
|
||||
<div class="toolbar">
|
||||
<el-button @click="showAddEnvDialog" v-auth="permissions.saveMember" type="primary" icon="plus">添加</el-button>
|
||||
<!-- <el-button v-auth="'role:update'" :disabled="chooseId == null" type="danger" icon="delete">删除</el-button> -->
|
||||
</div>
|
||||
<el-table border :data="showEnvDialog.envs">
|
||||
<el-table-column property="name" label="环境名" width="125"></el-table-column>
|
||||
<el-table-column property="remark" label="描述" width="125"></el-table-column>
|
||||
<el-table-column property="createTime" label="创建时间">
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<el-dialog width="400px" title="添加环境" :before-close="cancelAddEnv" v-model="showEnvDialog.addVisible">
|
||||
<el-form :model="showEnvDialog.envForm" label-width="70px">
|
||||
<el-form-item prop="name" label="环境名:" required>
|
||||
<el-input v-model="showEnvDialog.envForm.name" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="描述:">
|
||||
<el-input v-model="showEnvDialog.envForm.remark" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancelAddEnv()">取 消</el-button>
|
||||
<el-button v-auth="permissions.saveEnv" @click="addEnv" type="primary" :loading="btnLoading">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog width="500px" :title="showMemDialog.title" v-model="showMemDialog.visible">
|
||||
<div class="toolbar">
|
||||
<el-button v-auth="permissions.saveMember" @click="showAddMemberDialog()" type="primary" icon="plus">添加</el-button>
|
||||
<el-button v-auth="permissions.delMember" @click="deleteMember" :disabled="showMemDialog.chooseId == null" type="danger" icon="delete"
|
||||
>移除</el-button
|
||||
>
|
||||
</div>
|
||||
<el-table @current-change="chooseMember" border :data="showMemDialog.members.list">
|
||||
<el-table-column label="选择" width="50px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="showMemDialog.chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
</el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column property="username" label="账号" width="125"></el-table-column>
|
||||
<el-table-column property="createTime" label="加入时间">
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column property="creator" label="分配者" width="125"></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
@current-change="setMemebers"
|
||||
style="text-align: center"
|
||||
background
|
||||
layout="prev, pager, next, total, jumper"
|
||||
:total="showMemDialog.members.total"
|
||||
v-model:current-page="showMemDialog.query.pageNum"
|
||||
:page-size="showMemDialog.query.pageSize"
|
||||
/>
|
||||
|
||||
<el-dialog width="400px" title="添加成员" :before-close="cancelAddMember" v-model="showMemDialog.addVisible">
|
||||
<el-form :model="showMemDialog.memForm" label-width="70px">
|
||||
<el-form-item label="账号:">
|
||||
<el-select
|
||||
style="width: 100%"
|
||||
remote
|
||||
:remote-method="getAccount"
|
||||
v-model="showMemDialog.memForm.accountId"
|
||||
filterable
|
||||
placeholder="请选择"
|
||||
>
|
||||
<el-option v-for="item in showMemDialog.accounts" :key="item.id" :label="item.username" :value="item.id"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<!-- <el-form-item label="描述:">
|
||||
<el-input v-model="showEnvDialog.envForm.remark" auto-complete="off"></el-input>
|
||||
</el-form-item> -->
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancelAddMember()">取 消</el-button>
|
||||
<el-button v-auth="permissions.saveMember" @click="addMember" type="primary" :loading="btnLoading">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, reactive, onMounted, defineComponent } from 'vue';
|
||||
import { projectApi } from './api';
|
||||
import { accountApi } from '../../system/api';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { notEmpty, notNull } from '@/common/assert';
|
||||
export default defineComponent({
|
||||
name: 'ProjectList',
|
||||
components: {},
|
||||
setup() {
|
||||
const state = reactive({
|
||||
permissions: {
|
||||
saveProject: 'project:save',
|
||||
delProject: 'project:del',
|
||||
saveMember: 'project:member:add',
|
||||
delMember: 'project:member:del',
|
||||
saveEnv: 'project:env:add',
|
||||
},
|
||||
query: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
name: null,
|
||||
},
|
||||
total: 0,
|
||||
projects: [],
|
||||
btnLoading: false,
|
||||
chooseId: null as any,
|
||||
chooseData: null as any,
|
||||
addProjectDialog: {
|
||||
title: '新增项目',
|
||||
visible: false,
|
||||
form: { name: '', remark: '' },
|
||||
},
|
||||
showEnvDialog: {
|
||||
visible: false,
|
||||
envs: [],
|
||||
title: '',
|
||||
addVisible: false,
|
||||
envForm: {
|
||||
name: '',
|
||||
remark: '',
|
||||
projectId: 0,
|
||||
},
|
||||
},
|
||||
showMemDialog: {
|
||||
visible: false,
|
||||
chooseId: null,
|
||||
chooseData: null,
|
||||
query: {
|
||||
pageSize: 8,
|
||||
pageNum: 1,
|
||||
projectId: null,
|
||||
},
|
||||
members: {
|
||||
list: [],
|
||||
total: null,
|
||||
},
|
||||
title: '',
|
||||
addVisible: false,
|
||||
memForm: {},
|
||||
accounts: [],
|
||||
},
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
search();
|
||||
});
|
||||
|
||||
const search = async () => {
|
||||
let res = await projectApi.projects.request(state.query);
|
||||
state.projects = res.list;
|
||||
state.total = res.total;
|
||||
};
|
||||
|
||||
const handlePageChange = (curPage: number) => {
|
||||
state.query.pageNum = curPage;
|
||||
search();
|
||||
};
|
||||
|
||||
const showAddProjectDialog = (data: any) => {
|
||||
if (data) {
|
||||
state.addProjectDialog.form = { ...data };
|
||||
} else {
|
||||
state.addProjectDialog.form = {} as any;
|
||||
}
|
||||
state.addProjectDialog.visible = true;
|
||||
};
|
||||
|
||||
const cancelAddProject = () => {
|
||||
state.addProjectDialog.visible = false;
|
||||
state.addProjectDialog.form = {} as any;
|
||||
};
|
||||
|
||||
const addProject = async () => {
|
||||
const form = state.addProjectDialog.form as any;
|
||||
notEmpty(form.name, '项目名不能为空');
|
||||
notEmpty(form.remark, '项目描述不能为空');
|
||||
|
||||
await projectApi.saveProject.request(form);
|
||||
ElMessage.success('保存成功');
|
||||
search();
|
||||
cancelAddProject();
|
||||
};
|
||||
|
||||
const delProject = async () => {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除该项目?`, '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
});
|
||||
await projectApi.delProject.request({ id: state.chooseId });
|
||||
ElMessage.success('删除成功');
|
||||
state.chooseData = null;
|
||||
state.chooseId = null;
|
||||
search();
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
const choose = (item: any) => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
state.chooseId = item.id;
|
||||
state.chooseData = item;
|
||||
};
|
||||
|
||||
const showMembers = async (project: any) => {
|
||||
state.showMemDialog.query.projectId = project.id;
|
||||
await setMemebers();
|
||||
state.showMemDialog.title = `${project.name}的成员信息`;
|
||||
state.showMemDialog.visible = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 选中成员
|
||||
*/
|
||||
const chooseMember = (item: any) => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
state.showMemDialog.chooseData = item;
|
||||
state.showMemDialog.chooseId = item.id;
|
||||
};
|
||||
|
||||
const deleteMember = async () => {
|
||||
notNull(state.showMemDialog.chooseData, '请选选择成员');
|
||||
await projectApi.deleteProjectMem.request(state.showMemDialog.chooseData);
|
||||
ElMessage.success('移除成功');
|
||||
// 重新赋值成员列表
|
||||
setMemebers();
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置成员列表信息
|
||||
*/
|
||||
const setMemebers = async () => {
|
||||
const res = await projectApi.projectMems.request(state.showMemDialog.query);
|
||||
state.showMemDialog.members.list = res.list;
|
||||
state.showMemDialog.members.total = res.total;
|
||||
};
|
||||
|
||||
const showEnv = async (project: any) => {
|
||||
state.showEnvDialog.envs = await projectApi.projectEnvs.request({ projectId: project.id });
|
||||
state.showEnvDialog.title = `${project.name}的环境信息`;
|
||||
state.showEnvDialog.visible = true;
|
||||
};
|
||||
|
||||
const showAddMemberDialog = () => {
|
||||
state.showMemDialog.addVisible = true;
|
||||
};
|
||||
|
||||
const addMember = async () => {
|
||||
const memForm = state.showMemDialog.memForm as any;
|
||||
memForm.projectId = state.chooseData.id;
|
||||
notEmpty(memForm.accountId, '请先选择账号');
|
||||
|
||||
await projectApi.saveProjectMem.request(memForm);
|
||||
ElMessage.success('保存成功');
|
||||
setMemebers();
|
||||
cancelAddMember();
|
||||
};
|
||||
|
||||
const cancelAddMember = () => {
|
||||
state.showMemDialog.memForm = {};
|
||||
state.showMemDialog.addVisible = false;
|
||||
state.showMemDialog.chooseData = null;
|
||||
state.showMemDialog.chooseId = null;
|
||||
};
|
||||
|
||||
const getAccount = (username: any) => {
|
||||
accountApi.list.request({ username }).then((res) => {
|
||||
state.showMemDialog.accounts = res.list;
|
||||
});
|
||||
};
|
||||
|
||||
const showAddEnvDialog = () => {
|
||||
state.showEnvDialog.addVisible = true;
|
||||
};
|
||||
|
||||
const addEnv = async () => {
|
||||
const envForm = state.showEnvDialog.envForm;
|
||||
envForm.projectId = state.chooseData.id;
|
||||
await projectApi.saveProjectEnv.request(envForm);
|
||||
ElMessage.success('保存成功');
|
||||
state.showEnvDialog.envs = await projectApi.projectEnvs.request({ projectId: envForm.projectId });
|
||||
cancelAddEnv();
|
||||
};
|
||||
|
||||
const cancelAddEnv = () => {
|
||||
state.showEnvDialog.envForm = {} as any;
|
||||
state.showEnvDialog.addVisible = false;
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
search,
|
||||
handlePageChange,
|
||||
choose,
|
||||
showAddProjectDialog,
|
||||
addProject,
|
||||
delProject,
|
||||
cancelAddProject,
|
||||
showMembers,
|
||||
setMemebers,
|
||||
showEnv,
|
||||
showAddMemberDialog,
|
||||
addMember,
|
||||
chooseMember,
|
||||
deleteMember,
|
||||
cancelAddMember,
|
||||
showAddEnvDialog,
|
||||
addEnv,
|
||||
cancelAddEnv,
|
||||
getAccount,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
</style>
|
||||
@@ -1,16 +0,0 @@
|
||||
import Api from '@/common/Api';
|
||||
|
||||
export const projectApi = {
|
||||
// 获取账号可访问的项目列表
|
||||
accountProjects: Api.create("/accounts/projects", 'get'),
|
||||
projects: Api.create("/projects", 'get'),
|
||||
saveProject: Api.create("/projects", 'post'),
|
||||
delProject: Api.create("/projects", 'delete'),
|
||||
// 获取项目下的环境信息
|
||||
projectEnvs: Api.create("/projects/{projectId}/envs", 'get'),
|
||||
saveProjectEnv: Api.create("/projects/{projectId}/envs", 'post'),
|
||||
// 获取项目下的成员信息
|
||||
projectMems: Api.create("/projects/{projectId}/members", 'get'),
|
||||
saveProjectMem: Api.create("/projects/{projectId}/members", 'post'),
|
||||
deleteProjectMem: Api.create("/projects/{projectId}/members/{accountId}", 'delete'),
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
<template>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :show-close="false" width="750px" :destroy-on-close="true">
|
||||
<el-form label-width="85px">
|
||||
<el-form-item prop="key" label="key:">
|
||||
<el-input :disabled="operationType == 2" v-model="key.key"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="timed" label="过期时间:">
|
||||
<el-input v-model.number="key.timed" type="number"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="dataType" label="数据类型:">
|
||||
<el-select :disabled="operationType == 2" style="width: 100%" v-model="key.type" placeholder="请选择数据类型">
|
||||
<el-option key="string" label="string" value="string"> </el-option>
|
||||
<el-option key="hash" label="hash" value="hash"> </el-option>
|
||||
<el-option key="set" label="set" value="set"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item v-if="key.type == 'string'" prop="value" label="内容:">
|
||||
<div id="string-value-text" style="width: 100%">
|
||||
<el-input class="json-text" v-model="string.value" type="textarea" :autosize="{ minRows: 10, maxRows: 20 }"></el-input>
|
||||
<el-select class="text-type-select" @change="onChangeTextType" v-model="string.type">
|
||||
<el-option key="text" label="text" value="text"> </el-option>
|
||||
<el-option key="json" label="json" value="json"> </el-option>
|
||||
</el-select>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<span v-if="key.type == 'hash'">
|
||||
<el-button @click="onAddHashValue" icon="plus" size="small" plain class="mt10">添加</el-button>
|
||||
<el-table :data="hash.value" stripe style="width: 100%">
|
||||
<el-table-column prop="key" label="key" width>
|
||||
<template #default="scope">
|
||||
<el-input v-model="scope.row.key" clearable size="small"></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="value" label="value" min-width="200">
|
||||
<template #default="scope">
|
||||
<el-input
|
||||
v-model="scope.row.value"
|
||||
clearable
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 2, maxRows: 10 }"
|
||||
size="small"
|
||||
></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90">
|
||||
<template #default="scope">
|
||||
<el-button type="danger" @click="hash.value.splice(scope.$index, 1)" icon="delete" size="small" plain>删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</span>
|
||||
|
||||
<span v-if="key.type == 'set'">
|
||||
<el-button @click="onAddSetValue" icon="plus" size="small" plain class="mt10">添加</el-button>
|
||||
<el-table :data="set.value" stripe style="width: 100%">
|
||||
<el-table-column prop="value" label="value" min-width="200">
|
||||
<template #default="scope">
|
||||
<el-input
|
||||
v-model="scope.row.value"
|
||||
clearable
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 2, maxRows: 10 }"
|
||||
size="small"
|
||||
></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90">
|
||||
<template #default="scope">
|
||||
<el-button type="danger" @click="set.value.splice(scope.$index, 1)" icon="delete" size="small" plain>删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</span>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()">取 消</el-button>
|
||||
<el-button @click="saveValue" type="primary" v-auth="'redis:data:save'">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, watch, toRefs } from 'vue';
|
||||
import { redisApi } from './api';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { isTrue, notEmpty } from '@/common/assert';
|
||||
import { formatJsonString } from '@/common/utils/format';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'DateEdit',
|
||||
components: {},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
},
|
||||
redisId: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
keyInfo: {
|
||||
type: [Object],
|
||||
},
|
||||
// 操作类型,1:新增,2:修改
|
||||
operationType: {
|
||||
type: [Number],
|
||||
},
|
||||
stringValue: {
|
||||
type: [String],
|
||||
},
|
||||
setValue: {
|
||||
type: [Array, Object],
|
||||
},
|
||||
hashValue: {
|
||||
type: [Array, Object],
|
||||
},
|
||||
},
|
||||
emits: ['valChange', 'cancel', 'update:visible'],
|
||||
setup(props: any, { emit }) {
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
operationType: 1,
|
||||
redisId: '',
|
||||
key: {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
},
|
||||
string: {
|
||||
type: 'text',
|
||||
value: '',
|
||||
},
|
||||
hash: {
|
||||
value: [
|
||||
{
|
||||
key: '',
|
||||
value: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
set: {
|
||||
value: [{ value: '' }],
|
||||
},
|
||||
});
|
||||
|
||||
const cancel = () => {
|
||||
emit('update:visible', false);
|
||||
emit('cancel');
|
||||
setTimeout(() => {
|
||||
state.key = {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
};
|
||||
state.string.value = '';
|
||||
state.string.type = 'text';
|
||||
state.hash.value = [
|
||||
{
|
||||
key: '',
|
||||
value: '',
|
||||
},
|
||||
];
|
||||
}, 500);
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(val) => {
|
||||
state.dialogVisible = val;
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.redisId,
|
||||
(val) => {
|
||||
state.redisId = val;
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.operationType,
|
||||
(val) => {
|
||||
state.operationType = val;
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.keyInfo,
|
||||
(val) => {
|
||||
if (val) {
|
||||
state.key = { ...val };
|
||||
}
|
||||
},
|
||||
{
|
||||
deep: true, // 深度监听的参数
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.stringValue,
|
||||
(val) => {
|
||||
if (val) {
|
||||
state.string.value = val;
|
||||
}
|
||||
},
|
||||
{
|
||||
deep: true, // 深度监听的参数
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.setValue,
|
||||
(val) => {
|
||||
if (val) {
|
||||
state.set.value = val;
|
||||
}
|
||||
},
|
||||
{
|
||||
deep: true, // 深度监听的参数
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.hashValue,
|
||||
(val) => {
|
||||
if (val) {
|
||||
state.hash.value = val;
|
||||
}
|
||||
},
|
||||
{
|
||||
deep: true, // 深度监听的参数
|
||||
}
|
||||
);
|
||||
|
||||
const saveValue = async () => {
|
||||
notEmpty(state.key.key, 'key不能为空');
|
||||
|
||||
if (state.key.type == 'string') {
|
||||
notEmpty(state.string.value, 'value不能为空');
|
||||
const sv = { value: formatJsonString(state.string.value, true), id: state.redisId };
|
||||
Object.assign(sv, state.key);
|
||||
await redisApi.saveStringValue.request(sv);
|
||||
}
|
||||
|
||||
if (state.key.type == 'hash') {
|
||||
isTrue(state.hash.value.length > 0, 'hash内容不能为空');
|
||||
const sv = { value: state.hash.value, id: state.redisId };
|
||||
Object.assign(sv, state.key);
|
||||
await redisApi.saveHashValue.request(sv);
|
||||
}
|
||||
|
||||
if (state.key.type == 'set') {
|
||||
isTrue(state.set.value.length > 0, 'set内容不能为空');
|
||||
const sv = { value: state.set.value.map((x) => x.value), id: state.redisId };
|
||||
Object.assign(sv, state.key);
|
||||
await redisApi.saveSetValue.request(sv);
|
||||
}
|
||||
|
||||
ElMessage.success('数据保存成功');
|
||||
cancel();
|
||||
emit('valChange');
|
||||
};
|
||||
|
||||
const onAddHashValue = () => {
|
||||
state.hash.value.push({ key: '', value: '' });
|
||||
};
|
||||
|
||||
const onAddSetValue = () => {
|
||||
state.set.value.push({ value: '' });
|
||||
};
|
||||
|
||||
// 更改文本类型
|
||||
const onChangeTextType = (val: string) => {
|
||||
if (val == 'json') {
|
||||
state.string.value = formatJsonString(state.string.value, false);
|
||||
return;
|
||||
}
|
||||
if (val == 'text') {
|
||||
state.string.value = formatJsonString(state.string.value, true);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
saveValue,
|
||||
cancel,
|
||||
onAddHashValue,
|
||||
onAddSetValue,
|
||||
onChangeTextType,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
#string-value-text {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
position: relative;
|
||||
|
||||
.text-type-select {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
right: 10px;
|
||||
top: 10px;
|
||||
max-width: 70px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,39 +4,70 @@
|
||||
<div style="float: left">
|
||||
<el-row type="flex" justify="space-between">
|
||||
<el-col :span="24">
|
||||
<project-env-select @changeProjectEnv="changeProjectEnv" @clear="clearRedis">
|
||||
<template #default>
|
||||
<el-form-item label="redis" label-width="40px">
|
||||
<el-select v-model="scanParam.id" placeholder="请选择redis" @change="changeRedis" @clear="clearRedis" clearable>
|
||||
<el-option v-for="item in redisList" :key="item.id" :label="item.host" :value="item.id">
|
||||
<span style="float: left">{{ item.host }}</span>
|
||||
<span style="float: right; color: #8492a6; margin-left: 6px; font-size: 13px">{{
|
||||
`库: [${item.db}]`
|
||||
}}</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</template>
|
||||
</project-env-select>
|
||||
<el-form class="search-form" label-position="right" :inline="true">
|
||||
<el-form-item label="标签">
|
||||
<el-select
|
||||
@change="changeTag"
|
||||
@focus="getTags"
|
||||
v-model="query.tagPath"
|
||||
placeholder="请选择标签"
|
||||
filterable
|
||||
style="width: 250px"
|
||||
>
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="redis" label-width="40px">
|
||||
<el-select
|
||||
v-model="scanParam.id"
|
||||
placeholder="请选择redis"
|
||||
@change="changeRedis"
|
||||
@clear="clearRedis"
|
||||
clearable
|
||||
style="width: 250px"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in redisList"
|
||||
:key="item.id"
|
||||
:label="`${item.name ? item.name : ''} [${item.host}]`"
|
||||
:value="item.id"
|
||||
>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="库" label-width="20px">
|
||||
<el-select v-model="scanParam.db" @change="changeDb" placeholder="库" style="width: 85px">
|
||||
<el-option v-for="db in dbList" :key="db" :label="db" :value="db"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-col>
|
||||
<el-col class="mt10">
|
||||
<el-form class="search-form" label-position="right" :inline="true" label-width="60px">
|
||||
<el-form-item label="key" label-width="40px">
|
||||
<el-input
|
||||
placeholder="支持*模糊key"
|
||||
style="width: 240px"
|
||||
placeholder="match 支持*模糊key"
|
||||
style="width: 250px"
|
||||
v-model="scanParam.match"
|
||||
@clear="clear()"
|
||||
clearable
|
||||
></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="count" label-width="60px">
|
||||
<el-input placeholder="count" style="width: 62px" v-model.number="scanParam.count"></el-input>
|
||||
<el-form-item label="count" label-width="40px">
|
||||
<el-input placeholder="count" style="width: 70px" v-model.number="scanParam.count"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button @click="searchKey()" type="success" icon="search" plain></el-button>
|
||||
<el-button @click="scan()" icon="bottom" plain>scan</el-button>
|
||||
<el-button type="primary" icon="plus" @click="onAddData(false)" plain></el-button>
|
||||
<el-popover placement="right" :width="200" trigger="click">
|
||||
<template #reference>
|
||||
<el-button type="primary" icon="plus" plain></el-button>
|
||||
</template>
|
||||
<el-tag @click="onAddData('string')" :color="getTypeColor('string')" style="cursor: pointer">string</el-tag>
|
||||
<el-tag @click="onAddData('hash')" :color="getTypeColor('hash')" class="ml5" style="cursor: pointer">hash</el-tag>
|
||||
<el-tag @click="onAddData('set')" :color="getTypeColor('set')" class="ml5" style="cursor: pointer">set</el-tag>
|
||||
<!-- <el-tag @click="onAddData('list')" :color="getTypeColor('list')" class="ml5" style="cursor: pointer">list</el-tag> -->
|
||||
</el-popover>
|
||||
</el-form-item>
|
||||
<div style="float: right">
|
||||
<span>keys: {{ dbsize }}</span>
|
||||
@@ -53,7 +84,7 @@
|
||||
<el-tag :color="getTypeColor(scope.row.type)" size="small">{{ scope.row.type }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="ttl" label="ttl(过期时间)" width="130">
|
||||
<el-table-column prop="ttl" label="ttl(过期时间)" width="140">
|
||||
<template #default="scope">
|
||||
{{ ttlConveter(scope.row.ttl) }}
|
||||
</template>
|
||||
@@ -69,17 +100,46 @@
|
||||
|
||||
<div style="text-align: center; margin-top: 10px"></div>
|
||||
|
||||
<!-- <value-dialog v-model:visible="valueDialog.visible" :keyValue="valueDialog.value" /> -->
|
||||
|
||||
<data-edit
|
||||
v-model:visible="dataEdit.visible"
|
||||
<hash-value
|
||||
v-model:visible="hashValueDialog.visible"
|
||||
:operationType="dataEdit.operationType"
|
||||
:title="dataEdit.title"
|
||||
:keyInfo="dataEdit.keyInfo"
|
||||
:redisId="scanParam.id"
|
||||
:db="scanParam.db"
|
||||
@cancel="onCancelDataEdit"
|
||||
@valChange="searchKey"
|
||||
/>
|
||||
|
||||
<string-value
|
||||
v-model:visible="stringValueDialog.visible"
|
||||
:operationType="dataEdit.operationType"
|
||||
:title="dataEdit.title"
|
||||
:keyInfo="dataEdit.keyInfo"
|
||||
:redisId="scanParam.id"
|
||||
:db="scanParam.db"
|
||||
@cancel="onCancelDataEdit"
|
||||
@valChange="searchKey"
|
||||
/>
|
||||
|
||||
<set-value
|
||||
v-model:visible="setValueDialog.visible"
|
||||
:title="dataEdit.title"
|
||||
:keyInfo="dataEdit.keyInfo"
|
||||
:redisId="scanParam.id"
|
||||
:db="scanParam.db"
|
||||
:operationType="dataEdit.operationType"
|
||||
@valChange="searchKey"
|
||||
@cancel="onCancelDataEdit"
|
||||
/>
|
||||
|
||||
<list-value
|
||||
v-model:visible="listValueDialog.visible"
|
||||
:title="dataEdit.title"
|
||||
:keyInfo="dataEdit.keyInfo"
|
||||
:redisId="scanParam.id"
|
||||
:db="scanParam.db"
|
||||
:operationType="dataEdit.operationType"
|
||||
:stringValue="dataEdit.stringValue"
|
||||
:setValue="dataEdit.setValue"
|
||||
:hashValue="dataEdit.hashValue"
|
||||
@valChange="searchKey"
|
||||
@cancel="onCancelDataEdit"
|
||||
/>
|
||||
@@ -90,33 +150,37 @@
|
||||
import { redisApi } from './api';
|
||||
import { toRefs, reactive, defineComponent } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import ProjectEnvSelect from '../component/ProjectEnvSelect.vue';
|
||||
import DataEdit from './DataEdit.vue';
|
||||
import HashValue from './HashValue.vue';
|
||||
import StringValue from './StringValue.vue';
|
||||
import SetValue from './SetValue.vue';
|
||||
import ListValue from './ListValue.vue';
|
||||
import { isTrue, notBlank, notNull } from '@/common/assert';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'DataOperation',
|
||||
components: {
|
||||
DataEdit,
|
||||
ProjectEnvSelect,
|
||||
StringValue,
|
||||
HashValue,
|
||||
SetValue,
|
||||
ListValue,
|
||||
},
|
||||
setup() {
|
||||
const state = reactive({
|
||||
loading: false,
|
||||
redisList: [],
|
||||
tags: [],
|
||||
redisList: [] as any,
|
||||
dbList: [],
|
||||
query: {
|
||||
envId: 0,
|
||||
tagPath: null,
|
||||
},
|
||||
scanParam: {
|
||||
id: null,
|
||||
db: null,
|
||||
match: null,
|
||||
count: 10,
|
||||
cursor: {},
|
||||
},
|
||||
valueDialog: {
|
||||
visible: false,
|
||||
value: {},
|
||||
},
|
||||
dataEdit: {
|
||||
visible: false,
|
||||
title: '新增数据',
|
||||
@@ -126,30 +190,50 @@ export default defineComponent({
|
||||
timed: -1,
|
||||
key: '',
|
||||
},
|
||||
stringValue: '',
|
||||
hashValue: [{ key: '', value: '' }],
|
||||
setValue: [{ value: '' }],
|
||||
},
|
||||
hashValueDialog: {
|
||||
visible: false,
|
||||
},
|
||||
stringValueDialog: {
|
||||
visible: false,
|
||||
},
|
||||
setValueDialog: {
|
||||
visible: false,
|
||||
},
|
||||
listValueDialog: {
|
||||
visible: false,
|
||||
},
|
||||
keys: [],
|
||||
dbsize: 0,
|
||||
});
|
||||
|
||||
const searchRedis = async () => {
|
||||
notNull(state.query.envId, '请先选择项目环境');
|
||||
notBlank(state.query.tagPath, '请先选择标签');
|
||||
const res = await redisApi.redisList.request(state.query);
|
||||
state.redisList = res.list;
|
||||
};
|
||||
|
||||
const changeProjectEnv = (projectId: any, envId: any) => {
|
||||
const changeTag = (tagPath: string) => {
|
||||
clearRedis();
|
||||
if (envId != null) {
|
||||
state.query.envId = envId;
|
||||
if (tagPath != null) {
|
||||
searchRedis();
|
||||
}
|
||||
};
|
||||
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const changeRedis = (id: number) => {
|
||||
resetScanParam(id);
|
||||
state.scanParam.db = null;
|
||||
state.dbList = (state.redisList.find((x: any) => x.id == id) as any).db.split(',');
|
||||
state.keys = [];
|
||||
state.dbsize = 0;
|
||||
};
|
||||
|
||||
const changeDb = () => {
|
||||
resetScanParam(state.scanParam.id as any);
|
||||
state.keys = [];
|
||||
state.dbsize = 0;
|
||||
searchKey();
|
||||
@@ -158,10 +242,15 @@ export default defineComponent({
|
||||
const scan = async () => {
|
||||
isTrue(state.scanParam.id != null, '请先选择redis');
|
||||
notBlank(state.scanParam.count, 'count不能为空');
|
||||
isTrue(state.scanParam.count < 20001, 'count不能超过20000');
|
||||
|
||||
const match = state.scanParam.match;
|
||||
if (!match || (match as string).length < 4) {
|
||||
isTrue(state.scanParam.count <= 200, 'key为空或小于4字符时, count不能超过200');
|
||||
} else {
|
||||
isTrue(state.scanParam.count <= 20000, 'count不能超过20000');
|
||||
}
|
||||
|
||||
state.loading = true;
|
||||
|
||||
try {
|
||||
const res = await redisApi.scan.request(state.scanParam);
|
||||
state.keys = res.keys;
|
||||
@@ -181,6 +270,7 @@ export default defineComponent({
|
||||
state.redisList = [];
|
||||
state.scanParam.id = null;
|
||||
resetScanParam();
|
||||
state.scanParam.db = null;
|
||||
state.keys = [];
|
||||
state.dbsize = 0;
|
||||
};
|
||||
@@ -198,7 +288,7 @@ export default defineComponent({
|
||||
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.count = 4;
|
||||
}
|
||||
}
|
||||
state.scanParam.match = null;
|
||||
@@ -207,60 +297,47 @@ export default defineComponent({
|
||||
|
||||
const getValue = async (row: any) => {
|
||||
const type = row.type;
|
||||
const key = row.key;
|
||||
|
||||
let res: any;
|
||||
const reqParam = {
|
||||
key: row.key,
|
||||
id: state.scanParam.id,
|
||||
};
|
||||
switch (type) {
|
||||
case 'string':
|
||||
res = await redisApi.getStringValue.request(reqParam);
|
||||
break;
|
||||
case 'hash':
|
||||
res = await redisApi.getHashValue.request(reqParam);
|
||||
break;
|
||||
case 'set':
|
||||
res = await redisApi.getSetValue.request(reqParam);
|
||||
break;
|
||||
default:
|
||||
res = null;
|
||||
break;
|
||||
}
|
||||
notNull(res, '暂不支持该类型数据查看');
|
||||
|
||||
if (type == 'string') {
|
||||
state.dataEdit.stringValue = res;
|
||||
}
|
||||
if (type == 'set') {
|
||||
state.dataEdit.setValue = res.map((x: any) => {
|
||||
return {
|
||||
value: x,
|
||||
};
|
||||
});
|
||||
}
|
||||
if (type == 'hash') {
|
||||
const hash = [];
|
||||
//遍历key和value
|
||||
const keys = Object.keys(res);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
const value = res[key];
|
||||
hash.push({
|
||||
key,
|
||||
value,
|
||||
});
|
||||
}
|
||||
state.dataEdit.hashValue = hash;
|
||||
}
|
||||
|
||||
state.dataEdit.keyInfo.type = type;
|
||||
state.dataEdit.keyInfo.timed = row.ttl;
|
||||
state.dataEdit.keyInfo.key = key;
|
||||
state.dataEdit.keyInfo.key = row.key;
|
||||
state.dataEdit.operationType = 2;
|
||||
state.dataEdit.title = '修改数据';
|
||||
state.dataEdit.visible = true;
|
||||
state.dataEdit.title = '查看数据';
|
||||
|
||||
if (type == 'hash') {
|
||||
state.hashValueDialog.visible = true;
|
||||
} else if (type == 'string') {
|
||||
state.stringValueDialog.visible = true;
|
||||
} else if (type == 'set') {
|
||||
state.setValueDialog.visible = true;
|
||||
} else if (type == 'list') {
|
||||
state.listValueDialog.visible = true;
|
||||
} else {
|
||||
ElMessage.warning('暂不支持该类型');
|
||||
}
|
||||
};
|
||||
|
||||
const onAddData = (type: string) => {
|
||||
notNull(state.scanParam.id, '请先选择redis');
|
||||
state.dataEdit.operationType = 1;
|
||||
state.dataEdit.title = '新增数据';
|
||||
state.dataEdit.keyInfo.type = type;
|
||||
state.dataEdit.keyInfo.timed = -1;
|
||||
if (type == 'hash') {
|
||||
state.hashValueDialog.visible = true;
|
||||
} else if (type == 'string') {
|
||||
state.stringValueDialog.visible = true;
|
||||
} else if (type == 'set') {
|
||||
state.setValueDialog.visible = true;
|
||||
} else if (type == 'list') {
|
||||
state.listValueDialog.visible = true;
|
||||
} else {
|
||||
ElMessage.warning('暂不支持该类型');
|
||||
}
|
||||
};
|
||||
|
||||
const onCancelDataEdit = () => {
|
||||
state.dataEdit.keyInfo = {} as any;
|
||||
};
|
||||
|
||||
const del = (key: string) => {
|
||||
@@ -274,6 +351,7 @@ export default defineComponent({
|
||||
.request({
|
||||
key,
|
||||
id: state.scanParam.id,
|
||||
db: state.scanParam.db,
|
||||
})
|
||||
.then(() => {
|
||||
ElMessage.success('删除成功!');
|
||||
@@ -331,24 +409,12 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const onAddData = () => {
|
||||
notNull(state.scanParam.id, '请先选择redis');
|
||||
state.dataEdit.operationType = 1;
|
||||
state.dataEdit.title = '新增数据';
|
||||
state.dataEdit.visible = true;
|
||||
};
|
||||
|
||||
const onCancelDataEdit = () => {
|
||||
state.dataEdit.keyInfo = {} as any;
|
||||
state.dataEdit.stringValue = '';
|
||||
state.dataEdit.setValue = [];
|
||||
state.dataEdit.hashValue = [];
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
changeProjectEnv,
|
||||
getTags,
|
||||
changeTag,
|
||||
changeRedis,
|
||||
changeDb,
|
||||
clearRedis,
|
||||
searchKey,
|
||||
scan,
|
||||
|
||||
264
mayfly_go_web/src/views/ops/redis/HashValue.vue
Normal file
264
mayfly_go_web/src/views/ops/redis/HashValue.vue
Normal file
@@ -0,0 +1,264 @@
|
||||
<template>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" width="800px" :destroy-on-close="true">
|
||||
<el-form label-width="85px">
|
||||
<el-form-item prop="key" label="key:">
|
||||
<el-input :disabled="operationType == 2" v-model="key.key"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="timed" label="过期时间:">
|
||||
<el-input v-model.number="key.timed" type="number"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="dataType" label="数据类型:">
|
||||
<el-input v-model="key.type" disabled></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-row class="mt10">
|
||||
<el-form label-position="right" :inline="true">
|
||||
<el-form-item label="field" label-width="40px" v-if="operationType == 2">
|
||||
<el-input placeholder="支持*模糊field" style="width: 140px" v-model="scanParam.match" clearable size="small"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="count" v-if="operationType == 2">
|
||||
<el-input placeholder="count" style="width: 62px" v-model.number="scanParam.count" size="small"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button v-if="operationType == 2" @click="reHscan()" type="success" icon="search" plain size="small"></el-button>
|
||||
<el-button v-if="operationType == 2" @click="hscan()" icon="bottom" plain size="small">scan</el-button>
|
||||
<el-button @click="onAddHashValue" icon="plus" size="small" plain>添加</el-button>
|
||||
</el-form-item>
|
||||
<div v-if="operationType == 2" class="mt10" style="float: right">
|
||||
<span>fieldSize: {{ keySize }}</span>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-row>
|
||||
<el-table :data="hashValues" stripe style="width: 100%">
|
||||
<el-table-column prop="field" label="field" width>
|
||||
<template #default="scope">
|
||||
<el-input v-model="scope.row.field" clearable size="small"></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="value" label="value" min-width="200">
|
||||
<template #default="scope">
|
||||
<el-input v-model="scope.row.value" clearable type="textarea" :autosize="{ minRows: 2, maxRows: 10 }" size="small"></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="120">
|
||||
<template #default="scope">
|
||||
<el-button v-if="operationType == 2" type="success" @click="hset(scope.row)" icon="check" size="small" plain></el-button>
|
||||
<el-button type="danger" @click="hdel(scope.row.field, scope.$index)" icon="delete" size="small" plain></el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-form>
|
||||
<template #footer v-if="operationType == 1">
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()">取 消</el-button>
|
||||
<el-button @click="saveValue" type="primary" v-auth="'redis:data:save'">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, watch, toRefs } from 'vue';
|
||||
import { redisApi } from './api';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { isTrue, notEmpty } from '@/common/assert';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'HashValue',
|
||||
components: {},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
},
|
||||
// 操作类型,1:新增,2:修改
|
||||
operationType: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
redisId: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
db: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
keyInfo: {
|
||||
type: [Object],
|
||||
},
|
||||
hashValue: {
|
||||
type: [Array, Object],
|
||||
},
|
||||
},
|
||||
emits: ['valChange', 'cancel', 'update:visible'],
|
||||
setup(props: any, { emit }) {
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
operationType: 1,
|
||||
redisId: 0,
|
||||
db: 0,
|
||||
key: {
|
||||
key: '',
|
||||
type: 'hash',
|
||||
timed: -1,
|
||||
},
|
||||
scanParam: {
|
||||
key: '',
|
||||
id: 0,
|
||||
db: 0,
|
||||
cursor: 0,
|
||||
match: '',
|
||||
count: 10,
|
||||
},
|
||||
keySize: 0,
|
||||
hashValues: [
|
||||
{
|
||||
field: '',
|
||||
value: '',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const cancel = () => {
|
||||
emit('update:visible', false);
|
||||
emit('cancel');
|
||||
setTimeout(() => {
|
||||
state.hashValues = [];
|
||||
state.key = {} as any;
|
||||
}, 500);
|
||||
};
|
||||
|
||||
watch(props, async (newValue) => {
|
||||
const visible = newValue.visible;
|
||||
state.redisId = newValue.redisId;
|
||||
state.db = newValue.db;
|
||||
state.key = newValue.keyInfo;
|
||||
state.operationType = newValue.operationType;
|
||||
|
||||
if (visible && state.operationType == 2) {
|
||||
state.scanParam.id = props.redisId;
|
||||
state.scanParam.key = state.key.key;
|
||||
await reHscan();
|
||||
}
|
||||
|
||||
state.dialogVisible = visible;
|
||||
});
|
||||
|
||||
const reHscan = async () => {
|
||||
state.scanParam.id = state.redisId;
|
||||
state.scanParam.db = state.db;
|
||||
state.scanParam.cursor = 0;
|
||||
hscan();
|
||||
};
|
||||
|
||||
const hscan = async () => {
|
||||
const match = state.scanParam.match;
|
||||
if (!match || match == '' || match == '*') {
|
||||
if (state.scanParam.count > 100) {
|
||||
ElMessage.error('match为空或者*时, count不能超过100');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (state.scanParam.count > 1000) {
|
||||
ElMessage.error('count不能超过1000');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const scanRes = await redisApi.hscan.request(state.scanParam);
|
||||
state.scanParam.cursor = scanRes.cursor;
|
||||
state.keySize = scanRes.keySize;
|
||||
|
||||
const keys = scanRes.keys;
|
||||
const hashValue = [];
|
||||
const fieldCount = keys.length / 2;
|
||||
let nextFieldIndex = 0;
|
||||
for (let i = 0; i < fieldCount; i++) {
|
||||
hashValue.push({ field: keys[nextFieldIndex++], value: keys[nextFieldIndex++] });
|
||||
}
|
||||
state.hashValues = hashValue;
|
||||
};
|
||||
|
||||
const hdel = async (field: any, index: any) => {
|
||||
// 如果是新增操作,则直接数组移除即可
|
||||
if (state.operationType == 1) {
|
||||
state.hashValues.splice(index, 1);
|
||||
return;
|
||||
}
|
||||
await ElMessageBox.confirm(`确定删除[${field}]?`, '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
});
|
||||
await redisApi.hdel.request({
|
||||
id: state.redisId,
|
||||
db: state.db,
|
||||
key: state.key.key,
|
||||
field,
|
||||
});
|
||||
ElMessage.success('删除成功');
|
||||
reHscan();
|
||||
};
|
||||
|
||||
const hset = async (row: any) => {
|
||||
await redisApi.saveHashValue.request({
|
||||
id: state.redisId,
|
||||
db: state.db,
|
||||
key: state.key.key,
|
||||
timed: state.key.timed,
|
||||
value: [
|
||||
{
|
||||
field: row.field,
|
||||
value: row.value,
|
||||
},
|
||||
],
|
||||
});
|
||||
ElMessage.success('保存成功');
|
||||
};
|
||||
|
||||
const onAddHashValue = () => {
|
||||
state.hashValues.unshift({ field: '', value: '' });
|
||||
};
|
||||
|
||||
const saveValue = async () => {
|
||||
notEmpty(state.key.key, 'key不能为空');
|
||||
isTrue(state.hashValues.length > 0, 'hash内容不能为空');
|
||||
const sv = { value: state.hashValues, id: state.redisId, db: state.db };
|
||||
Object.assign(sv, state.key);
|
||||
await redisApi.saveHashValue.request(sv);
|
||||
ElMessage.success('保存成功');
|
||||
|
||||
cancel();
|
||||
emit('valChange');
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
reHscan,
|
||||
hscan,
|
||||
cancel,
|
||||
hdel,
|
||||
hset,
|
||||
onAddHashValue,
|
||||
saveValue,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
#string-value-text {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
position: relative;
|
||||
|
||||
.text-type-select {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
right: 10px;
|
||||
top: 10px;
|
||||
max-width: 70px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
213
mayfly_go_web/src/views/ops/redis/ListValue.vue
Normal file
213
mayfly_go_web/src/views/ops/redis/ListValue.vue
Normal file
@@ -0,0 +1,213 @@
|
||||
<template>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" width="800px" :destroy-on-close="true">
|
||||
<el-form label-width="85px">
|
||||
<el-form-item prop="key" label="key:">
|
||||
<el-input :disabled="operationType == 2" v-model="key.key"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="timed" label="过期时间:">
|
||||
<el-input v-model.number="key.timed" type="number"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="dataType" label="数据类型:">
|
||||
<el-input v-model="key.type" disabled></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<!-- <el-button @click="onAddListValue" icon="plus" size="small" plain class="mt10">添加</el-button> -->
|
||||
<div v-if="operationType == 2" class="mt10" style="float: left">
|
||||
<span>len: {{ len }}</span>
|
||||
</div>
|
||||
<el-table :data="value" stripe style="width: 100%">
|
||||
<el-table-column prop="value" label="value" min-width="200">
|
||||
<template #default="scope">
|
||||
<el-input v-model="scope.row.value" clearable type="textarea" :autosize="{ minRows: 2, maxRows: 10 }" size="small"></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="140">
|
||||
<template #default="scope">
|
||||
<el-button
|
||||
v-if="operationType == 2"
|
||||
type="success"
|
||||
@click="lset(scope.row, scope.$index)"
|
||||
icon="check"
|
||||
size="small"
|
||||
plain
|
||||
></el-button>
|
||||
<!-- <el-button type="danger" @click="set.value.splice(scope.$index, 1)" icon="delete" size="small" plain></el-button> -->
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-row style="margin-top: 20px" type="flex" justify="end">
|
||||
<el-pagination
|
||||
style="text-align: right"
|
||||
:total="len"
|
||||
layout="prev, pager, next, total"
|
||||
@current-change="handlePageChange"
|
||||
v-model:current-page="pageNum"
|
||||
:page-size="pageSize"
|
||||
></el-pagination>
|
||||
</el-row>
|
||||
</el-form>
|
||||
<!-- <template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()">取 消</el-button>
|
||||
<el-button @click="saveValue" type="primary" v-auth="'redis:data:save'">确 定</el-button>
|
||||
</div>
|
||||
</template> -->
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, watch, toRefs } from 'vue';
|
||||
import { redisApi } from './api';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { isTrue, notEmpty } from '@/common/assert';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'ListValue',
|
||||
components: {},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
},
|
||||
redisId: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
db: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
keyInfo: {
|
||||
type: [Object],
|
||||
},
|
||||
// 操作类型,1:新增,2:修改
|
||||
operationType: {
|
||||
type: [Number],
|
||||
},
|
||||
listValue: {
|
||||
type: [Array, Object],
|
||||
},
|
||||
},
|
||||
emits: ['valChange', 'cancel', 'update:visible'],
|
||||
setup(props: any, { emit }) {
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
operationType: 1,
|
||||
redisId: '',
|
||||
db: 0,
|
||||
key: {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
},
|
||||
value: [{ value: '' }],
|
||||
len: 0,
|
||||
start: 0,
|
||||
stop: 0,
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
});
|
||||
|
||||
const cancel = () => {
|
||||
emit('update:visible', false);
|
||||
emit('cancel');
|
||||
setTimeout(() => {
|
||||
state.key = {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
};
|
||||
state.value = [];
|
||||
}, 500);
|
||||
};
|
||||
|
||||
watch(props, async (newValue) => {
|
||||
state.dialogVisible = newValue.visible;
|
||||
state.key = newValue.key;
|
||||
state.redisId = newValue.redisId;
|
||||
state.db = newValue.db;
|
||||
state.key = newValue.keyInfo;
|
||||
state.operationType = newValue.operationType;
|
||||
// 如果是查看编辑操作,则获取值
|
||||
if (state.dialogVisible && state.operationType == 2) {
|
||||
getListValue();
|
||||
}
|
||||
});
|
||||
|
||||
const getListValue = async () => {
|
||||
const pageNum = state.pageNum;
|
||||
const pageSize = state.pageSize;
|
||||
const res = await redisApi.getListValue.request({
|
||||
id: state.redisId,
|
||||
db: state.db,
|
||||
key: state.key.key,
|
||||
start: (pageNum - 1) * pageSize,
|
||||
stop: pageNum * pageSize - 1,
|
||||
});
|
||||
state.len = res.len;
|
||||
state.value = res.list.map((x: any) => {
|
||||
return {
|
||||
value: x,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const lset = async (row: any, rowIndex: number) => {
|
||||
await redisApi.setListValue.request({
|
||||
id: state.redisId,
|
||||
db: state.db,
|
||||
key: state.key.key,
|
||||
index: (state.pageNum - 1) * state.pageSize + rowIndex,
|
||||
value: row.value,
|
||||
});
|
||||
ElMessage.success('数据保存成功');
|
||||
};
|
||||
|
||||
const saveValue = async () => {
|
||||
notEmpty(state.key.key, 'key不能为空');
|
||||
isTrue(state.value.length > 0, 'list内容不能为空');
|
||||
// const sv = { value: state.value.map((x) => x.value), id: state.redisId };
|
||||
// Object.assign(sv, state.key);
|
||||
// await redisApi.saveSetValue.request(sv);
|
||||
|
||||
ElMessage.success('数据保存成功');
|
||||
cancel();
|
||||
emit('valChange');
|
||||
};
|
||||
|
||||
const onAddListValue = () => {
|
||||
state.value.unshift({ value: '' });
|
||||
};
|
||||
|
||||
const handlePageChange = (curPage: number) => {
|
||||
state.pageNum = curPage;
|
||||
getListValue();
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
saveValue,
|
||||
handlePageChange,
|
||||
cancel,
|
||||
lset,
|
||||
onAddListValue,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
#string-value-text {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
position: relative;
|
||||
|
||||
.text-type-select {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
right: 10px;
|
||||
top: 10px;
|
||||
max-width: 70px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,27 +2,23 @@
|
||||
<div>
|
||||
<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="redisForm" :rules="rules" label-width="85px">
|
||||
<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>
|
||||
</el-select>
|
||||
<el-form-item prop="tagId" label="标签:" required>
|
||||
<tag-select v-model:tag-id="form.tagId" v-model:tag-path="form.tagPath" style="width: 100%" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="envId" label="环境:" required>
|
||||
<el-select @change="changeEnv" style="width: 100%" v-model="form.envId" placeholder="请选择环境">
|
||||
<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 prop="name" label="名称:" required>
|
||||
<el-input v-model.trim="form.name" placeholder="请输入redis名称" auto-complete="off"></el-input>
|
||||
</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-option label="sentinel" value="sentinel"> </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,集群模式用','分割"
|
||||
placeholder="请输入host:port;sentinel模式为: mastername=sentinelhost:port,若集群或哨兵需设多个节点可使用','分割"
|
||||
auto-complete="off"
|
||||
type="textarea"
|
||||
></el-input>
|
||||
@@ -34,10 +30,19 @@
|
||||
v-model.trim="form.password"
|
||||
placeholder="请输入密码, 修改操作可不填"
|
||||
autocomplete="new-password"
|
||||
></el-input>
|
||||
><template v-if="form.id && form.id != 0" #suffix>
|
||||
<el-popover @hide="pwd = ''" placement="right" title="原密码" :width="200" trigger="click" :content="pwd">
|
||||
<template #reference>
|
||||
<el-link @click="getPwd" :underline="false" type="primary" class="mr5">原密码</el-link>
|
||||
</template>
|
||||
</el-popover>
|
||||
</template></el-input
|
||||
>
|
||||
</el-form-item>
|
||||
<el-form-item prop="db" label="库号:" required>
|
||||
<el-input v-model.number="form.db" placeholder="请输入库号"></el-input>
|
||||
<el-select @change="changeDb" v-model="dbList" multiple placeholder="请选择可操作库号" style="width: 100%">
|
||||
<el-option v-for="db in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]" :key="db" :label="db" :value="db" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item prop="remark" label="备注:">
|
||||
<el-input v-model.trim="form.remark" auto-complete="off" type="textarea"></el-input>
|
||||
@@ -78,9 +83,13 @@ import { projectApi } from '../project/api.ts';
|
||||
import { machineApi } from '../machine/api.ts';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { RsaEncrypt } from '@/common/rsa';
|
||||
import TagSelect from '../component/TagSelect.vue';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'RedisEdit',
|
||||
components: {
|
||||
TagSelect,
|
||||
},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
@@ -104,10 +113,13 @@ export default defineComponent({
|
||||
sshTunnelMachineList: [],
|
||||
form: {
|
||||
id: null,
|
||||
tagId: null as any,
|
||||
tatPath: null as any,
|
||||
name: null,
|
||||
mode: 'standalone',
|
||||
host: null,
|
||||
host: '',
|
||||
password: null,
|
||||
db: '',
|
||||
project: null,
|
||||
projectId: null,
|
||||
envId: null,
|
||||
@@ -116,6 +128,8 @@ export default defineComponent({
|
||||
enableSshTunnel: null,
|
||||
sshTunnelMachineId: null,
|
||||
},
|
||||
dbList: [0],
|
||||
pwd: '',
|
||||
btnLoading: false,
|
||||
rules: {
|
||||
projectId: [
|
||||
@@ -142,14 +156,14 @@ export default defineComponent({
|
||||
db: [
|
||||
{
|
||||
required: true,
|
||||
message: '请输入库号',
|
||||
message: '请选择库号',
|
||||
trigger: ['change', 'blur'],
|
||||
},
|
||||
],
|
||||
mode: [
|
||||
{
|
||||
required: true,
|
||||
message: '请输入模式',
|
||||
message: '请选择模式',
|
||||
trigger: ['change', 'blur'],
|
||||
},
|
||||
],
|
||||
@@ -163,15 +177,27 @@ export default defineComponent({
|
||||
}
|
||||
state.projects = newValue.projects;
|
||||
if (newValue.redis) {
|
||||
getEnvs(newValue.redis.projectId);
|
||||
state.form = { ...newValue.redis };
|
||||
convertDb(state.form.db);
|
||||
} else {
|
||||
state.envs = [];
|
||||
state.form = { db: 0, enableSshTunnel: -1 } as any;
|
||||
state.form = { db: '0', enableSshTunnel: -1 } as any;
|
||||
state.dbList = [];
|
||||
}
|
||||
getSshTunnelMachines();
|
||||
});
|
||||
|
||||
const convertDb = (db: string) => {
|
||||
state.dbList = db.split(',').map((x) => Number.parseInt(x));
|
||||
};
|
||||
|
||||
/**
|
||||
* 改变表单中的数据库字段,方便表单错误提示。如全部删光,可提示请添加库号
|
||||
*/
|
||||
const changeDb = () => {
|
||||
state.form.db = state.dbList.length == 0 ? '' : state.dbList.join(',');
|
||||
};
|
||||
|
||||
const getSshTunnelMachines = async () => {
|
||||
if (state.form.enableSshTunnel == 1 && state.sshTunnelMachineList.length == 0) {
|
||||
const res = await machineApi.list.request({ pageNum: 1, pageSize: 100 });
|
||||
@@ -179,34 +205,18 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const getEnvs = async (projectId: any) => {
|
||||
state.envs = await projectApi.projectEnvs.request({ projectId });
|
||||
};
|
||||
|
||||
const changeProject = (projectId: number) => {
|
||||
for (let p of state.projects as any) {
|
||||
if (p.id == projectId) {
|
||||
state.form.project = p.name;
|
||||
}
|
||||
}
|
||||
state.form.envId = null;
|
||||
state.form.env = null;
|
||||
state.envs = [];
|
||||
getEnvs(projectId);
|
||||
};
|
||||
|
||||
const changeEnv = (envId: number) => {
|
||||
for (let p of state.envs as any) {
|
||||
if (p.id == envId) {
|
||||
state.form.env = p.name;
|
||||
}
|
||||
}
|
||||
const getPwd = async () => {
|
||||
state.pwd = await redisApi.getRedisPwd.request({ id: state.form.id });
|
||||
};
|
||||
|
||||
const btnOk = async () => {
|
||||
redisForm.value.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
const reqForm = { ...state.form };
|
||||
if (reqForm.mode == 'sentinel' && reqForm.host.split('=').length != 2) {
|
||||
ElMessage.error('sentinel模式host需为: mastername=sentinelhost:sentinelport模式');
|
||||
return;
|
||||
}
|
||||
reqForm.password = await RsaEncrypt(reqForm.password);
|
||||
redisApi.saveRedis.request(reqForm).then(() => {
|
||||
ElMessage.success('保存成功');
|
||||
@@ -233,9 +243,9 @@ export default defineComponent({
|
||||
return {
|
||||
...toRefs(state),
|
||||
redisForm,
|
||||
changeDb,
|
||||
getSshTunnelMachines,
|
||||
changeProject,
|
||||
changeEnv,
|
||||
getPwd,
|
||||
btnOk,
|
||||
cancel,
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<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-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 @focus="getTags" v-model="query.tagPath" placeholder="请选择标签" filterable clearable>
|
||||
<el-option v-for="item in tags" :key="item" :label="item" :value="item"> </el-option>
|
||||
</el-select>
|
||||
<el-button class="ml5" @click="search" type="success" icon="search"></el-button>
|
||||
</div>
|
||||
@@ -18,20 +18,26 @@
|
||||
</el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<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="tagPath" label="标签路径" min-width="150" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="name" 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="120" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="createTime" label="创建时间" min-width="160">
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
{{ dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<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-link v-if="scope.row.mode == 'standalone'" type="primary" @click="info(scope.row)" :underline="false">单机信息</el-link>
|
||||
<el-link
|
||||
v-if="scope.row.mode == 'standalone' || scope.row.mode == 'sentinel'"
|
||||
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
|
||||
>
|
||||
@@ -132,7 +138,7 @@
|
||||
|
||||
<redis-edit
|
||||
@val-change="valChange"
|
||||
:projects="projects"
|
||||
:tags="tags"
|
||||
:title="redisEditDialog.title"
|
||||
v-model:visible="redisEditDialog.visible"
|
||||
v-model:redis="redisEditDialog.data"
|
||||
@@ -145,8 +151,9 @@ import Info from './Info.vue';
|
||||
import { redisApi } from './api';
|
||||
import { toRefs, reactive, defineComponent, onMounted } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { projectApi } from '../project/api.ts';
|
||||
import { tagApi } from '../tag/api.ts';
|
||||
import RedisEdit from './RedisEdit.vue';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'RedisList',
|
||||
@@ -156,15 +163,15 @@ export default defineComponent({
|
||||
},
|
||||
setup() {
|
||||
const state = reactive({
|
||||
projects: [],
|
||||
tags: [],
|
||||
redisTable: [],
|
||||
total: 0,
|
||||
currentId: null,
|
||||
currentData: null,
|
||||
query: {
|
||||
tagPath: null,
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
prjectId: null,
|
||||
clusterId: null,
|
||||
},
|
||||
redisInfo: {
|
||||
@@ -202,7 +209,6 @@ export default defineComponent({
|
||||
|
||||
onMounted(async () => {
|
||||
search();
|
||||
state.projects = await projectApi.accountProjects.request(null);
|
||||
});
|
||||
|
||||
const handlePageChange = (curPage: number) => {
|
||||
@@ -258,7 +264,11 @@ export default defineComponent({
|
||||
state.total = res.total;
|
||||
};
|
||||
|
||||
const editRedis = (isAdd = false) => {
|
||||
const getTags = async () => {
|
||||
state.tags = await tagApi.getAccountTags.request(null);
|
||||
};
|
||||
|
||||
const editRedis = async (isAdd = false) => {
|
||||
if (isAdd) {
|
||||
state.redisEditDialog.data = null;
|
||||
state.redisEditDialog.title = '新增redis';
|
||||
@@ -277,6 +287,8 @@ export default defineComponent({
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
dateFormat,
|
||||
getTags,
|
||||
search,
|
||||
handlePageChange,
|
||||
choose,
|
||||
|
||||
164
mayfly_go_web/src/views/ops/redis/SetValue.vue
Normal file
164
mayfly_go_web/src/views/ops/redis/SetValue.vue
Normal file
@@ -0,0 +1,164 @@
|
||||
<template>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" width="800px" :destroy-on-close="true">
|
||||
<el-form label-width="85px">
|
||||
<el-form-item prop="key" label="key:">
|
||||
<el-input :disabled="operationType == 2" v-model="key.key"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="timed" label="过期时间:">
|
||||
<el-input v-model.number="key.timed" type="number"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="dataType" label="数据类型:">
|
||||
<el-input v-model="key.type" disabled></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-button @click="onAddSetValue" icon="plus" size="small" plain class="mt10">添加</el-button>
|
||||
<el-table :data="value" stripe style="width: 100%">
|
||||
<el-table-column prop="value" label="value" min-width="200">
|
||||
<template #default="scope">
|
||||
<el-input v-model="scope.row.value" clearable type="textarea" :autosize="{ minRows: 2, maxRows: 10 }" size="small"></el-input>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90">
|
||||
<template #default="scope">
|
||||
<el-button type="danger" @click="value.splice(scope.$index, 1)" icon="delete" size="small" plain>删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()">取 消</el-button>
|
||||
<el-button @click="saveValue" type="primary" v-auth="'redis:data:save'">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, watch, toRefs } from 'vue';
|
||||
import { redisApi } from './api';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { isTrue, notEmpty } from '@/common/assert';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'SetValue',
|
||||
components: {},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
},
|
||||
redisId: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
db: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
keyInfo: {
|
||||
type: [Object],
|
||||
},
|
||||
// 操作类型,1:新增,2:修改
|
||||
operationType: {
|
||||
type: [Number],
|
||||
},
|
||||
setValue: {
|
||||
type: [Array, Object],
|
||||
},
|
||||
},
|
||||
emits: ['valChange', 'cancel', 'update:visible'],
|
||||
setup(props: any, { emit }) {
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
operationType: 1,
|
||||
redisId: '',
|
||||
db: 0,
|
||||
key: {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
},
|
||||
value: [{ value: '' }],
|
||||
});
|
||||
|
||||
const cancel = () => {
|
||||
emit('update:visible', false);
|
||||
emit('cancel');
|
||||
setTimeout(() => {
|
||||
state.key = {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
};
|
||||
state.value = [];
|
||||
}, 500);
|
||||
};
|
||||
|
||||
watch(props, async (newValue) => {
|
||||
state.dialogVisible = newValue.visible;
|
||||
state.key = newValue.key;
|
||||
state.redisId = newValue.redisId;
|
||||
state.db = newValue.db;
|
||||
state.key = newValue.keyInfo;
|
||||
state.operationType = newValue.operationType;
|
||||
// 如果是查看编辑操作,则获取值
|
||||
if (state.dialogVisible && state.operationType == 2) {
|
||||
getSetValue();
|
||||
}
|
||||
});
|
||||
|
||||
const getSetValue = async () => {
|
||||
const res = await redisApi.getSetValue.request({
|
||||
id: state.redisId,
|
||||
db: state.db,
|
||||
key: state.key.key,
|
||||
});
|
||||
state.value = res.map((x: any) => {
|
||||
return {
|
||||
value: x,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const saveValue = async () => {
|
||||
notEmpty(state.key.key, 'key不能为空');
|
||||
isTrue(state.value.length > 0, 'set内容不能为空');
|
||||
const sv = { value: state.value.map((x) => x.value), id: state.redisId, db: state.db };
|
||||
Object.assign(sv, state.key);
|
||||
await redisApi.saveSetValue.request(sv);
|
||||
|
||||
ElMessage.success('数据保存成功');
|
||||
cancel();
|
||||
emit('valChange');
|
||||
};
|
||||
|
||||
const onAddSetValue = () => {
|
||||
state.value.unshift({ value: '' });
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
saveValue,
|
||||
cancel,
|
||||
onAddSetValue,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
#string-value-text {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
position: relative;
|
||||
|
||||
.text-type-select {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
right: 10px;
|
||||
top: 10px;
|
||||
max-width: 70px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
183
mayfly_go_web/src/views/ops/redis/StringValue.vue
Normal file
183
mayfly_go_web/src/views/ops/redis/StringValue.vue
Normal file
@@ -0,0 +1,183 @@
|
||||
<template>
|
||||
<el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" width="800px" :destroy-on-close="true">
|
||||
<el-form label-width="85px">
|
||||
<el-form-item prop="key" label="key:">
|
||||
<el-input :disabled="operationType == 2" v-model="key.key"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="timed" label="过期时间:">
|
||||
<el-input v-model.number="key.timed" type="number"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="dataType" label="数据类型:">
|
||||
<el-input v-model="key.type" disabled></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<div id="string-value-text" style="width: 100%">
|
||||
<el-input class="json-text" v-model="string.value" type="textarea" :autosize="{ minRows: 10, maxRows: 20 }"></el-input>
|
||||
<el-select class="text-type-select" @change="onChangeTextType" v-model="string.type">
|
||||
<el-option key="text" label="text" value="text"> </el-option>
|
||||
<el-option key="json" label="json" value="json"> </el-option>
|
||||
</el-select>
|
||||
</div>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()">取 消</el-button>
|
||||
<el-button @click="saveValue" type="primary" v-auth="'redis:data:save'">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, watch, toRefs } from 'vue';
|
||||
import { redisApi } from './api';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { notEmpty } from '@/common/assert';
|
||||
import { formatJsonString } from '@/common/utils/format';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'StringValue',
|
||||
components: {},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
},
|
||||
redisId: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
db: {
|
||||
type: [Number],
|
||||
require: true,
|
||||
},
|
||||
keyInfo: {
|
||||
type: [Object],
|
||||
},
|
||||
// 操作类型,1:新增,2:修改
|
||||
operationType: {
|
||||
type: [Number],
|
||||
},
|
||||
},
|
||||
emits: ['valChange', 'cancel', 'update:visible'],
|
||||
setup(props: any, { emit }) {
|
||||
const state = reactive({
|
||||
dialogVisible: false,
|
||||
operationType: 1,
|
||||
redisId: '',
|
||||
db: 0,
|
||||
key: {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
},
|
||||
string: {
|
||||
type: 'text',
|
||||
value: '',
|
||||
},
|
||||
});
|
||||
|
||||
const cancel = () => {
|
||||
emit('update:visible', false);
|
||||
emit('cancel');
|
||||
setTimeout(() => {
|
||||
state.key = {
|
||||
key: '',
|
||||
type: 'string',
|
||||
timed: -1,
|
||||
};
|
||||
state.string.value = '';
|
||||
state.string.type = 'text';
|
||||
}, 500);
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(val) => {
|
||||
state.dialogVisible = val;
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.redisId,
|
||||
(val) => {
|
||||
state.redisId = val;
|
||||
}
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.db,
|
||||
(val) => {
|
||||
state.db = val;
|
||||
}
|
||||
);
|
||||
|
||||
watch(props, async (newValue) => {
|
||||
state.dialogVisible = newValue.visible;
|
||||
state.key = newValue.key;
|
||||
state.redisId = newValue.redisId;
|
||||
state.db = newValue.db;
|
||||
state.key = newValue.keyInfo;
|
||||
state.operationType = newValue.operationType;
|
||||
// 如果是查看编辑操作,则获取值
|
||||
if (state.dialogVisible && state.operationType == 2) {
|
||||
getStringValue();
|
||||
}
|
||||
});
|
||||
|
||||
const getStringValue = async () => {
|
||||
state.string.value = await redisApi.getStringValue.request({
|
||||
id: state.redisId,
|
||||
db: state.db,
|
||||
key: state.key.key,
|
||||
});
|
||||
};
|
||||
|
||||
const saveValue = async () => {
|
||||
notEmpty(state.key.key, 'key不能为空');
|
||||
|
||||
notEmpty(state.string.value, 'value不能为空');
|
||||
const sv = { value: formatJsonString(state.string.value, true), id: state.redisId, db: state.db };
|
||||
Object.assign(sv, state.key);
|
||||
await redisApi.saveStringValue.request(sv);
|
||||
ElMessage.success('数据保存成功');
|
||||
cancel();
|
||||
emit('valChange');
|
||||
};
|
||||
|
||||
// 更改文本类型
|
||||
const onChangeTextType = (val: string) => {
|
||||
if (val == 'json') {
|
||||
state.string.value = formatJsonString(state.string.value, false);
|
||||
return;
|
||||
}
|
||||
if (val == 'text') {
|
||||
state.string.value = formatJsonString(state.string.value, true);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
saveValue,
|
||||
cancel,
|
||||
onChangeTextType,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
#string-value-text {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
position: relative;
|
||||
|
||||
.text-type-select {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
right: 10px;
|
||||
top: 10px;
|
||||
max-width: 70px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,18 +2,25 @@ import Api from '@/common/Api';
|
||||
|
||||
export const redisApi = {
|
||||
redisList : Api.create("/redis", 'get'),
|
||||
getRedisPwd: Api.create("/redis/{id}/pwd", '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", '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'),
|
||||
saveHashValue: Api.create("/redis/{id}/hash-value", 'post'),
|
||||
getSetValue: Api.create("/redis/{id}/set-value", 'get'),
|
||||
saveSetValue: Api.create("/redis/{id}/set-value", 'post'),
|
||||
del: Api.create("/redis/{id}/scan/{cursor}/{count}", 'delete'),
|
||||
delKey: Api.create("/redis/{id}/key", 'delete'),
|
||||
scan: Api.create("/redis/{id}/{db}/scan", 'post'),
|
||||
getStringValue: Api.create("/redis/{id}/{db}/string-value", 'get'),
|
||||
saveStringValue: Api.create("/redis/{id}/{db}/string-value", 'post'),
|
||||
getHashValue: Api.create("/redis/{id}/{db}/hash-value", 'get'),
|
||||
hscan: Api.create("/redis/{id}/{db}/hscan", 'get'),
|
||||
hget: Api.create("/redis/{id}/{db}/hget", 'get'),
|
||||
hdel: Api.create("/redis/{id}/{db}/hdel", 'delete'),
|
||||
saveHashValue: Api.create("/redis/{id}/{db}/hash-value", 'post'),
|
||||
getSetValue: Api.create("/redis/{id}/{db}/set-value", 'get'),
|
||||
saveSetValue: Api.create("/redis/{id}/{db}/set-value", 'post'),
|
||||
del: Api.create("/redis/{id}/{db}/scan/{cursor}/{count}", 'delete'),
|
||||
delKey: Api.create("/redis/{id}/{db}/key", 'delete'),
|
||||
getListValue: Api.create("/redis/{id}/{db}/list-value", 'get'),
|
||||
saveListValue: Api.create("/redis/{id}/{db}/list-value", 'post'),
|
||||
setListValue: Api.create("/redis/{id}/{db}/list-value/lset", 'post'),
|
||||
}
|
||||
300
mayfly_go_web/src/views/ops/tag/TagTreeList.vue
Normal file
300
mayfly_go_web/src/views/ops/tag/TagTreeList.vue
Normal file
@@ -0,0 +1,300 @@
|
||||
<template>
|
||||
<div class="menu">
|
||||
<div class="toolbar">
|
||||
<el-button v-auth="'tag:save'" type="primary" icon="plus" @click="showSaveTabDialog(null)">添加</el-button>
|
||||
<div style="float: right">
|
||||
<el-tooltip effect="dark" placement="top">
|
||||
<template #content>
|
||||
1. 用于将资产进行归类
|
||||
<br />2. 可在团队管理中进行分配,用于资源隔离
|
||||
<br />3. 父标签可访问及操作所有子标签关联的资源
|
||||
</template>
|
||||
<span>标签作用<el-icon><question-filled /></el-icon></span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<el-tree
|
||||
class="none-select"
|
||||
:indent="38"
|
||||
node-key="id"
|
||||
:props="props"
|
||||
:data="data"
|
||||
@node-expand="handleNodeExpand"
|
||||
@node-collapse="handleNodeCollapse"
|
||||
:default-expanded-keys="defaultExpandedKeys"
|
||||
:expand-on-click-node="false"
|
||||
>
|
||||
<template #default="{ data }">
|
||||
<span class="custom-tree-node">
|
||||
<span style="font-size: 13px">
|
||||
{{ data.code }}
|
||||
<span style="color: #3c8dbc">【</span>
|
||||
{{ data.name }}
|
||||
<span style="color: #3c8dbc">】</span>
|
||||
<el-tag v-if="data.children !== null" size="small">{{ data.children.length }}</el-tag>
|
||||
</span>
|
||||
|
||||
<el-link @click.prevent="info(data)" style="margin-left: 25px" icon="view" type="info" :underline="false" />
|
||||
|
||||
<el-link v-auth="'tag:save'" @click.prevent="showEditTagDialog(data)" class="ml5" type="primary" icon="edit" :underline="false" />
|
||||
|
||||
<el-link
|
||||
v-auth="'tag:save'"
|
||||
@click.prevent="showSaveTabDialog(data)"
|
||||
icon="circle-plus"
|
||||
:underline="false"
|
||||
type="success"
|
||||
class="ml5"
|
||||
/>
|
||||
|
||||
<!-- <el-link
|
||||
v-auth="'resource:changeStatus'"
|
||||
@click.prevent="changeStatus(data, -1)"
|
||||
v-if="data.status === 1 && data.type === enums.ResourceTypeEnum.PERMISSION.value"
|
||||
icon="circle-close"
|
||||
:underline="false"
|
||||
type="warning"
|
||||
class="ml5"
|
||||
/>
|
||||
|
||||
<el-link
|
||||
v-auth="'resource:changeStatus'"
|
||||
@click.prevent="changeStatus(data, 1)"
|
||||
v-if="data.status === -1 && data.type === enums.ResourceTypeEnum.PERMISSION.value"
|
||||
type="success"
|
||||
icon="circle-check"
|
||||
:underline="false"
|
||||
plain
|
||||
class="ml5"
|
||||
/> -->
|
||||
|
||||
<el-link
|
||||
v-auth="'tag:del'"
|
||||
@click.prevent="deleteTag(data)"
|
||||
v-if="data.children == null"
|
||||
type="danger"
|
||||
icon="delete"
|
||||
:underline="false"
|
||||
plain
|
||||
class="ml5"
|
||||
/>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
|
||||
<el-dialog width="500px" :title="saveTabDialog.title" :before-close="cancelSaveTag" v-model="saveTabDialog.visible">
|
||||
<el-form ref="tagForm" :rules="rules" :model="saveTabDialog.form" label-width="70px">
|
||||
<el-form-item prop="code" label="标识:" required>
|
||||
<el-input :disabled="saveTabDialog.form.id ? true : false" v-model="saveTabDialog.form.code" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="name" label="名称:" required>
|
||||
<el-input v-model="saveTabDialog.form.name" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注:">
|
||||
<el-input v-model="saveTabDialog.form.remark" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancelSaveTag()">取 消</el-button>
|
||||
<el-button @click="saveTag" type="primary">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="infoDialog.visible">
|
||||
<el-descriptions title="节点信息" :column="2" border>
|
||||
<el-descriptions-item label="code">{{ infoDialog.data.code }}</el-descriptions-item>
|
||||
<el-descriptions-item label="code路径">{{ infoDialog.data.codePath }}</el-descriptions-item>
|
||||
<el-descriptions-item label="名称">{{ infoDialog.data.name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="备注">{{ infoDialog.data.remark }}</el-descriptions-item>
|
||||
|
||||
<el-descriptions-item label="创建者">{{ infoDialog.data.creator }}</el-descriptions-item>
|
||||
<el-descriptions-item label="创建时间">{{ dateFormat(infoDialog.data.createTime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="修改者">{{ infoDialog.data.modifier }}</el-descriptions-item>
|
||||
<el-descriptions-item label="更新时间">{{ dateFormat(infoDialog.data.updateTime) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, ref, reactive, onMounted, defineComponent } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { tagApi } from './api';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'TagTreeList',
|
||||
components: {},
|
||||
setup() {
|
||||
const tagForm: any = ref(null);
|
||||
const state = reactive({
|
||||
saveTabDialog: {
|
||||
title: '新增标签',
|
||||
visible: false,
|
||||
form: { id: 0, pid: 0, code: '', name: '', remark: '' },
|
||||
},
|
||||
//资源信息弹出框对象
|
||||
infoDialog: {
|
||||
title: '',
|
||||
visible: false,
|
||||
// 资源类型选择是否选
|
||||
data: null as any,
|
||||
},
|
||||
data: [],
|
||||
props: {
|
||||
label: 'name',
|
||||
children: 'children',
|
||||
},
|
||||
// 展开的节点
|
||||
defaultExpandedKeys: [] as any[],
|
||||
rules: {
|
||||
code: [
|
||||
{ required: true, message: '标识符不能为空', trigger: 'blur' },
|
||||
// {
|
||||
// pattern: /^\w+$/g,
|
||||
// message: '标识符只能为空数字字母下划线等',
|
||||
// trigger: 'blur',
|
||||
// },
|
||||
],
|
||||
name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
|
||||
},
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
search();
|
||||
});
|
||||
|
||||
const search = async () => {
|
||||
let res = await tagApi.getTagTrees.request(null);
|
||||
state.data = res;
|
||||
};
|
||||
|
||||
const info = async (data: any) => {
|
||||
state.infoDialog.data = data;
|
||||
state.infoDialog.visible = true;
|
||||
};
|
||||
|
||||
const showSaveTabDialog = (data: any) => {
|
||||
if (data) {
|
||||
state.saveTabDialog.form.pid = data.id;
|
||||
state.saveTabDialog.title = `新增 [${data.codePath}] 子标签信息`;
|
||||
} else {
|
||||
state.saveTabDialog.title = '新增根标签信息';
|
||||
}
|
||||
state.saveTabDialog.visible = true;
|
||||
};
|
||||
|
||||
const showEditTagDialog = (data: any) => {
|
||||
state.saveTabDialog.form.id = data.id;
|
||||
state.saveTabDialog.form.code = data.code;
|
||||
state.saveTabDialog.form.name = data.name;
|
||||
state.saveTabDialog.form.remark = data.remark;
|
||||
state.saveTabDialog.title = `修改 [${data.codePath}] 信息`;
|
||||
state.saveTabDialog.visible = true;
|
||||
};
|
||||
|
||||
const saveTag = async () => {
|
||||
tagForm.value.validate(async (valid: any) => {
|
||||
if (valid) {
|
||||
const form = state.saveTabDialog.form;
|
||||
await tagApi.saveTagTree.request(form);
|
||||
ElMessage.success('保存成功');
|
||||
search();
|
||||
cancelSaveTag();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const cancelSaveTag = () => {
|
||||
state.saveTabDialog.visible = false;
|
||||
state.saveTabDialog.form = {} as any;
|
||||
tagForm.value.resetFields();
|
||||
};
|
||||
|
||||
const deleteTag = (data: any) => {
|
||||
ElMessageBox.confirm(`此操作将删除 [${data.codePath}], 是否继续?`, '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(async () => {
|
||||
await tagApi.delTagTree.request({ id: data.id });
|
||||
ElMessage.success('删除成功!');
|
||||
search();
|
||||
});
|
||||
};
|
||||
|
||||
// const changeStatus = async (data: any, status: any) => {
|
||||
// await resourceApi.changeStatus.request({
|
||||
// id: data.id,
|
||||
// status: status,
|
||||
// });
|
||||
// data.status = status;
|
||||
// ElMessage.success((status === 1 ? '启用' : '禁用') + '成功!');
|
||||
// };
|
||||
|
||||
// 节点被展开时触发的事件
|
||||
const handleNodeExpand = (data: any, node: any) => {
|
||||
const id: any = node.data.id;
|
||||
if (!state.defaultExpandedKeys.includes(id)) {
|
||||
state.defaultExpandedKeys.push(id);
|
||||
}
|
||||
};
|
||||
|
||||
// 关闭节点
|
||||
const handleNodeCollapse = (data: any, node: any) => {
|
||||
removeDeafultExpandId(node.data.id);
|
||||
|
||||
let childNodes = node.childNodes;
|
||||
for (let cn of childNodes) {
|
||||
if (cn.expanded) {
|
||||
removeDeafultExpandId(cn.data.id);
|
||||
}
|
||||
// 递归删除展开的子节点节点id
|
||||
handleNodeCollapse(data, cn);
|
||||
}
|
||||
};
|
||||
|
||||
const removeDeafultExpandId = (id: any) => {
|
||||
let index = state.defaultExpandedKeys.indexOf(id);
|
||||
if (index > -1) {
|
||||
state.defaultExpandedKeys.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
dateFormat,
|
||||
tagForm,
|
||||
info,
|
||||
saveTag,
|
||||
showSaveTabDialog,
|
||||
showEditTagDialog,
|
||||
cancelSaveTag,
|
||||
deleteTag,
|
||||
handleNodeExpand,
|
||||
handleNodeCollapse,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
.menu {
|
||||
height: 100%;
|
||||
.el-tree-node__content {
|
||||
height: 40px;
|
||||
line-height: 40px;
|
||||
}
|
||||
}
|
||||
|
||||
.none-select {
|
||||
moz-user-select: -moz-none;
|
||||
-moz-user-select: none;
|
||||
-o-user-select: none;
|
||||
-khtml-user-select: none;
|
||||
-webkit-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
</style>
|
||||
440
mayfly_go_web/src/views/ops/tag/TeamList.vue
Executable file
440
mayfly_go_web/src/views/ops/tag/TeamList.vue
Executable file
@@ -0,0 +1,440 @@
|
||||
<template>
|
||||
<div class="role-list">
|
||||
<el-card>
|
||||
<el-button v-auth="'team:save'" type="primary" icon="plus" @click="showSaveTeamDialog(false)">添加</el-button>
|
||||
<el-button v-auth="'team:save'" :disabled="chooseId == null" @click="showSaveTeamDialog(chooseData)" type="primary" icon="edit"
|
||||
>编辑</el-button
|
||||
>
|
||||
<el-button v-auth="'team:del'" :disabled="chooseId == null" @click="deleteTeam(chooseData)" type="danger" icon="delete">删除</el-button>
|
||||
|
||||
<div style="float: right">
|
||||
<el-input placeholder="请输入团队名称" class="mr2" style="width: 200px" v-model="query.name" @clear="search" clearable></el-input>
|
||||
<el-button @click="search" type="success" icon="search"></el-button>
|
||||
</div>
|
||||
<el-table :data="data" @current-change="choose" ref="table" style="width: 100%">
|
||||
<el-table-column label="选择" width="55px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
</el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="name" label="团队名称"></el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="160px" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="createTime" label="创建时间">
|
||||
<template #default="scope">
|
||||
{{ dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="creator" label="创建者"> </el-table-column>
|
||||
<el-table-column label="操作" min-width="80px">
|
||||
<template #default="scope">
|
||||
<el-link @click.prevent="showMembers(scope.row)" :underline="false" type="primary">成员</el-link>
|
||||
<el-divider direction="vertical" border-style="dashed" />
|
||||
<el-link @click.prevent="showTags(scope.row)" :underline="false" type="success">标签</el-link>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-row style="margin-top: 20px" type="flex" justify="end">
|
||||
<el-pagination
|
||||
style="text-align: right"
|
||||
@current-change="handlePageChange"
|
||||
:total="total"
|
||||
layout="prev, pager, next, total, jumper"
|
||||
v-model:current-page="query.pageNum"
|
||||
:page-size="query.pageSize"
|
||||
></el-pagination>
|
||||
</el-row>
|
||||
</el-card>
|
||||
|
||||
<el-dialog width="400px" title="团队编辑" :before-close="cancelSaveTeam" v-model="addTeamDialog.visible">
|
||||
<el-form ref="teamForm" :model="addTeamDialog.form" label-width="70px">
|
||||
<el-form-item prop="name" label="团队名:" required>
|
||||
<el-input v-model="addTeamDialog.form.name" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注:">
|
||||
<el-input v-model="addTeamDialog.form.remark" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancelSaveTeam()">取 消</el-button>
|
||||
<el-button @click="saveTeam" type="primary">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog width="500px" :title="showTagDialog.title" :before-close="closeTagDialog" v-model="showTagDialog.visible">
|
||||
<el-form label-width="70px">
|
||||
<el-form-item prop="project" label="标签:">
|
||||
<el-tree-select
|
||||
ref="tagTreeRef"
|
||||
style="width: 100%"
|
||||
v-model="showTagDialog.tagTreeTeams"
|
||||
:data="showTagDialog.tags"
|
||||
:default-expanded-keys="showTagDialog.tagTreeTeams"
|
||||
multiple
|
||||
:render-after-expand="true"
|
||||
show-checkbox
|
||||
check-strictly
|
||||
node-key="id"
|
||||
:props="showTagDialog.props"
|
||||
@check="tagTreeNodeCheck"
|
||||
>
|
||||
<template #default="{ data }">
|
||||
<span class="custom-tree-node">
|
||||
<span style="font-size: 13px">
|
||||
{{ data.code }}
|
||||
<span style="color: #3c8dbc">【</span>
|
||||
{{ data.name }}
|
||||
<span style="color: #3c8dbc">】</span>
|
||||
<el-tag v-if="data.children !== null" size="small">{{ data.children.length }}</el-tag>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="closeTagDialog()">取 消</el-button>
|
||||
<el-button v-auth="'team:tag:save'" @click="saveTags()" type="primary">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog width="600px" :title="showMemDialog.title" v-model="showMemDialog.visible">
|
||||
<div class="toolbar">
|
||||
<el-button v-auth="'team:member:save'" @click="showAddMemberDialog()" type="primary" icon="plus">添加</el-button>
|
||||
<el-button v-auth="'team:member:del'" @click="deleteMember" :disabled="showMemDialog.chooseId == null" type="danger" icon="delete">移除</el-button>
|
||||
</div>
|
||||
<el-table @current-change="chooseMember" border :data="showMemDialog.members.list">
|
||||
<el-table-column label="选择" width="50px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="showMemDialog.chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
</el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column property="username" label="账号" width="135"></el-table-column>
|
||||
<el-table-column property="createTime" label="加入时间">
|
||||
<template #default="scope">
|
||||
{{ dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column property="creator" label="分配者" width="135"></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
@current-change="setMemebers"
|
||||
style="text-align: center"
|
||||
background
|
||||
layout="prev, pager, next, total, jumper"
|
||||
:total="showMemDialog.members.total"
|
||||
v-model:current-page="showMemDialog.query.pageNum"
|
||||
:page-size="showMemDialog.query.pageSize"
|
||||
/>
|
||||
|
||||
<el-dialog width="400px" title="添加成员" :before-close="cancelAddMember" v-model="showMemDialog.addVisible">
|
||||
<el-form :model="showMemDialog.memForm" label-width="70px">
|
||||
<el-form-item label="账号:">
|
||||
<el-select
|
||||
style="width: 100%"
|
||||
remote
|
||||
:remote-method="getAccount"
|
||||
v-model="showMemDialog.memForm.accountId"
|
||||
filterable
|
||||
placeholder="请输入账号模糊搜索并选择"
|
||||
>
|
||||
<el-option v-for="item in showMemDialog.accounts" :key="item.id" :label="item.username" :value="item.id"> </el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancelAddMember()">取 消</el-button>
|
||||
<el-button @click="addMember" type="primary">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { ref, toRefs, reactive, onMounted, defineComponent } from 'vue';
|
||||
import { tagApi } from './api';
|
||||
import { accountApi } from '../../system/api';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
import { notBlank } from '@/common/assert';
|
||||
export default defineComponent({
|
||||
name: 'TeamList',
|
||||
components: {},
|
||||
setup() {
|
||||
const teamForm: any = ref(null);
|
||||
const tagTreeRef: any = ref(null);
|
||||
const state = reactive({
|
||||
dialogFormVisible: false,
|
||||
currentEditPermissions: false,
|
||||
addTeamDialog: {
|
||||
title: '新增团队',
|
||||
visible: false,
|
||||
form: { id: 0, name: '', remark: '' },
|
||||
},
|
||||
query: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
name: null,
|
||||
},
|
||||
total: 0,
|
||||
data: [],
|
||||
chooseId: 0,
|
||||
chooseData: null,
|
||||
showMemDialog: {
|
||||
visible: false,
|
||||
chooseId: 0,
|
||||
chooseData: null,
|
||||
query: {
|
||||
pageSize: 8,
|
||||
pageNum: 1,
|
||||
teamId: null,
|
||||
},
|
||||
members: {
|
||||
list: [],
|
||||
total: null,
|
||||
},
|
||||
title: '',
|
||||
addVisible: false,
|
||||
memForm: {
|
||||
accountId: null as any,
|
||||
teamId: 0,
|
||||
},
|
||||
accounts: Array(),
|
||||
},
|
||||
showTagDialog: {
|
||||
title: '项目信息',
|
||||
visible: false,
|
||||
tags: [],
|
||||
teamId: 0,
|
||||
tagTreeTeams: [] as any,
|
||||
props: {
|
||||
value: 'id',
|
||||
label: 'codePath',
|
||||
children: 'children',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
search();
|
||||
});
|
||||
|
||||
const search = async () => {
|
||||
let res = await tagApi.getTeams.request(state.query);
|
||||
state.data = res.list;
|
||||
state.total = res.total;
|
||||
};
|
||||
|
||||
const handlePageChange = (curPage: number) => {
|
||||
state.query.pageNum = curPage;
|
||||
search();
|
||||
};
|
||||
|
||||
const choose = (item: any) => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
state.chooseId = item.id;
|
||||
state.chooseData = item;
|
||||
};
|
||||
|
||||
const showSaveTeamDialog = (data: any) => {
|
||||
if (data) {
|
||||
state.addTeamDialog.form.id = data.id;
|
||||
state.addTeamDialog.form.name = data.name;
|
||||
state.addTeamDialog.form.remark = data.remark;
|
||||
state.addTeamDialog.title = `修改 [${data.codePath}] 信息`;
|
||||
}
|
||||
state.addTeamDialog.visible = true;
|
||||
};
|
||||
|
||||
const saveTeam = async () => {
|
||||
teamForm.value.validate(async (valid: any) => {
|
||||
if (valid) {
|
||||
const form = state.addTeamDialog.form;
|
||||
await tagApi.saveTeam.request(form);
|
||||
ElMessage.success('保存成功');
|
||||
search();
|
||||
cancelSaveTeam();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const cancelSaveTeam = () => {
|
||||
state.addTeamDialog.visible = false;
|
||||
state.addTeamDialog.form = {} as any;
|
||||
teamForm.value.resetFields();
|
||||
};
|
||||
|
||||
const deleteTeam = (data: any) => {
|
||||
ElMessageBox.confirm(`此操作将删除 [${data.name}], 是否继续?`, '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(async () => {
|
||||
await tagApi.delTeam.request({ id: data.id });
|
||||
ElMessage.success('删除成功!');
|
||||
search();
|
||||
});
|
||||
};
|
||||
|
||||
/********** 团队成员相关 ***********/
|
||||
|
||||
const showMembers = async (team: any) => {
|
||||
state.showMemDialog.query.teamId = team.id;
|
||||
await setMemebers();
|
||||
state.showMemDialog.title = `[${team.name}] 成员信息`;
|
||||
state.showMemDialog.visible = true;
|
||||
};
|
||||
|
||||
const getAccount = (username: any) => {
|
||||
accountApi.list.request({ username }).then((res) => {
|
||||
state.showMemDialog.accounts = res.list;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 选中成员
|
||||
*/
|
||||
const chooseMember = (item: any) => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
state.showMemDialog.chooseData = item;
|
||||
state.showMemDialog.chooseId = item.id;
|
||||
};
|
||||
|
||||
const deleteMember = async () => {
|
||||
await tagApi.delTeamMem.request(state.showMemDialog.chooseData);
|
||||
ElMessage.success('移除成功');
|
||||
// 重新赋值成员列表
|
||||
setMemebers();
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置成员列表信息
|
||||
*/
|
||||
const setMemebers = async () => {
|
||||
const res = await tagApi.getTeamMem.request(state.showMemDialog.query);
|
||||
state.showMemDialog.members.list = res.list;
|
||||
state.showMemDialog.members.total = res.total;
|
||||
};
|
||||
|
||||
const showAddMemberDialog = () => {
|
||||
state.showMemDialog.addVisible = true;
|
||||
};
|
||||
|
||||
const addMember = async () => {
|
||||
const memForm = state.showMemDialog.memForm;
|
||||
memForm.teamId = state.chooseId;
|
||||
notBlank(memForm.accountId, '请先选择账号');
|
||||
|
||||
await tagApi.saveTeamMem.request(memForm);
|
||||
ElMessage.success('保存成功');
|
||||
setMemebers();
|
||||
cancelAddMember();
|
||||
};
|
||||
|
||||
const cancelAddMember = () => {
|
||||
state.showMemDialog.memForm = {} as any;
|
||||
state.showMemDialog.addVisible = false;
|
||||
state.showMemDialog.chooseData = null;
|
||||
state.showMemDialog.chooseId = 0;
|
||||
};
|
||||
|
||||
/********** 标签相关 ***********/
|
||||
|
||||
const showTags = async (team: any) => {
|
||||
state.showTagDialog.tags = await tagApi.getTagTrees.request(null);
|
||||
state.showTagDialog.tagTreeTeams = await tagApi.getTeamTagIds.request({ teamId: team.id });
|
||||
state.showTagDialog.title = `[${team.name}] 项目信息`;
|
||||
state.showTagDialog.teamId = team.id;
|
||||
state.showTagDialog.visible = true;
|
||||
};
|
||||
|
||||
const closeTagDialog = () => {
|
||||
state.showTagDialog.visible = false;
|
||||
setTimeout(() => {
|
||||
state.showTagDialog.tagTreeTeams = [];
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const saveTags = async () => {
|
||||
await tagApi.saveTeamTags.request({
|
||||
teamId: state.showTagDialog.teamId,
|
||||
tagIds: state.showTagDialog.tagTreeTeams,
|
||||
});
|
||||
ElMessage.success('保存成功');
|
||||
closeTagDialog();
|
||||
};
|
||||
|
||||
const tagTreeNodeCheck = (data: any, checkInfo: any) => {
|
||||
const node = tagTreeRef.value.getNode(data.id);
|
||||
console.log(node);
|
||||
// state.showTagDialog.tagTreeTeams = [16]
|
||||
if (node.checked) {
|
||||
if (node.parent) {
|
||||
console.log(node.parent);
|
||||
// removeCheckedTagId(node.parent.key);
|
||||
tagTreeRef.value.setChecked(node.parent, false, false);
|
||||
}
|
||||
// // parentNode = node.parent
|
||||
// for (let parentNode of node.parent) {
|
||||
// parentNode.setChecked(false);
|
||||
// }
|
||||
}
|
||||
console.log(data);
|
||||
console.log(checkInfo);
|
||||
};
|
||||
|
||||
// function removeCheckedTagId(id: any) {
|
||||
// console.log(state.showTagDialog.tagTreeTeams);
|
||||
// for (let i = 0; i < state.showTagDialog.tagTreeTeams.length; i++) {
|
||||
// if (state.showTagDialog.tagTreeTeams[i] == id) {
|
||||
// console.log('has id', id);
|
||||
// state.showTagDialog.tagTreeTeams.splice(i, 1);
|
||||
// }
|
||||
// }
|
||||
// console.log(state.showTagDialog.tagTreeTeams);
|
||||
// }
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
teamForm,
|
||||
tagTreeRef,
|
||||
dateFormat,
|
||||
choose,
|
||||
search,
|
||||
handlePageChange,
|
||||
showSaveTeamDialog,
|
||||
saveTeam,
|
||||
cancelSaveTeam,
|
||||
deleteTeam,
|
||||
showMembers,
|
||||
setMemebers,
|
||||
getAccount,
|
||||
showAddMemberDialog,
|
||||
addMember,
|
||||
cancelAddMember,
|
||||
chooseMember,
|
||||
deleteMember,
|
||||
showTags,
|
||||
closeTagDialog,
|
||||
saveTags,
|
||||
tagTreeNodeCheck,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
</style>
|
||||
19
mayfly_go_web/src/views/ops/tag/api.ts
Normal file
19
mayfly_go_web/src/views/ops/tag/api.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import Api from '@/common/Api';
|
||||
|
||||
export const tagApi = {
|
||||
getAccountTags: Api.create("/tag-trees/account-has", 'get'),
|
||||
getTagTrees: Api.create("/tag-trees", 'get'),
|
||||
saveTagTree: Api.create("/tag-trees", 'post'),
|
||||
delTagTree: Api.create("/tag-trees/{id}", 'delete'),
|
||||
|
||||
getTeams: Api.create("/teams", 'get'),
|
||||
saveTeam: Api.create("/teams", 'post'),
|
||||
delTeam: Api.create("/teams/{id}", 'delete'),
|
||||
|
||||
getTeamMem: Api.create("/teams/{teamId}/members", 'get'),
|
||||
saveTeamMem: Api.create("/teams/{teamId}/members", 'post'),
|
||||
delTeamMem: Api.create("/teams/{teamId}/members/{accountId}", 'delete'),
|
||||
|
||||
getTeamTagIds: Api.create("/teams/{teamId}/tags", 'get'),
|
||||
saveTeamTags: Api.create("/teams/{teamId}/tags", 'post'),
|
||||
}
|
||||
@@ -5,12 +5,9 @@
|
||||
<el-form-item prop="username" label="用户名:" required>
|
||||
<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-form-item v-if="edit" prop="password" label="密码:" required>
|
||||
<el-input type="password" v-model.trim="form.password" placeholder="请输入密码" autocomplete="new-password"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="!edit" label="确认密码:" required>
|
||||
<el-input type="password" v-model.trim="form.repassword" placeholder="请输入确认密码" autocomplete="new-password"></el-input>
|
||||
</el-form-item> -->
|
||||
</el-form>
|
||||
|
||||
<template #footer>
|
||||
@@ -74,18 +71,18 @@ export default defineComponent({
|
||||
watch(props, (newValue) => {
|
||||
if (newValue.account) {
|
||||
state.form = { ...newValue.account };
|
||||
state.edit = true;
|
||||
} else {
|
||||
state.edit = false;
|
||||
state.form = {} as any;
|
||||
}
|
||||
state.dialogVisible = newValue.visible;
|
||||
});
|
||||
|
||||
const btnOk = async () => {
|
||||
let p = state.form.id ? accountApi.update : accountApi.save;
|
||||
|
||||
accountForm.value.validate((valid: boolean) => {
|
||||
if (valid) {
|
||||
p.request(state.form).then(() => {
|
||||
accountApi.save.request(state.form).then(() => {
|
||||
ElMessage.success('操作成功');
|
||||
emit('val-change', state.form);
|
||||
state.btnLoading = true;
|
||||
|
||||
@@ -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:add'" :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
|
||||
>
|
||||
@@ -20,7 +20,7 @@
|
||||
<el-button @click="search()" type="success" icon="search" size="small"></el-button>
|
||||
</div>
|
||||
<el-table :data="datas" ref="table" @current-change="choose" show-overflow-tooltip>
|
||||
<el-table-column label="选择" width="50px">
|
||||
<el-table-column label="选择" width="55px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
@@ -29,20 +29,20 @@
|
||||
</el-table-column>
|
||||
<el-table-column prop="username" label="用户名" min-width="115"></el-table-column>
|
||||
|
||||
<el-table-column align="center" prop="status" label="状态" min-width="63">
|
||||
<el-table-column align="center" prop="status" label="状态" min-width="65">
|
||||
<template #default="scope">
|
||||
<el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
|
||||
<el-tag v-if="scope.row.status == -1" type="danger">禁用</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column min-width="160" prop="lastLoginTime" label="最后登录时间">
|
||||
<el-table-column min-width="160" prop="lastLoginTime" label="最后登录时间" show-overflow-tooltip>
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.lastLoginTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column min-width="115" prop="creator" label="创建账号"></el-table-column>
|
||||
<el-table-column min-width="160" prop="createTime" label="创建时间">
|
||||
<el-table-column min-width="160" prop="createTime" label="创建时间" show-overflow-tooltip>
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
|
||||
@@ -32,6 +32,12 @@ export const accountApi = {
|
||||
saveRoles: Api.create("/sys/accounts/roles", 'post')
|
||||
}
|
||||
|
||||
export const configApi = {
|
||||
list: Api.create("/sys/configs", 'get'),
|
||||
save: Api.create("/sys/configs", 'post'),
|
||||
getValue: Api.create("/sys/configs/value", 'get'),
|
||||
}
|
||||
|
||||
export const logApi = {
|
||||
list: Api.create("/syslogs", "get")
|
||||
}
|
||||
|
||||
139
mayfly_go_web/src/views/system/config/ConfigEdit.vue
Executable file
139
mayfly_go_web/src/views/system/config/ConfigEdit.vue
Executable file
@@ -0,0 +1,139 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-dialog :title="title" v-model="dvisible" :show-close="false" :before-close="cancel" width="750px" :destroy-on-close="true">
|
||||
<el-form ref="configForm" :model="form" label-width="90px">
|
||||
<el-form-item prop="name" label="配置项:" required>
|
||||
<el-input v-model="form.name"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="key" label="配置key:" required>
|
||||
<el-input :disabled="form.id != null" v-model="form.key"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-row style="margin-left: 30px; margin-bottom: 5px">
|
||||
<el-button @click="onAddParam" size="small" type="success">新增配置项</el-button>
|
||||
</el-row>
|
||||
<el-form-item :key="param" v-for="(param, index) in params" prop="params" :label="`参数${index + 1}`">
|
||||
<el-row>
|
||||
<el-col :span="5"><el-input v-model="param.model" placeholder="model"></el-input></el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="4"><el-input v-model="param.name" placeholder="字段名"></el-input></el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="4"><el-input v-model="param.placeholder" placeholder="字段说明"></el-input></el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="4">
|
||||
<el-input v-model="param.options" placeholder="可选值 ,分割"></el-input>
|
||||
</el-col>
|
||||
<el-divider :span="1" direction="vertical" border-style="dashed" />
|
||||
<el-col :span="2"><el-button @click="onDeleteParam(index)" size="small" type="danger">删除</el-button></el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<!-- <el-form-item prop="value" label="配置值:" required>
|
||||
<el-input v-model="form.value"></el-input>
|
||||
</el-form-item> -->
|
||||
<el-form-item label="备注:">
|
||||
<el-input v-model="form.remark" type="textarea" :rows="2"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="cancel()">取 消</el-button>
|
||||
<el-button type="primary" :loading="btnLoading" @click="btnOk">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { ref, toRefs, reactive, watch, defineComponent } from 'vue';
|
||||
import { configApi } from '../api';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'ConfigEdit',
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
},
|
||||
data: {
|
||||
type: [Boolean, Object],
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
},
|
||||
},
|
||||
setup(props: any, { emit }) {
|
||||
const configForm: any = ref(null);
|
||||
const state = reactive({
|
||||
dvisible: false,
|
||||
params: [] as any,
|
||||
form: {
|
||||
id: null,
|
||||
name: '',
|
||||
key: '',
|
||||
params: '',
|
||||
value: '',
|
||||
remark: '',
|
||||
},
|
||||
btnLoading: false,
|
||||
});
|
||||
|
||||
watch(props, (newValue) => {
|
||||
state.dvisible = newValue.visible;
|
||||
if (newValue.data) {
|
||||
state.form = { ...newValue.data };
|
||||
if (state.form.params) {
|
||||
state.params = JSON.parse(state.form.params);
|
||||
} else {
|
||||
state.params = [];
|
||||
}
|
||||
} else {
|
||||
state.form = {} as any;
|
||||
state.params = [];
|
||||
}
|
||||
});
|
||||
|
||||
const onAddParam = () => {
|
||||
state.params.push({ name: '', model: '', placeholder: '' });
|
||||
};
|
||||
|
||||
const onDeleteParam = (idx: number) => {
|
||||
state.params.splice(idx, 1);
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
// 更新父组件visible prop对应的值为false
|
||||
emit('update:visible', false);
|
||||
// 若父组件有取消事件,则调用
|
||||
emit('cancel');
|
||||
};
|
||||
|
||||
const btnOk = async () => {
|
||||
configForm.value.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
if (state.params) {
|
||||
state.form.params = JSON.stringify(state.params);
|
||||
}
|
||||
await configApi.save.request(state.form);
|
||||
emit('val-change', state.form);
|
||||
cancel();
|
||||
state.btnLoading = true;
|
||||
setTimeout(() => {
|
||||
state.btnLoading = false;
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
onAddParam,
|
||||
onDeleteParam,
|
||||
configForm,
|
||||
btnOk,
|
||||
cancel,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
</style>
|
||||
238
mayfly_go_web/src/views/system/config/ConfigList.vue
Executable file
238
mayfly_go_web/src/views/system/config/ConfigList.vue
Executable file
@@ -0,0 +1,238 @@
|
||||
<template>
|
||||
<div class="role-list">
|
||||
<el-card>
|
||||
<el-button type="primary" icon="plus" @click="editConfig(false)">添加</el-button>
|
||||
<el-button :disabled="chooseId == null" @click="editConfig(chooseData)" type="primary" icon="edit">编辑</el-button>
|
||||
|
||||
<el-table :data="configs" @current-change="choose" ref="table" style="width: 100%">
|
||||
<el-table-column label="选择" width="55px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
</el-radio>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="name" label="配置项"></el-table-column>
|
||||
<el-table-column prop="key" label="配置key"></el-table-column>
|
||||
<el-table-column prop="value" label="配置值" min-width="100px" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="100px" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="updateTime" label="更新时间" min-width="100px">
|
||||
<template #default="scope">
|
||||
{{ $filters.dateFormat(scope.row.createTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="modifier" label="修改者" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column label="操作" min-width="50" fixed="right">
|
||||
<template #default="scope">
|
||||
<el-link
|
||||
:disabled="scope.row.status == -1"
|
||||
type="warning"
|
||||
@click="showSetConfigDialog(scope.row)"
|
||||
plain
|
||||
size="small"
|
||||
:underline="false"
|
||||
>配置</el-link
|
||||
>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-row style="margin-top: 20px" type="flex" justify="end">
|
||||
<el-pagination
|
||||
style="text-align: right"
|
||||
@current-change="handlePageChange"
|
||||
:total="total"
|
||||
layout="prev, pager, next, total, jumper"
|
||||
v-model:current-page="query.pageNum"
|
||||
:page-size="query.pageSize"
|
||||
></el-pagination>
|
||||
</el-row>
|
||||
</el-card>
|
||||
|
||||
<el-dialog :before-close="closeSetConfigDialog" title="配置项设置" v-model="paramsDialog.visible" width="500px">
|
||||
<el-form v-if="paramsDialog.paramsFormItem.length > 0" ref="paramsForm" :model="paramsDialog.params" label-width="90px">
|
||||
<el-form-item v-for="item in paramsDialog.paramsFormItem" :key="item.name" :prop="item.model" :label="item.name" required>
|
||||
<el-input
|
||||
v-if="!item.options"
|
||||
v-model="paramsDialog.params[item.model]"
|
||||
:placeholder="item.placeholder"
|
||||
autocomplete="off"
|
||||
clearable
|
||||
></el-input>
|
||||
<el-select
|
||||
v-else
|
||||
v-model="paramsDialog.params[item.model]"
|
||||
:placeholder="item.placeholder"
|
||||
filterable
|
||||
autocomplete="off"
|
||||
clearable
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option v-for="option in item.options.split(',')" :key="option" :label="option" :value="option" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-form v-else ref="paramsForm" label-width="90px">
|
||||
<el-form-item label="配置值" required>
|
||||
<el-input v-model="paramsDialog.params" :placeholder="paramsDialog.config.remark" autocomplete="off" clearable></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="closeSetConfigDialog()">取 消</el-button>
|
||||
<el-button type="primary" @click="setConfig()">确 定</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<config-edit :title="configEdit.title" v-model:visible="configEdit.visible" :data="configEdit.config" @val-change="configEditChange" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, reactive, onMounted, defineComponent } from 'vue';
|
||||
import ConfigEdit from './ConfigEdit.vue';
|
||||
import { configApi } from '../api';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
export default defineComponent({
|
||||
name: 'ConfigList',
|
||||
components: {
|
||||
ConfigEdit,
|
||||
},
|
||||
setup() {
|
||||
const state = reactive({
|
||||
dialogFormVisible: false,
|
||||
currentEditPermissions: false,
|
||||
query: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
name: null,
|
||||
},
|
||||
total: 0,
|
||||
configs: [],
|
||||
chooseId: null,
|
||||
chooseData: null,
|
||||
paramsDialog: {
|
||||
visible: false,
|
||||
config: null as any,
|
||||
params: {},
|
||||
paramsFormItem: [] as any,
|
||||
},
|
||||
configEdit: {
|
||||
title: '配置修改',
|
||||
visible: false,
|
||||
config: {},
|
||||
},
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
search();
|
||||
});
|
||||
|
||||
const search = async () => {
|
||||
let res = await configApi.list.request(state.query);
|
||||
state.configs = res.list;
|
||||
state.total = res.total;
|
||||
};
|
||||
|
||||
const handlePageChange = (curPage: number) => {
|
||||
state.query.pageNum = curPage;
|
||||
search();
|
||||
};
|
||||
|
||||
const showSetConfigDialog = (row: any) => {
|
||||
state.paramsDialog.config = row;
|
||||
// 存在配置项则弹窗提示输入对应的配置项
|
||||
if (row.params) {
|
||||
state.paramsDialog.paramsFormItem = JSON.parse(row.params);
|
||||
if (state.paramsDialog.paramsFormItem && state.paramsDialog.paramsFormItem.length > 0) {
|
||||
if (row.value) {
|
||||
state.paramsDialog.params = JSON.parse(row.value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
state.paramsDialog.params = row.value;
|
||||
}
|
||||
state.paramsDialog.visible = true;
|
||||
};
|
||||
|
||||
const closeSetConfigDialog = () => {
|
||||
state.paramsDialog.visible = false;
|
||||
setTimeout(() => {
|
||||
state.paramsDialog.config = {};
|
||||
state.paramsDialog.params = {};
|
||||
state.paramsDialog.paramsFormItem = [];
|
||||
}, 300);
|
||||
};
|
||||
|
||||
const setConfig = async () => {
|
||||
let paramsValue = state.paramsDialog.params;
|
||||
if (state.paramsDialog.paramsFormItem.length > 0) {
|
||||
// 如果配置项删除,则需要将value中对应的字段移除
|
||||
for (let paramKey in paramsValue) {
|
||||
if (!hasParam(paramKey, state.paramsDialog.paramsFormItem)) {
|
||||
delete paramsValue[paramKey];
|
||||
}
|
||||
}
|
||||
paramsValue = JSON.stringify(paramsValue);
|
||||
}
|
||||
await configApi.save.request({
|
||||
id: state.paramsDialog.config.id,
|
||||
key: state.paramsDialog.config.key,
|
||||
name: state.paramsDialog.config.name,
|
||||
value: paramsValue,
|
||||
});
|
||||
ElMessage.success('保存成功');
|
||||
closeSetConfigDialog();
|
||||
search();
|
||||
};
|
||||
|
||||
const hasParam = (paramKey: string, paramItems: any) => {
|
||||
for (let paramItem of paramItems) {
|
||||
if (paramItem.model == paramKey) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const choose = (item: any) => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
state.chooseId = item.id;
|
||||
state.chooseData = item;
|
||||
};
|
||||
|
||||
const configEditChange = () => {
|
||||
ElMessage.success('保存成功');
|
||||
state.chooseId = null;
|
||||
state.chooseData = null;
|
||||
search();
|
||||
};
|
||||
|
||||
const editConfig = (data: any) => {
|
||||
if (data) {
|
||||
state.configEdit.config = data;
|
||||
} else {
|
||||
state.configEdit.config = false;
|
||||
}
|
||||
|
||||
state.configEdit.visible = true;
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
showSetConfigDialog,
|
||||
closeSetConfigDialog,
|
||||
setConfig,
|
||||
search,
|
||||
handlePageChange,
|
||||
choose,
|
||||
configEditChange,
|
||||
editConfig,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="scss">
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="role-dialog">
|
||||
<el-dialog :title="title" v-model="dvisible" :show-close="false" :before-close="cancel" width="500px" :destroy-on-close="true">
|
||||
<el-form :model="form" label-width="90px">
|
||||
<el-form ref="roleForm" :model="form" label-width="90px">
|
||||
<el-form-item prop="name" label="角色名称:" required>
|
||||
<el-input v-model="form.name" auto-complete="off"></el-input>
|
||||
</el-form-item>
|
||||
@@ -28,7 +28,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { toRefs, reactive, watch, defineComponent } from 'vue';
|
||||
import { ref, toRefs, reactive, watch, defineComponent } from 'vue';
|
||||
import { roleApi } from '../api';
|
||||
|
||||
export default defineComponent({
|
||||
@@ -45,6 +45,7 @@ export default defineComponent({
|
||||
},
|
||||
},
|
||||
setup(props: any, { emit }) {
|
||||
const roleForm: any = ref(null);
|
||||
const state = reactive({
|
||||
dvisible: false,
|
||||
form: {
|
||||
@@ -73,18 +74,22 @@ export default defineComponent({
|
||||
};
|
||||
|
||||
const btnOk = async () => {
|
||||
// let p = state.form.id ? roleApi.update : roleApi.save;
|
||||
await roleApi.save.request(state.form);
|
||||
emit('val-change', state.form);
|
||||
cancel();
|
||||
state.btnLoading = true;
|
||||
setTimeout(() => {
|
||||
state.btnLoading = false;
|
||||
}, 1000);
|
||||
roleForm.value.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
await roleApi.save.request(state.form);
|
||||
emit('val-change', state.form);
|
||||
cancel();
|
||||
state.btnLoading = true;
|
||||
setTimeout(() => {
|
||||
state.btnLoading = false;
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
roleForm,
|
||||
btnOk,
|
||||
cancel,
|
||||
};
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<el-button @click="search" type="success" icon="search"></el-button>
|
||||
</div>
|
||||
<el-table :data="roles" @current-change="choose" ref="table" style="width: 100%">
|
||||
<el-table-column label="选择" width="50px">
|
||||
<el-table-column label="选择" width="55px">
|
||||
<template #default="scope">
|
||||
<el-radio v-model="chooseId" :label="scope.row.id">
|
||||
<i></i>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,3 @@
|
||||
app:
|
||||
name: mayfly-go
|
||||
version: 1.2.3
|
||||
|
||||
server:
|
||||
# debug release test
|
||||
model: release
|
||||
@@ -11,24 +7,16 @@ server:
|
||||
enable: false
|
||||
key-file: ./default.key
|
||||
cert-file: ./default.pem
|
||||
# 静态资源
|
||||
static:
|
||||
- relative-path: /assets
|
||||
root: ./static/assets
|
||||
# 静态文件
|
||||
static-file:
|
||||
- relative-path: /
|
||||
filepath: ./static/index.html
|
||||
- relative-path: /favicon.ico
|
||||
filepath: ./static/favicon.ico
|
||||
- relative-path: /config.js
|
||||
filepath: ./static/config.js
|
||||
|
||||
# 机器终端操作回放文件存储路径
|
||||
machine-rec-path: ./rec
|
||||
jwt:
|
||||
key: mykey
|
||||
# jwt key,不设置默认使用随机字符串
|
||||
key:
|
||||
# 过期时间单位分钟
|
||||
expire-time: 1440
|
||||
|
||||
# 资源密码aes加密key
|
||||
aes:
|
||||
key: 1111111111111111
|
||||
mysql:
|
||||
host: localhost:3306
|
||||
username: root
|
||||
@@ -36,7 +24,6 @@ mysql:
|
||||
db-name: mayfly-go
|
||||
config: charset=utf8&loc=Local&parseTime=true
|
||||
max-idle-conns: 5
|
||||
|
||||
log:
|
||||
# 日志等级, trace, debug, info, warn, error, fatal
|
||||
level: info
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
module mayfly-go
|
||||
|
||||
go 1.18
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible // jwt
|
||||
github.com/gin-gonic/gin v1.8.1
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/go-sql-driver/mysql v1.6.0
|
||||
github.com/golang-jwt/jwt/v4 v4.4.2
|
||||
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.5
|
||||
github.com/robfig/cron/v3 v3.0.1 // 定时任务
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
github.com/sirupsen/logrus v1.9.0
|
||||
github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2
|
||||
go.mongodb.org/mongo-driver v1.9.1 // mongo
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // ssh
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
|
||||
golang.org/x/crypto v0.1.0 // ssh
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
// gorm
|
||||
gorm.io/driver/mysql v1.3.4
|
||||
gorm.io/gorm v1.23.5
|
||||
gorm.io/driver/mysql v1.4.1
|
||||
gorm.io/gorm v1.24.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -34,7 +34,7 @@ require (
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // 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
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.13.6 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
@@ -50,10 +50,10 @@ 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/net v0.1.0 // 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
|
||||
golang.org/x/sys v0.1.0 // indirect
|
||||
golang.org/x/text v0.4.0 // 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
|
||||
|
||||
@@ -2,16 +2,29 @@ package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
common_router "mayfly-go/internal/common/router"
|
||||
devops_router "mayfly-go/internal/devops/router"
|
||||
db_router "mayfly-go/internal/db/router"
|
||||
machine_router "mayfly-go/internal/machine/router"
|
||||
mongo_router "mayfly-go/internal/mongo/router"
|
||||
redis_router "mayfly-go/internal/redis/router"
|
||||
sys_router "mayfly-go/internal/sys/router"
|
||||
tag_router "mayfly-go/internal/tag/router"
|
||||
"mayfly-go/pkg/config"
|
||||
"mayfly-go/pkg/middleware"
|
||||
"mayfly-go/static"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func WrapStaticHandler(h http.Handler) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Cache-Control", `public, max-age=31536000`)
|
||||
h.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
}
|
||||
|
||||
func InitRouter() *gin.Engine {
|
||||
// server配置
|
||||
serverConfig := config.Conf.Server
|
||||
@@ -25,12 +38,21 @@ func InitRouter() *gin.Engine {
|
||||
g.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": fmt.Sprintf("not found '%s:%s'", g.Request.Method, g.Request.URL.Path)})
|
||||
})
|
||||
|
||||
// 使用embed打包静态资源至二进制文件中
|
||||
fsys, _ := fs.Sub(static.Static, "static")
|
||||
fileServer := http.FileServer(http.FS(fsys))
|
||||
handler := WrapStaticHandler(fileServer)
|
||||
router.GET("/", handler)
|
||||
router.GET("/favicon.ico", handler)
|
||||
router.GET("/config.js", handler)
|
||||
// 所有/assets/**开头的都是静态资源文件
|
||||
router.GET("/assets/*file", handler)
|
||||
|
||||
// 设置静态资源
|
||||
if staticConfs := serverConfig.Static; staticConfs != nil {
|
||||
for _, scs := range *staticConfs {
|
||||
router.Static(scs.RelativePath, scs.Root)
|
||||
router.StaticFS(scs.RelativePath, http.Dir(scs.Root))
|
||||
}
|
||||
|
||||
}
|
||||
// 设置静态文件
|
||||
if staticFileConfs := serverConfig.StaticFile; staticFileConfs != nil {
|
||||
@@ -38,6 +60,7 @@ func InitRouter() *gin.Engine {
|
||||
router.StaticFile(sfs.RelativePath, sfs.Filepath)
|
||||
}
|
||||
}
|
||||
|
||||
// 是否允许跨域
|
||||
if serverConfig.Cors {
|
||||
router.Use(middleware.Cors())
|
||||
@@ -49,21 +72,14 @@ func InitRouter() *gin.Engine {
|
||||
common_router.InitIndexRouter(api)
|
||||
common_router.InitCommonRouter(api)
|
||||
|
||||
sys_router.InitCaptchaRouter(api)
|
||||
sys_router.InitAccountRouter(api) // 注册account路由
|
||||
sys_router.InitResourceRouter(api)
|
||||
sys_router.InitRoleRouter(api)
|
||||
sys_router.InitSystemRouter(api)
|
||||
sys_router.InitSyslogRouter(api)
|
||||
sys_router.Init(api)
|
||||
|
||||
devops_router.InitProjectRouter(api)
|
||||
devops_router.InitDbRouter(api)
|
||||
devops_router.InitDbSqlExecRouter(api)
|
||||
devops_router.InitRedisRouter(api)
|
||||
devops_router.InitMachineRouter(api)
|
||||
devops_router.InitMachineScriptRouter(api)
|
||||
devops_router.InitMachineFileRouter(api)
|
||||
devops_router.InitMongoRouter(api)
|
||||
// project_router.Init(api)
|
||||
tag_router.Init(api)
|
||||
machine_router.Init(api)
|
||||
db_router.Init(api)
|
||||
redis_router.Init(api)
|
||||
mongo_router.Init(api)
|
||||
}
|
||||
|
||||
return router
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
sys_application "mayfly-go/internal/sys/application"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
"mayfly-go/pkg/ctx"
|
||||
)
|
||||
|
||||
func InitSaveLogFunc() ctx.SaveLogFunc {
|
||||
return sys_application.SyslogApp.SaveFromReq
|
||||
return sysapp.GetSyslogApp().SaveFromReq
|
||||
}
|
||||
|
||||
@@ -1,23 +1,45 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/devops/application"
|
||||
"mayfly-go/internal/devops/domain/entity"
|
||||
dbapp "mayfly-go/internal/db/application"
|
||||
dbentity "mayfly-go/internal/db/domain/entity"
|
||||
machineapp "mayfly-go/internal/machine/application"
|
||||
machineentity "mayfly-go/internal/machine/domain/entity"
|
||||
mongoapp "mayfly-go/internal/mongo/application"
|
||||
mongoentity "mayfly-go/internal/mongo/domain/entity"
|
||||
redisapp "mayfly-go/internal/redis/application"
|
||||
redisentity "mayfly-go/internal/redis/domain/entity"
|
||||
tagapp "mayfly-go/internal/tag/application"
|
||||
"mayfly-go/pkg/ctx"
|
||||
)
|
||||
|
||||
type Index struct {
|
||||
ProjectApp application.Project
|
||||
MachineApp application.Machine
|
||||
DbApp application.Db
|
||||
RedisApp application.Redis
|
||||
TagApp tagapp.TagTree
|
||||
MachineApp machineapp.Machine
|
||||
DbApp dbapp.Db
|
||||
RedisApp redisapp.Redis
|
||||
MongoApp mongoapp.Mongo
|
||||
}
|
||||
|
||||
func (i *Index) Count(rc *ctx.ReqCtx) {
|
||||
accountId := rc.LoginAccount.Id
|
||||
tagIds := i.TagApp.ListTagIdByAccountId(accountId)
|
||||
|
||||
var mongoNum int64
|
||||
var redisNum int64
|
||||
var dbNum int64
|
||||
var machienNum int64
|
||||
|
||||
if len(tagIds) > 0 {
|
||||
mongoNum = i.MongoApp.Count(&mongoentity.MongoQuery{TagIds: tagIds})
|
||||
machienNum = i.MachineApp.Count(&machineentity.MachineQuery{TagIds: tagIds})
|
||||
dbNum = i.DbApp.Count(&dbentity.DbQuery{TagIds: tagIds})
|
||||
redisNum = i.RedisApp.Count(&redisentity.RedisQuery{TagIds: tagIds})
|
||||
}
|
||||
rc.ResData = map[string]interface{}{
|
||||
"projectNum": i.ProjectApp.Count(new(entity.Project)),
|
||||
"machineNum": i.MachineApp.Count(new(entity.Machine)),
|
||||
"dbNum": i.DbApp.Count(new(entity.Db)),
|
||||
"redisNum": i.RedisApp.Count(new(entity.Redis)),
|
||||
"mongoNum": mongoNum,
|
||||
"machineNum": machienNum,
|
||||
"dbNum": dbNum,
|
||||
"redisNum": redisNum,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,11 @@ package router
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/common/api"
|
||||
devops_app "mayfly-go/internal/devops/application"
|
||||
dbapp "mayfly-go/internal/db/application"
|
||||
machineapp "mayfly-go/internal/machine/application"
|
||||
mongoapp "mayfly-go/internal/mongo/application"
|
||||
redisapp "mayfly-go/internal/redis/application"
|
||||
tagapp "mayfly-go/internal/tag/application"
|
||||
"mayfly-go/pkg/ctx"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -11,10 +15,11 @@ import (
|
||||
func InitIndexRouter(router *gin.RouterGroup) {
|
||||
index := router.Group("common/index")
|
||||
i := &api.Index{
|
||||
ProjectApp: devops_app.ProjectApp,
|
||||
MachineApp: devops_app.MachineApp,
|
||||
DbApp: devops_app.DbApp,
|
||||
RedisApp: devops_app.RedisApp,
|
||||
TagApp: tagapp.GetTagTreeApp(),
|
||||
MachineApp: machineapp.GetMachineApp(),
|
||||
DbApp: dbapp.GetDbApp(),
|
||||
RedisApp: redisapp.GetRedisApp(),
|
||||
MongoApp: mongoapp.GetMongoApp(),
|
||||
}
|
||||
{
|
||||
// 首页基本信息统计
|
||||
|
||||
35
server/internal/common/utils/pwd.go
Normal file
35
server/internal/common/utils/pwd.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/config"
|
||||
)
|
||||
|
||||
// 使用config.yml的aes.key进行密码加密
|
||||
func PwdAesEncrypt(password string) string {
|
||||
if password == "" {
|
||||
return ""
|
||||
}
|
||||
aes := config.Conf.Aes
|
||||
if aes == nil {
|
||||
return password
|
||||
}
|
||||
encryptPwd, err := aes.EncryptBase64([]byte(password))
|
||||
biz.ErrIsNilAppendErr(err, "密码加密失败: %s")
|
||||
return encryptPwd
|
||||
}
|
||||
|
||||
// 使用config.yml的aes.key进行密码解密
|
||||
func PwdAesDecrypt(encryptPwd string) string {
|
||||
if encryptPwd == "" {
|
||||
return ""
|
||||
}
|
||||
aes := config.Conf.Aes
|
||||
if aes == nil {
|
||||
return encryptPwd
|
||||
}
|
||||
decryptPwd, err := aes.DecryptBase64(encryptPwd)
|
||||
biz.ErrIsNilAppendErr(err, "密码解密失败: %s")
|
||||
// 解密后的密码
|
||||
return string(decryptPwd)
|
||||
}
|
||||
16
server/internal/constant/constant.go
Normal file
16
server/internal/constant/constant.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package constant
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
MachineConnExpireTime = 60 * time.Minute
|
||||
DbConnExpireTime = 45 * time.Minute
|
||||
RedisConnExpireTime = 30 * time.Minute
|
||||
MongoConnExpireTime = 30 * time.Minute
|
||||
|
||||
/**** 开发测试使用 ****/
|
||||
// MachineConnExpireTime = 4 * time.Minute
|
||||
// DbConnExpireTime = 2 * time.Minute
|
||||
// RedisConnExpireTime = 2 * time.Minute
|
||||
// MongoConnExpireTime = 2 * time.Minute
|
||||
)
|
||||
@@ -3,11 +3,12 @@ package api
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mayfly-go/internal/devops/api/form"
|
||||
"mayfly-go/internal/devops/api/vo"
|
||||
"mayfly-go/internal/devops/application"
|
||||
"mayfly-go/internal/devops/domain/entity"
|
||||
sysApplication "mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/db/api/form"
|
||||
"mayfly-go/internal/db/api/vo"
|
||||
"mayfly-go/internal/db/application"
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
tagapp "mayfly-go/internal/tag/application"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/ctx"
|
||||
"mayfly-go/pkg/ginx"
|
||||
@@ -25,20 +26,25 @@ import (
|
||||
type Db struct {
|
||||
DbApp application.Db
|
||||
DbSqlExecApp application.DbSqlExec
|
||||
MsgApp sysApplication.Msg
|
||||
ProjectApp application.Project
|
||||
MsgApp sysapp.Msg
|
||||
TagApp tagapp.TagTree
|
||||
}
|
||||
|
||||
const DEFAULT_COLUMN_SIZE = 500
|
||||
const DEFAULT_ROW_SIZE = 1800
|
||||
|
||||
// @router /api/dbs [get]
|
||||
func (d *Db) Dbs(rc *ctx.ReqCtx) {
|
||||
g := rc.GinCtx
|
||||
m := &entity.Db{EnvId: uint64(ginx.QueryInt(g, "envId", 0)),
|
||||
ProjectId: uint64(ginx.QueryInt(g, "projectId", 0)),
|
||||
condition := new(entity.DbQuery)
|
||||
condition.TagPathLike = rc.GinCtx.Query("tagPath")
|
||||
|
||||
// 不存在可访问标签id,即没有可操作数据
|
||||
tagIds := d.TagApp.ListTagIdByAccountId(rc.LoginAccount.Id)
|
||||
if len(tagIds) == 0 {
|
||||
rc.ResData = model.EmptyPageResult()
|
||||
return
|
||||
}
|
||||
m.CreatorId = rc.LoginAccount.Id
|
||||
rc.ResData = d.DbApp.GetPageList(m, ginx.GetPageParam(rc.GinCtx), new([]vo.SelectDataDbVO))
|
||||
condition.TagIds = tagIds
|
||||
rc.ResData = d.DbApp.GetPageList(condition, ginx.GetPageParam(rc.GinCtx), new([]vo.SelectDataDbVO))
|
||||
}
|
||||
|
||||
func (d *Db) Save(rc *ctx.ReqCtx) {
|
||||
@@ -55,21 +61,40 @@ func (d *Db) Save(rc *ctx.ReqCtx) {
|
||||
|
||||
// 密码脱敏记录日志
|
||||
form.Password = "****"
|
||||
|
||||
// if form.Type == "mysql" && form.EnableSSH == 1 {
|
||||
// // originSSHPwd, err := utils.DefaultRsaDecrypt(form.SSHPass, true)
|
||||
// biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
|
||||
// // db.SSHPass = originSSHPwd
|
||||
// // 密码脱敏记录日志
|
||||
// form.SSHPass = "****"
|
||||
// }
|
||||
|
||||
rc.ReqParam = form
|
||||
|
||||
db.SetBaseInfo(rc.LoginAccount)
|
||||
d.DbApp.Save(db)
|
||||
}
|
||||
|
||||
// 获取数据库实例密码,由于数据库是加密存储,故提供该接口展示原文密码
|
||||
func (d *Db) GetDbPwd(rc *ctx.ReqCtx) {
|
||||
dbId := GetDbId(rc.GinCtx)
|
||||
dbEntity := d.DbApp.GetById(dbId, "Password")
|
||||
dbEntity.PwdDecrypt()
|
||||
rc.ResData = dbEntity.Password
|
||||
}
|
||||
|
||||
// 获取数据库实例的所有数据库名
|
||||
func (d *Db) GetDatabaseNames(rc *ctx.ReqCtx) {
|
||||
form := &form.DbForm{}
|
||||
ginx.BindJsonAndValid(rc.GinCtx, form)
|
||||
|
||||
db := new(entity.Db)
|
||||
utils.Copy(db, form)
|
||||
|
||||
// 密码解密,并使用解密后的赋值
|
||||
originPwd, err := utils.DefaultRsaDecrypt(form.Password, true)
|
||||
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
|
||||
db.Password = originPwd
|
||||
|
||||
// 如果id不为空,并且密码为空则从数据库查询
|
||||
if form.Id != 0 && db.Password == "" {
|
||||
db = d.DbApp.GetById(form.Id)
|
||||
}
|
||||
rc.ResData = d.DbApp.GetDatabases(db)
|
||||
}
|
||||
|
||||
func (d *Db) DeleteDb(rc *ctx.ReqCtx) {
|
||||
dbId := GetDbId(rc.GinCtx)
|
||||
d.DbApp.Delete(dbId)
|
||||
@@ -78,19 +103,19 @@ func (d *Db) DeleteDb(rc *ctx.ReqCtx) {
|
||||
}
|
||||
|
||||
func (d *Db) TableInfos(rc *ctx.ReqCtx) {
|
||||
rc.ResData = d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetTableInfos()
|
||||
rc.ResData = d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetMeta().GetTableInfos()
|
||||
}
|
||||
|
||||
func (d *Db) TableIndex(rc *ctx.ReqCtx) {
|
||||
tn := rc.GinCtx.Query("tableName")
|
||||
biz.NotEmpty(tn, "tableName不能为空")
|
||||
rc.ResData = d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetTableIndex(tn)
|
||||
rc.ResData = d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetMeta().GetTableIndex(tn)
|
||||
}
|
||||
|
||||
func (d *Db) GetCreateTableDdl(rc *ctx.ReqCtx) {
|
||||
tn := rc.GinCtx.Query("tableName")
|
||||
biz.NotEmpty(tn, "tableName不能为空")
|
||||
rc.ResData = d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetCreateTableDdl(tn)
|
||||
rc.ResData = d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetMeta().GetCreateTableDdl(tn)
|
||||
}
|
||||
|
||||
func (d *Db) ExecSql(rc *ctx.ReqCtx) {
|
||||
@@ -101,7 +126,7 @@ func (d *Db) ExecSql(rc *ctx.ReqCtx) {
|
||||
id := GetDbId(g)
|
||||
db := form.Db
|
||||
dbInstance := d.DbApp.GetDbInstance(id, db)
|
||||
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbInstance.ProjectId), "%s")
|
||||
biz.ErrIsNilAppendErr(d.TagApp.CanAccess(rc.LoginAccount.Id, dbInstance.TagPath), "%s")
|
||||
|
||||
// 去除前后空格及换行符
|
||||
sql := strings.TrimFunc(form.Sql, func(r rune) bool {
|
||||
@@ -110,37 +135,21 @@ 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") || strings.HasPrefix(sql, "explain") {
|
||||
colNames, res, err := dbInstance.SelectData(sql)
|
||||
biz.ErrIsNilAppendErr(err, "查询失败: %s")
|
||||
colAndRes := make(map[string]interface{})
|
||||
colAndRes["colNames"] = colNames
|
||||
colAndRes["res"] = res
|
||||
rc.ResData = colAndRes
|
||||
} else {
|
||||
// 根据执行sql,生成执行记录
|
||||
execRecord := d.DbSqlExecApp.GenExecLog(rc.LoginAccount, id, db, sql, dbInstance)
|
||||
|
||||
rowsAffected, err := dbInstance.Exec(sql)
|
||||
biz.ErrIsNilAppendErr(err, "执行失败: %s")
|
||||
res := make([]map[string]string, 0)
|
||||
resData := make(map[string]string)
|
||||
resData["影响条数"] = fmt.Sprintf("%d", rowsAffected)
|
||||
res = append(res, resData)
|
||||
|
||||
colAndRes := make(map[string]interface{})
|
||||
colAndRes["colNames"] = []string{"影响条数"}
|
||||
colAndRes["res"] = res
|
||||
|
||||
rc.ResData = colAndRes
|
||||
// 保存sql执行记录
|
||||
if res[0]["影响条数"] > "0" {
|
||||
execRecord.Remark = form.Remark
|
||||
d.DbSqlExecApp.Save(execRecord)
|
||||
}
|
||||
}
|
||||
execRes, err := d.DbSqlExecApp.Exec(&application.DbSqlExecReq{
|
||||
DbId: id,
|
||||
Db: db,
|
||||
Sql: sql,
|
||||
Remark: form.Remark,
|
||||
DbInstance: dbInstance,
|
||||
LoginAccount: rc.LoginAccount,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "执行失败: %s")
|
||||
colAndRes := make(map[string]interface{})
|
||||
colAndRes["colNames"] = execRes.ColNames
|
||||
colAndRes["res"] = execRes.Res
|
||||
rc.ResData = colAndRes
|
||||
}
|
||||
|
||||
// 执行sql文件
|
||||
@@ -159,7 +168,7 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
|
||||
db := d.DbApp.GetDbInstance(dbId, db)
|
||||
|
||||
dbEntity := d.DbApp.GetById(dbId)
|
||||
dbInfo := fmt.Sprintf("于%s的%s环境", dbEntity.Name, dbEntity.Env)
|
||||
dbInfo := fmt.Sprintf("于%s的%s环境", dbEntity.Name, dbEntity.TagPath)
|
||||
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
@@ -170,7 +179,7 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
|
||||
}
|
||||
}()
|
||||
|
||||
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, db.ProjectId), "%s")
|
||||
biz.ErrIsNilAppendErr(d.TagApp.CanAccess(rc.LoginAccount.Id, db.TagPath), "%s")
|
||||
|
||||
tokens := sqlparser.NewTokenizer(file)
|
||||
for {
|
||||
@@ -204,7 +213,7 @@ func (d *Db) DumpSql(rc *ctx.ReqCtx) {
|
||||
needData := dumpType == "2" || dumpType == "3"
|
||||
|
||||
dbInstance := d.DbApp.GetDbInstance(dbId, db)
|
||||
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbInstance.ProjectId), "%s")
|
||||
biz.ErrIsNilAppendErr(d.TagApp.CanAccess(rc.LoginAccount.Id, dbInstance.TagPath), "%s")
|
||||
|
||||
now := time.Now()
|
||||
filename := fmt.Sprintf("%s.%s.sql", db, now.Format("200601021504"))
|
||||
@@ -218,11 +227,12 @@ func (d *Db) DumpSql(rc *ctx.ReqCtx) {
|
||||
writer.WriteString(fmt.Sprintf("\n-- 导出数据库: %s ", db))
|
||||
writer.WriteString("\n-- ----------------------------\n")
|
||||
|
||||
dbmeta := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx)).GetMeta()
|
||||
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")
|
||||
writer.WriteString(dbmeta.GetCreateTableDdl(table)[0]["Create Table"].(string) + ";\n")
|
||||
}
|
||||
|
||||
if !needData {
|
||||
@@ -235,22 +245,28 @@ func (d *Db) DumpSql(rc *ctx.ReqCtx) {
|
||||
countSql := fmt.Sprintf("SELECT COUNT(*) count FROM %s", table)
|
||||
_, countRes, _ := dbInstance.SelectData(countSql)
|
||||
// 查询出所有列信息总数,手动分页获取所有数据
|
||||
maCount := int(countRes[0]["count"].(int64))
|
||||
maCount := 0
|
||||
// 查询出所有列信息总数,手动分页获取所有数据
|
||||
if count64, is64 := countRes[0]["count"].(int64); is64 {
|
||||
maCount = int(count64)
|
||||
} else {
|
||||
maCount = countRes[0]["count"].(int)
|
||||
}
|
||||
// 计算需要查询的页数
|
||||
pageNum := maCount / DEFAULT_COLUMN_SIZE
|
||||
if maCount%DEFAULT_COLUMN_SIZE > 0 {
|
||||
pageNum := maCount / DEFAULT_ROW_SIZE
|
||||
if maCount%DEFAULT_ROW_SIZE > 0 {
|
||||
pageNum++
|
||||
}
|
||||
|
||||
var sqlTmp string
|
||||
switch dbInstance.Type {
|
||||
case "mysql":
|
||||
case entity.DbTypeMysql:
|
||||
sqlTmp = "SELECT * FROM %s LIMIT %d, %d"
|
||||
case "postgres":
|
||||
case entity.DbTypePostgres:
|
||||
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)
|
||||
sql := fmt.Sprintf(sqlTmp, table, index*DEFAULT_ROW_SIZE, DEFAULT_ROW_SIZE)
|
||||
columns, result, _ := dbInstance.SelectData(sql)
|
||||
|
||||
insertSql := "INSERT INTO `%s` VALUES (%s);\n"
|
||||
@@ -283,8 +299,8 @@ func (d *Db) DumpSql(rc *ctx.ReqCtx) {
|
||||
// @router /api/db/:dbId/t-metadata [get]
|
||||
func (d *Db) TableMA(rc *ctx.ReqCtx) {
|
||||
dbi := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx))
|
||||
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbi.ProjectId), "%s")
|
||||
rc.ResData = dbi.GetTableMetedatas()
|
||||
biz.ErrIsNilAppendErr(d.TagApp.CanAccess(rc.LoginAccount.Id, dbi.TagPath), "%s")
|
||||
rc.ResData = dbi.GetMeta().GetTables()
|
||||
}
|
||||
|
||||
// @router /api/db/:dbId/c-metadata [get]
|
||||
@@ -294,17 +310,18 @@ func (d *Db) ColumnMA(rc *ctx.ReqCtx) {
|
||||
biz.NotEmpty(tn, "tableName不能为空")
|
||||
|
||||
dbi := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx))
|
||||
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbi.ProjectId), "%s")
|
||||
rc.ResData = dbi.GetColumnMetadatas(tn)
|
||||
// biz.ErrIsNilAppendErr(d.TagApp.CanAccess(rc.LoginAccount.Id, dbInstance.TagPath), "%s")
|
||||
rc.ResData = dbi.GetMeta().GetColumns(tn)
|
||||
}
|
||||
|
||||
// @router /api/db/:dbId/hint-tables [get]
|
||||
func (d *Db) HintTables(rc *ctx.ReqCtx) {
|
||||
dbi := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx))
|
||||
biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbi.ProjectId), "%s")
|
||||
// 获取所有表
|
||||
tables := dbi.GetTableMetedatas()
|
||||
// biz.ErrIsNilAppendErr(d.TagApp.CanAccess(rc.LoginAccount.Id, dbInstance.TagPath), "%s")
|
||||
|
||||
dm := dbi.GetMeta()
|
||||
// 获取所有表
|
||||
tables := dm.GetTables()
|
||||
tableNames := make([]string, 0)
|
||||
for _, v := range tables {
|
||||
tableNames = append(tableNames, v["tableName"].(string))
|
||||
@@ -319,7 +336,7 @@ func (d *Db) HintTables(rc *ctx.ReqCtx) {
|
||||
}
|
||||
|
||||
// 获取所有表下的所有列信息
|
||||
columnMds := dbi.GetColumnMetadatas(tableNames...)
|
||||
columnMds := dm.GetColumns(tableNames...)
|
||||
for _, v := range columnMds {
|
||||
tName := v["tableName"].(string)
|
||||
if res[tName] == nil {
|
||||
@@ -1,8 +1,8 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/devops/application"
|
||||
"mayfly-go/internal/devops/domain/entity"
|
||||
"mayfly-go/internal/db/application"
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/pkg/ctx"
|
||||
"mayfly-go/pkg/ginx"
|
||||
)
|
||||
33
server/internal/db/api/form/db.go
Normal file
33
server/internal/db/api/form/db.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package form
|
||||
|
||||
type DbForm struct {
|
||||
Id uint64
|
||||
Name string `binding:"required" json:"name"`
|
||||
Type string `binding:"required" json:"type"` // 类型,mysql oracle等
|
||||
Host string `binding:"required" json:"host"`
|
||||
Port int `binding:"required" json:"port"`
|
||||
Username string `binding:"required" json:"username"`
|
||||
Password string `json:"password"`
|
||||
Params string `json:"params"`
|
||||
Database string `json:"database"`
|
||||
Remark string `json:"remark"`
|
||||
TagId uint64 `json:"tagId"`
|
||||
TagPath string `json:"tagPath"`
|
||||
|
||||
EnableSshTunnel int8 `json:"enableSshTunnel"`
|
||||
SshTunnelMachineId uint64 `json:"sshTunnelMachineId"`
|
||||
}
|
||||
|
||||
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"` //数据库名
|
||||
Sql string `binding:"required" json:"sql"` // 执行sql
|
||||
Remark string `json:"remark"` // 执行备注
|
||||
}
|
||||
@@ -12,10 +12,9 @@ type SelectDataDbVO struct {
|
||||
Params *string `json:"params"`
|
||||
Database *string `json:"database"`
|
||||
Username *string `json:"username"`
|
||||
ProjectId *int64 `json:"projectId"`
|
||||
Project *string `json:"project"`
|
||||
Env *string `json:"env"`
|
||||
EnvId *int64 `json:"envId"`
|
||||
Remark *string `json:"remark"`
|
||||
TagId *int64 `json:"tagId"`
|
||||
TagPath *string `json:"tagPath"`
|
||||
CreateTime *time.Time `json:"createTime"`
|
||||
Creator *string `json:"creator"`
|
||||
CreatorId *int64 `json:"creatorId"`
|
||||
16
server/internal/db/application/application.go
Normal file
16
server/internal/db/application/application.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package application
|
||||
|
||||
import "mayfly-go/internal/db/infrastructure/persistence"
|
||||
|
||||
var (
|
||||
dbApp Db = newDbApp(persistence.GetDbRepo(), persistence.GetDbSqlRepo())
|
||||
dbSqlExecApp DbSqlExec = newDbSqlExecApp(persistence.GetDbSqlExecRepo())
|
||||
)
|
||||
|
||||
func GetDbApp() Db {
|
||||
return dbApp
|
||||
}
|
||||
|
||||
func GetDbSqlExecApp() DbSqlExec {
|
||||
return dbSqlExecApp
|
||||
}
|
||||
521
server/internal/db/application/db.go
Normal file
521
server/internal/db/application/db.go
Normal file
@@ -0,0 +1,521 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"mayfly-go/internal/constant"
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/internal/db/domain/repository"
|
||||
machineapp "mayfly-go/internal/machine/application"
|
||||
"mayfly-go/internal/machine/infrastructure/machine"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/utils"
|
||||
"net"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
type Db interface {
|
||||
// 分页获取
|
||||
GetPageList(condition *entity.DbQuery, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult
|
||||
|
||||
Count(condition *entity.DbQuery) int64
|
||||
|
||||
// 根据条件获取
|
||||
GetDbBy(condition *entity.Db, cols ...string) error
|
||||
|
||||
// 根据id获取
|
||||
GetById(id uint64, cols ...string) *entity.Db
|
||||
|
||||
Save(entity *entity.Db)
|
||||
|
||||
// 删除数据库信息
|
||||
Delete(id uint64)
|
||||
|
||||
// 获取数据库连接实例
|
||||
// @param id 数据库实例id
|
||||
// @param db 数据库
|
||||
GetDbInstance(id uint64, db string) *DbInstance
|
||||
|
||||
// 获取数据库实例的所有数据库列表
|
||||
GetDatabases(entity *entity.Db) []string
|
||||
}
|
||||
|
||||
func newDbApp(dbRepo repository.Db, dbSqlRepo repository.DbSql) Db {
|
||||
return &dbAppImpl{
|
||||
dbRepo: dbRepo,
|
||||
dbSqlRepo: dbSqlRepo,
|
||||
}
|
||||
}
|
||||
|
||||
type dbAppImpl struct {
|
||||
dbRepo repository.Db
|
||||
dbSqlRepo repository.DbSql
|
||||
}
|
||||
|
||||
// 分页获取数据库信息列表
|
||||
func (d *dbAppImpl) GetPageList(condition *entity.DbQuery, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult {
|
||||
return d.dbRepo.GetDbList(condition, pageParam, toEntity, orderBy...)
|
||||
}
|
||||
|
||||
func (d *dbAppImpl) Count(condition *entity.DbQuery) int64 {
|
||||
return d.dbRepo.Count(condition)
|
||||
}
|
||||
|
||||
// 根据条件获取
|
||||
func (d *dbAppImpl) GetDbBy(condition *entity.Db, cols ...string) error {
|
||||
return d.dbRepo.GetDb(condition, cols...)
|
||||
}
|
||||
|
||||
// 根据id获取
|
||||
func (d *dbAppImpl) GetById(id uint64, cols ...string) *entity.Db {
|
||||
return d.dbRepo.GetById(id, cols...)
|
||||
}
|
||||
|
||||
func (d *dbAppImpl) Save(dbEntity *entity.Db) {
|
||||
// 默认tcp连接
|
||||
dbEntity.Network = dbEntity.GetNetwork()
|
||||
|
||||
// 测试连接
|
||||
if dbEntity.Password != "" {
|
||||
TestConnection(dbEntity)
|
||||
}
|
||||
|
||||
// 查找是否存在该库
|
||||
oldDb := &entity.Db{Host: dbEntity.Host, Port: dbEntity.Port, TagId: dbEntity.TagId}
|
||||
err := d.GetDbBy(oldDb)
|
||||
|
||||
if dbEntity.Id == 0 {
|
||||
biz.NotEmpty(dbEntity.Password, "密码不能为空")
|
||||
biz.IsTrue(err != nil, "该数据库实例已存在")
|
||||
dbEntity.PwdEncrypt()
|
||||
d.dbRepo.Insert(dbEntity)
|
||||
return
|
||||
}
|
||||
|
||||
// 如果存在该库,则校验修改的库是否为该库
|
||||
if err == nil {
|
||||
biz.IsTrue(oldDb.Id == dbEntity.Id, "该数据库实例已存在")
|
||||
}
|
||||
|
||||
dbId := dbEntity.Id
|
||||
old := d.GetById(dbId)
|
||||
|
||||
var oldDbs []interface{}
|
||||
for _, v := range strings.Split(old.Database, " ") {
|
||||
// 关闭数据库连接
|
||||
CloseDb(dbEntity.Id, v)
|
||||
oldDbs = append(oldDbs, v)
|
||||
}
|
||||
|
||||
var newDbs []interface{}
|
||||
for _, v := range strings.Split(dbEntity.Database, " ") {
|
||||
newDbs = append(newDbs, v)
|
||||
}
|
||||
// 比较新旧数据库列表,需要将移除的数据库相关联的信息删除
|
||||
_, delDb, _ := utils.ArrayCompare(newDbs, oldDbs, func(i1, i2 interface{}) bool {
|
||||
return i1.(string) == i2.(string)
|
||||
})
|
||||
for _, v := range delDb {
|
||||
// 删除该库关联的所有sql记录
|
||||
d.dbSqlRepo.DeleteBy(&entity.DbSql{DbId: dbId, Db: v.(string)})
|
||||
}
|
||||
|
||||
dbEntity.PwdEncrypt()
|
||||
d.dbRepo.Update(dbEntity)
|
||||
}
|
||||
|
||||
func (d *dbAppImpl) Delete(id uint64) {
|
||||
db := d.GetById(id)
|
||||
dbs := strings.Split(db.Database, " ")
|
||||
for _, v := range dbs {
|
||||
// 关闭连接
|
||||
CloseDb(id, v)
|
||||
}
|
||||
d.dbRepo.Delete(id)
|
||||
// 删除该库下用户保存的所有sql信息
|
||||
d.dbSqlRepo.DeleteBy(&entity.DbSql{DbId: id})
|
||||
}
|
||||
|
||||
func (d *dbAppImpl) GetDatabases(ed *entity.Db) []string {
|
||||
ed.Network = ed.GetNetwork()
|
||||
databases := make([]string, 0)
|
||||
var dbConn *sql.DB
|
||||
var metaDb string
|
||||
var getDatabasesSql string
|
||||
if ed.Type == entity.DbTypeMysql {
|
||||
metaDb = "information_schema"
|
||||
getDatabasesSql = "SELECT SCHEMA_NAME AS dbname FROM SCHEMATA"
|
||||
} else {
|
||||
metaDb = "postgres"
|
||||
getDatabasesSql = "SELECT datname AS dbname FROM pg_database"
|
||||
}
|
||||
|
||||
dbConn, err := GetDbConn(ed, metaDb)
|
||||
biz.ErrIsNilAppendErr(err, "数据库连接失败: %s")
|
||||
defer dbConn.Close()
|
||||
|
||||
_, res, err := SelectDataByDb(dbConn, getDatabasesSql, true)
|
||||
biz.ErrIsNilAppendErr(err, "获取数据库列表失败")
|
||||
for _, re := range res {
|
||||
databases = append(databases, re["dbname"].(string))
|
||||
}
|
||||
return databases
|
||||
}
|
||||
|
||||
var mutex sync.Mutex
|
||||
|
||||
func (da *dbAppImpl) GetDbInstance(id uint64, db string) *DbInstance {
|
||||
// Id不为0,则为需要缓存
|
||||
needCache := id != 0
|
||||
if needCache {
|
||||
load, ok := dbCache.Get(GetDbCacheKey(id, db))
|
||||
if ok {
|
||||
return load.(*DbInstance)
|
||||
}
|
||||
}
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
|
||||
d := da.GetById(id)
|
||||
// 密码解密
|
||||
d.PwdDecrypt()
|
||||
biz.NotNil(d, "数据库信息不存在")
|
||||
biz.IsTrue(strings.Contains(d.Database, db), "未配置该库的操作权限")
|
||||
|
||||
cacheKey := GetDbCacheKey(id, db)
|
||||
dbi := &DbInstance{Id: cacheKey, Type: d.Type, TagPath: d.TagPath, sshTunnelMachineId: d.SshTunnelMachineId}
|
||||
|
||||
DB, err := GetDbConn(d, db)
|
||||
if err != nil {
|
||||
dbi.Close()
|
||||
global.Log.Errorf("连接db失败: %s:%d/%s", d.Host, d.Port, db)
|
||||
panic(biz.NewBizErr(fmt.Sprintf("数据库连接失败: %s", err.Error())))
|
||||
}
|
||||
|
||||
// 最大连接周期,超过时间的连接就close
|
||||
// DB.SetConnMaxLifetime(100 * time.Second)
|
||||
// 设置最大连接数
|
||||
DB.SetMaxOpenConns(5)
|
||||
// 设置闲置连接数
|
||||
DB.SetMaxIdleConns(1)
|
||||
|
||||
dbi.db = DB
|
||||
global.Log.Infof("连接db: %s:%d/%s", d.Host, d.Port, db)
|
||||
if needCache {
|
||||
dbCache.Put(cacheKey, dbi)
|
||||
}
|
||||
return dbi
|
||||
}
|
||||
|
||||
//---------------------------------------- db instance ------------------------------------
|
||||
|
||||
// db实例
|
||||
type DbInstance struct {
|
||||
Id string
|
||||
Type string
|
||||
TagPath string
|
||||
db *sql.DB
|
||||
sshTunnelMachineId uint64
|
||||
}
|
||||
|
||||
// 执行查询语句
|
||||
// 依次返回 列名数组,结果map,错误
|
||||
func (d *DbInstance) SelectData(execSql string) ([]string, []map[string]interface{}, error) {
|
||||
return SelectDataByDb(d.db, execSql, false)
|
||||
}
|
||||
|
||||
// 将查询结果映射至struct,可具体参考sqlx库
|
||||
func (d *DbInstance) SelectData2Struct(execSql string, dest interface{}) error {
|
||||
return Select2StructByDb(d.db, execSql, dest)
|
||||
}
|
||||
|
||||
// 执行内部查询语句,不返回列名以及不限制行数
|
||||
// 依次返回 结果map,错误
|
||||
func (d *DbInstance) innerSelect(execSql string) ([]map[string]interface{}, error) {
|
||||
_, res, err := SelectDataByDb(d.db, execSql, true)
|
||||
return res, err
|
||||
}
|
||||
|
||||
// 执行 update, insert, delete,建表等sql
|
||||
// 返回影响条数和错误
|
||||
func (d *DbInstance) Exec(sql string) (int64, error) {
|
||||
res, err := d.db.Exec(sql)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// 获取数据库元信息实现接口
|
||||
func (di *DbInstance) GetMeta() DbMetadata {
|
||||
dbType := di.Type
|
||||
if dbType == entity.DbTypeMysql {
|
||||
return &MysqlMetadata{di: di}
|
||||
}
|
||||
if dbType == entity.DbTypePostgres {
|
||||
return &PgsqlMetadata{di: di}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 关闭连接
|
||||
func (d *DbInstance) Close() {
|
||||
if d.db != nil {
|
||||
if err := d.db.Close(); err != nil {
|
||||
global.Log.Errorf("关闭数据库实例[%s]连接失败: %s", d.Id, err.Error())
|
||||
}
|
||||
d.db = nil
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// 单次最大查询数据集
|
||||
const Max_Rows = 2000
|
||||
|
||||
// 客户端连接缓存,指定时间内没有访问则会被关闭, key为数据库实例id:数据库
|
||||
var dbCache = cache.NewTimedCache(constant.DbConnExpireTime, 5*time.Second).
|
||||
WithUpdateAccessTime(true).
|
||||
OnEvicted(func(key interface{}, value interface{}) {
|
||||
global.Log.Info(fmt.Sprintf("删除db连接缓存 id = %s", key))
|
||||
value.(*DbInstance).Close()
|
||||
})
|
||||
|
||||
func init() {
|
||||
machine.AddCheckSshTunnelMachineUseFunc(func(machineId uint64) bool {
|
||||
// 遍历所有db连接实例,若存在db实例使用该ssh隧道机器,则返回true,表示还在使用中...
|
||||
items := dbCache.Items()
|
||||
for _, v := range items {
|
||||
if v.Value.(*DbInstance).sshTunnelMachineId == machineId {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func GetDbCacheKey(dbId uint64, db string) string {
|
||||
return fmt.Sprintf("%d:%s", dbId, db)
|
||||
}
|
||||
|
||||
func GetDbInstanceByCache(id string) *DbInstance {
|
||||
if load, ok := dbCache.Get(id); ok {
|
||||
return load.(*DbInstance)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestConnection(d *entity.Db) {
|
||||
// 验证第一个库是否可以连接即可
|
||||
DB, err := GetDbConn(d, strings.Split(d.Database, " ")[0])
|
||||
biz.ErrIsNilAppendErr(err, "数据库连接失败: %s")
|
||||
defer DB.Close()
|
||||
}
|
||||
|
||||
// 获取数据库连接
|
||||
func GetDbConn(d *entity.Db, db string) (*sql.DB, error) {
|
||||
// SSH Conect
|
||||
if d.EnableSshTunnel == 1 && d.SshTunnelMachineId != 0 {
|
||||
sshTunnelMachine := machineapp.GetMachineApp().GetSshTunnelMachine(d.SshTunnelMachineId)
|
||||
if d.Type == entity.DbTypeMysql {
|
||||
mysql.RegisterDialContext(d.Network, func(ctx context.Context, addr string) (net.Conn, error) {
|
||||
return sshTunnelMachine.GetDialConn("tcp", addr)
|
||||
})
|
||||
} else if d.Type == entity.DbTypePostgres {
|
||||
_, err := pq.DialOpen(&PqSqlDialer{sshTunnelMachine: sshTunnelMachine}, getDsn(d, db))
|
||||
if err != nil {
|
||||
panic(biz.NewBizErr(fmt.Sprintf("postgres隧道连接失败: %s", err.Error())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DB, err := sql.Open(d.Type, getDsn(d, db))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = DB.Ping()
|
||||
if err != nil {
|
||||
DB.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return DB, nil
|
||||
}
|
||||
|
||||
// 获取dataSourceName
|
||||
func getDsn(d *entity.Db, db string) string {
|
||||
var dsn string
|
||||
if d.Type == entity.DbTypeMysql {
|
||||
dsn = fmt.Sprintf("%s:%s@%s(%s:%d)/%s?timeout=8s", d.Username, d.Password, d.Network, d.Host, d.Port, db)
|
||||
if d.Params != "" {
|
||||
dsn = fmt.Sprintf("%s&%s", dsn, d.Params)
|
||||
}
|
||||
return dsn
|
||||
}
|
||||
|
||||
if d.Type == entity.DbTypePostgres {
|
||||
dsn = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", d.Host, d.Port, d.Username, d.Password, db)
|
||||
if d.Params != "" {
|
||||
dsn = fmt.Sprintf("%s %s", dsn, strings.Join(strings.Split(d.Params, "&"), " "))
|
||||
}
|
||||
return dsn
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func SelectDataByDb(db *sql.DB, selectSql string, isInner bool) ([]string, []map[string]interface{}, error) {
|
||||
rows, err := db.Query(selectSql)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// rows对象一定要close掉,如果出错,不关掉则会很迅速的达到设置最大连接数,
|
||||
// 后面的链接过来直接报错或拒绝,实际上也没有起效果
|
||||
defer func() {
|
||||
if rows != nil {
|
||||
rows.Close()
|
||||
}
|
||||
}()
|
||||
colTypes, _ := rows.ColumnTypes()
|
||||
// 这里表示一行填充数据
|
||||
scans := make([]interface{}, len(colTypes))
|
||||
// 这里表示一行所有列的值,用[]byte表示
|
||||
vals := make([][]byte, len(colTypes))
|
||||
// 这里scans引用vals,把数据填充到[]byte里
|
||||
for k := range vals {
|
||||
scans[k] = &vals[k]
|
||||
}
|
||||
|
||||
result := make([]map[string]interface{}, 0)
|
||||
// 列名用于前端表头名称按照数据库与查询字段顺序显示
|
||||
colNames := make([]string, 0)
|
||||
// 是否第一次遍历,列名数组只需第一次遍历时加入
|
||||
isFirst := true
|
||||
rowNum := 0
|
||||
for rows.Next() {
|
||||
rowNum++
|
||||
// 非内部sql,则校验返回结果数量
|
||||
if !isInner {
|
||||
biz.IsTrue(rowNum <= Max_Rows, "结果集 > 2000, 请完善条件或分页信息")
|
||||
}
|
||||
|
||||
// 不Scan也会导致等待,该链接实际处于未工作的状态,然后也会导致连接数迅速达到最大
|
||||
err := rows.Scan(scans...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// 每行数据
|
||||
rowData := make(map[string]interface{})
|
||||
// 把vals中的数据复制到row中
|
||||
for i, v := range vals {
|
||||
colType := colTypes[i]
|
||||
colName := colType.Name()
|
||||
// 如果是第一行,则将列名加入到列信息中,由于map是无序的,所有需要返回列名的有序数组
|
||||
if isFirst {
|
||||
colNames = append(colNames, colName)
|
||||
}
|
||||
rowData[colName] = valueConvert(v, colType)
|
||||
}
|
||||
// 放入结果集
|
||||
result = append(result, rowData)
|
||||
isFirst = false
|
||||
}
|
||||
return colNames, result, nil
|
||||
}
|
||||
|
||||
// 将查询的值转为对应列类型的实际值,不全部转为字符串
|
||||
func valueConvert(data []byte, colType *sql.ColumnType) interface{} {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
// 列的数据库类型名
|
||||
colDatabaseTypeName := strings.ToLower(colType.DatabaseTypeName())
|
||||
|
||||
// 如果类型是bit,则直接返回第一个字节即可
|
||||
if strings.Contains(colDatabaseTypeName, "bit") {
|
||||
return data[0]
|
||||
}
|
||||
|
||||
// 这里把[]byte数据转成string
|
||||
stringV := string(data)
|
||||
if stringV == "" {
|
||||
return ""
|
||||
}
|
||||
colScanType := strings.ToLower(colType.ScanType().Name())
|
||||
|
||||
if strings.Contains(colScanType, "int") {
|
||||
// 如果长度超过16位,则返回字符串,因为前端js长度大于16会丢失精度
|
||||
if len(stringV) > 16 {
|
||||
return stringV
|
||||
}
|
||||
intV, _ := strconv.Atoi(stringV)
|
||||
switch colType.ScanType().Kind() {
|
||||
case reflect.Int8:
|
||||
return int8(intV)
|
||||
case reflect.Uint8:
|
||||
return uint8(intV)
|
||||
case reflect.Int64:
|
||||
return int64(intV)
|
||||
case reflect.Uint64:
|
||||
return uint64(intV)
|
||||
case reflect.Uint:
|
||||
return uint(intV)
|
||||
default:
|
||||
return intV
|
||||
}
|
||||
}
|
||||
if strings.Contains(colScanType, "float") {
|
||||
floatV, _ := strconv.ParseFloat(stringV, 64)
|
||||
return floatV
|
||||
}
|
||||
|
||||
return stringV
|
||||
}
|
||||
|
||||
// 查询数据结果映射至struct。可参考sqlx库
|
||||
func Select2StructByDb(db *sql.DB, selectSql string, dest interface{}) error {
|
||||
rows, err := db.Query(selectSql)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// rows对象一定要close掉,如果出错,不关掉则会很迅速的达到设置最大连接数,
|
||||
// 后面的链接过来直接报错或拒绝,实际上也没有起效果
|
||||
defer func() {
|
||||
if rows != nil {
|
||||
rows.Close()
|
||||
}
|
||||
}()
|
||||
return scanAll(rows, dest, false)
|
||||
}
|
||||
|
||||
// 删除db缓存并关闭该数据库所有连接
|
||||
func CloseDb(dbId uint64, db string) {
|
||||
dbCache.Delete(GetDbCacheKey(dbId, db))
|
||||
}
|
||||
|
||||
type PqSqlDialer struct {
|
||||
sshTunnelMachine *machine.SshTunnelMachine
|
||||
}
|
||||
|
||||
func (pd *PqSqlDialer) Dial(network, address string) (net.Conn, error) {
|
||||
if sshConn, err := pd.sshTunnelMachine.GetDialConn("tcp", address); err == nil {
|
||||
// 将ssh conn包装,否则redis内部设置超时会报错,ssh conn不支持设置超时会返回错误: ssh: tcpChan: deadline not supported
|
||||
return &utils.WrapSshConn{Conn: sshConn}, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (pd *PqSqlDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) {
|
||||
return pd.Dial(network, address)
|
||||
}
|
||||
200
server/internal/db/application/db_sql_exec.go
Normal file
200
server/internal/db/application/db_sql_exec.go
Normal file
@@ -0,0 +1,200 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/internal/db/domain/repository"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/model"
|
||||
"strings"
|
||||
|
||||
"github.com/xwb1989/sqlparser"
|
||||
)
|
||||
|
||||
type DbSqlExecReq struct {
|
||||
DbId uint64
|
||||
Db string
|
||||
Sql string
|
||||
Remark string
|
||||
LoginAccount *model.LoginAccount
|
||||
DbInstance *DbInstance
|
||||
}
|
||||
|
||||
type DbSqlExecRes struct {
|
||||
ColNames []string
|
||||
Res []map[string]interface{}
|
||||
}
|
||||
|
||||
type DbSqlExec interface {
|
||||
// 执行sql
|
||||
Exec(execSqlReq *DbSqlExecReq) (*DbSqlExecRes, error)
|
||||
|
||||
// 根据条件删除sql执行记录
|
||||
DeleteBy(condition *entity.DbSqlExec)
|
||||
|
||||
// 分页获取
|
||||
GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult
|
||||
}
|
||||
|
||||
func newDbSqlExecApp(dbExecSqlRepo repository.DbSqlExec) DbSqlExec {
|
||||
return &dbSqlExecAppImpl{
|
||||
dbSqlExecRepo: dbExecSqlRepo,
|
||||
}
|
||||
}
|
||||
|
||||
type dbSqlExecAppImpl struct {
|
||||
dbSqlExecRepo repository.DbSqlExec
|
||||
}
|
||||
|
||||
func (d *dbSqlExecAppImpl) Exec(execSqlReq *DbSqlExecReq) (*DbSqlExecRes, error) {
|
||||
sql := execSqlReq.Sql
|
||||
loginAccount := execSqlReq.LoginAccount
|
||||
|
||||
// 如果是pgsql并且为查询语句,则直接返回,sqlparser不支持解析pgsql select语句
|
||||
if execSqlReq.DbInstance.Type == entity.DbTypePostgres && (strings.HasPrefix(sql, "SELECT") || strings.HasPrefix(sql, "select")) {
|
||||
return doSelect(nil, execSqlReq, nil)
|
||||
}
|
||||
|
||||
stmt, err := sqlparser.Parse(sql)
|
||||
if err != nil {
|
||||
global.Log.Error("sql解析失败: ", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dbSqlExecRecord := new(entity.DbSqlExec)
|
||||
dbSqlExecRecord.DbId = execSqlReq.DbId
|
||||
dbSqlExecRecord.Db = execSqlReq.Db
|
||||
dbSqlExecRecord.Sql = sql
|
||||
dbSqlExecRecord.Remark = execSqlReq.Remark
|
||||
dbSqlExecRecord.SetBaseInfo(loginAccount)
|
||||
|
||||
var execRes *DbSqlExecRes
|
||||
isSelect := false
|
||||
switch stmt := stmt.(type) {
|
||||
case *sqlparser.Select:
|
||||
isSelect = true
|
||||
execRes, err = doSelect(stmt, execSqlReq, dbSqlExecRecord)
|
||||
case *sqlparser.Show:
|
||||
isSelect = true
|
||||
execRes, err = doSelect(nil, execSqlReq, dbSqlExecRecord)
|
||||
case *sqlparser.OtherRead:
|
||||
isSelect = true
|
||||
execRes, err = doSelect(nil, execSqlReq, dbSqlExecRecord)
|
||||
case *sqlparser.Update:
|
||||
execRes, err = doUpdate(stmt, execSqlReq, dbSqlExecRecord)
|
||||
case *sqlparser.Delete:
|
||||
execRes, err = doDelete(stmt, execSqlReq, dbSqlExecRecord)
|
||||
case *sqlparser.Insert:
|
||||
execRes, err = doInsert(stmt, execSqlReq, dbSqlExecRecord)
|
||||
default:
|
||||
execRes, err = doExec(execSqlReq.Sql, execSqlReq.DbInstance)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !isSelect {
|
||||
// 保存执行记录
|
||||
d.dbSqlExecRepo.Insert(dbSqlExecRecord)
|
||||
}
|
||||
return execRes, nil
|
||||
}
|
||||
|
||||
func (d *dbSqlExecAppImpl) DeleteBy(condition *entity.DbSqlExec) {
|
||||
d.dbSqlExecRepo.DeleteBy(condition)
|
||||
}
|
||||
|
||||
func (d *dbSqlExecAppImpl) GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult {
|
||||
return d.dbSqlExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
|
||||
}
|
||||
|
||||
func doSelect(selectStmt *sqlparser.Select, execSqlReq *DbSqlExecReq, dbSqlExec *entity.DbSqlExec) (*DbSqlExecRes, error) {
|
||||
dbInstance := execSqlReq.DbInstance
|
||||
sql := execSqlReq.Sql
|
||||
colNames, res, err := dbInstance.SelectData(sql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &DbSqlExecRes{
|
||||
ColNames: colNames,
|
||||
Res: res,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func doUpdate(update *sqlparser.Update, execSqlReq *DbSqlExecReq, dbSqlExec *entity.DbSqlExec) (*DbSqlExecRes, error) {
|
||||
dbInstance := execSqlReq.DbInstance
|
||||
|
||||
tableStr := sqlparser.String(update.TableExprs)
|
||||
// 可能使用别名,故空格切割
|
||||
tableName := strings.Split(tableStr, " ")[0]
|
||||
where := sqlparser.String(update.Where)
|
||||
|
||||
updateExprs := update.Exprs
|
||||
updateColumns := make([]string, 0)
|
||||
for _, v := range updateExprs {
|
||||
updateColumns = append(updateColumns, v.Name.Name.String())
|
||||
}
|
||||
|
||||
// 获取表主键列名,排除使用别名
|
||||
primaryKey := dbInstance.GetMeta().GetPrimaryKey(tableName)
|
||||
|
||||
updateColumnsAndPrimaryKey := strings.Join(updateColumns, ",") + "," + primaryKey
|
||||
// 查询要更新字段数据的旧值,以及主键值
|
||||
selectSql := fmt.Sprintf("SELECT %s FROM %s %s LIMIT 200", updateColumnsAndPrimaryKey, tableStr, where)
|
||||
_, res, _ := dbInstance.SelectData(selectSql)
|
||||
|
||||
bytes, _ := json.Marshal(res)
|
||||
dbSqlExec.OldValue = string(bytes)
|
||||
dbSqlExec.Table = tableName
|
||||
dbSqlExec.Type = entity.DbSqlExecTypeUpdate
|
||||
|
||||
return doExec(execSqlReq.Sql, dbInstance)
|
||||
}
|
||||
|
||||
func doDelete(delete *sqlparser.Delete, execSqlReq *DbSqlExecReq, dbSqlExec *entity.DbSqlExec) (*DbSqlExecRes, error) {
|
||||
dbInstance := execSqlReq.DbInstance
|
||||
|
||||
tableStr := sqlparser.String(delete.TableExprs)
|
||||
// 可能使用别名,故空格切割
|
||||
table := strings.Split(tableStr, " ")[0]
|
||||
where := sqlparser.String(delete.Where)
|
||||
|
||||
// 查询删除数据
|
||||
selectSql := fmt.Sprintf("SELECT * FROM %s %s LIMIT 200", tableStr, where)
|
||||
_, res, _ := dbInstance.SelectData(selectSql)
|
||||
|
||||
bytes, _ := json.Marshal(res)
|
||||
dbSqlExec.OldValue = string(bytes)
|
||||
dbSqlExec.Table = table
|
||||
dbSqlExec.Type = entity.DbSqlExecTypeDelete
|
||||
|
||||
return doExec(execSqlReq.Sql, dbInstance)
|
||||
}
|
||||
|
||||
func doInsert(insert *sqlparser.Insert, execSqlReq *DbSqlExecReq, dbSqlExec *entity.DbSqlExec) (*DbSqlExecRes, error) {
|
||||
tableStr := sqlparser.String(insert.Table)
|
||||
// 可能使用别名,故空格切割
|
||||
table := strings.Split(tableStr, " ")[0]
|
||||
dbSqlExec.Table = table
|
||||
dbSqlExec.Type = entity.DbSqlExecTypeInsert
|
||||
|
||||
return doExec(execSqlReq.Sql, execSqlReq.DbInstance)
|
||||
}
|
||||
|
||||
func doExec(sql string, dbInstance *DbInstance) (*DbSqlExecRes, error) {
|
||||
rowsAffected, err := dbInstance.Exec(sql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res := make([]map[string]interface{}, 0)
|
||||
resData := make(map[string]interface{})
|
||||
resData["影响条数"] = rowsAffected
|
||||
res = append(res, resData)
|
||||
|
||||
return &DbSqlExecRes{
|
||||
ColNames: []string{"影响条数"},
|
||||
Res: res,
|
||||
}, nil
|
||||
}
|
||||
28
server/internal/db/application/meta.go
Normal file
28
server/internal/db/application/meta.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package application
|
||||
|
||||
// -----------------------------------元数据接口定义------------------------------------------
|
||||
// 数据库元信息接口(表、列等元信息)
|
||||
// 所有数据查出来直接用map接收,注意不同数据库实现该接口返回的map中的key需要统一.
|
||||
// 即: 使用别名统一即可。如table_name AS tableName
|
||||
type DbMetadata interface {
|
||||
|
||||
// 获取表基础元信息
|
||||
// 表名: tableName, 备注: tableComment
|
||||
GetTables() []map[string]interface{}
|
||||
|
||||
// 获取指定表名的所有列元信息
|
||||
// 表名: tableName, 列名: columnName, 列类型: columnType, 备注: columnComment, 是否可为null: nullable, 其他信息: extra
|
||||
GetColumns(tableNames ...string) []map[string]interface{}
|
||||
|
||||
// 获取表主键字段名,目前默认第一个字段
|
||||
GetPrimaryKey(tablename string) string
|
||||
|
||||
// 获取表信息,比GetTables获取更详细的表信息
|
||||
GetTableInfos() []map[string]interface{}
|
||||
|
||||
// 获取表索引信息
|
||||
GetTableIndex(tableName string) []map[string]interface{}
|
||||
|
||||
// 获取建表ddl
|
||||
GetCreateTableDdl(tableName string) []map[string]interface{}
|
||||
}
|
||||
83
server/internal/db/application/mysql_meta.go
Normal file
83
server/internal/db/application/mysql_meta.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mayfly-go/pkg/biz"
|
||||
)
|
||||
|
||||
// ---------------------------------- mysql元数据 -----------------------------------
|
||||
const (
|
||||
// mysql 表信息元数据
|
||||
MYSQL_TABLE_MA = `SELECT table_name tableName, table_comment tableComment from information_schema.tables WHERE table_schema = (SELECT database())`
|
||||
|
||||
// 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())`
|
||||
|
||||
// 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'`
|
||||
|
||||
// mysql 列信息元数据
|
||||
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_schema = (SELECT database()) AND table_name in (%s) ORDER BY tableName, ordinal_position`
|
||||
)
|
||||
|
||||
type MysqlMetadata struct {
|
||||
di *DbInstance
|
||||
}
|
||||
|
||||
// 获取表基础元信息, 如表名等
|
||||
func (mm *MysqlMetadata) GetTables() []map[string]interface{} {
|
||||
res, err := mm.di.innerSelect(MYSQL_TABLE_MA)
|
||||
biz.ErrIsNilAppendErr(err, "获取表基本信息失败: %s")
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取列元信息, 如列名等
|
||||
func (mm *MysqlMetadata) GetColumns(tableNames ...string) []map[string]interface{} {
|
||||
tableName := ""
|
||||
for i := 0; i < len(tableNames); i++ {
|
||||
if i != 0 {
|
||||
tableName = tableName + ", "
|
||||
}
|
||||
tableName = tableName + "'" + tableNames[i] + "'"
|
||||
}
|
||||
result, err := mm.di.innerSelect(fmt.Sprintf(MYSQL_COLUMN_MA, tableName))
|
||||
biz.ErrIsNilAppendErr(err, "获取数据库列信息失败: %s")
|
||||
return result
|
||||
}
|
||||
|
||||
// 获取表主键字段名,默认第一个字段
|
||||
func (mm *MysqlMetadata) GetPrimaryKey(tablename string) string {
|
||||
columns := mm.GetColumns(tablename)
|
||||
if len(columns) == 0 {
|
||||
panic(biz.NewBizErr(fmt.Sprintf("[%s] 表不存在", tablename)))
|
||||
}
|
||||
return columns[0]["columnName"].(string)
|
||||
}
|
||||
|
||||
// 获取表信息,比GetTableMetedatas获取更详细的表信息
|
||||
func (mm *MysqlMetadata) GetTableInfos() []map[string]interface{} {
|
||||
res, err := mm.di.innerSelect(MYSQL_TABLE_INFO)
|
||||
biz.ErrIsNilAppendErr(err, "获取表信息失败: %s")
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取表索引信息
|
||||
func (mm *MysqlMetadata) GetTableIndex(tableName string) []map[string]interface{} {
|
||||
res, err := mm.di.innerSelect(fmt.Sprintf(MYSQL_INDEX_INFO, tableName))
|
||||
biz.ErrIsNilAppendErr(err, "获取表索引信息失败: %s")
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取建表ddl
|
||||
func (mm *MysqlMetadata) GetCreateTableDdl(tableName string) []map[string]interface{} {
|
||||
res, _ := mm.di.innerSelect(fmt.Sprintf("show create table %s ", tableName))
|
||||
return res
|
||||
}
|
||||
95
server/internal/db/application/pgsql_meta.go
Normal file
95
server/internal/db/application/pgsql_meta.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mayfly-go/pkg/biz"
|
||||
)
|
||||
|
||||
// ---------------------------------- pgsql元数据 -----------------------------------
|
||||
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",
|
||||
tc.is_nullable AS "nullable",
|
||||
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
|
||||
JOIN information_schema.columns tc ON tc.column_name = a.attname AND tc.table_name = C.relname AND tc.table_schema = pn.nspname
|
||||
WHERE
|
||||
A.attnum >= 0
|
||||
AND pn.nspname = (select current_schema())
|
||||
AND C.relname in (%s)
|
||||
ORDER BY
|
||||
C.relname DESC,
|
||||
A.attnum ASC
|
||||
`
|
||||
)
|
||||
|
||||
type PgsqlMetadata struct {
|
||||
di *DbInstance
|
||||
}
|
||||
|
||||
// 获取表基础元信息, 如表名等
|
||||
func (pm *PgsqlMetadata) GetTables() []map[string]interface{} {
|
||||
res, err := pm.di.innerSelect(PGSQL_TABLE_MA)
|
||||
biz.ErrIsNilAppendErr(err, "获取表基本信息失败: %s")
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取列元信息, 如列名等
|
||||
func (pm *PgsqlMetadata) GetColumns(tableNames ...string) []map[string]interface{} {
|
||||
tableName := ""
|
||||
for i := 0; i < len(tableNames); i++ {
|
||||
if i != 0 {
|
||||
tableName = tableName + ", "
|
||||
}
|
||||
tableName = tableName + "'" + tableNames[i] + "'"
|
||||
}
|
||||
result, err := pm.di.innerSelect(fmt.Sprintf(PGSQL_COLUMN_MA, tableName))
|
||||
biz.ErrIsNilAppendErr(err, "获取数据库列信息失败: %s")
|
||||
return result
|
||||
}
|
||||
|
||||
// 获取表主键字段名,默认第一个字段
|
||||
func (pm *PgsqlMetadata) GetPrimaryKey(tablename string) string {
|
||||
columns := pm.GetColumns(tablename)
|
||||
if len(columns) == 0 {
|
||||
panic(biz.NewBizErr(fmt.Sprintf("[%s] 表不存在", tablename)))
|
||||
}
|
||||
return columns[0]["columnName"].(string)
|
||||
}
|
||||
|
||||
// 获取表信息,比GetTables获取更详细的表信息
|
||||
func (pm *PgsqlMetadata) GetTableInfos() []map[string]interface{} {
|
||||
res, err := pm.di.innerSelect(PGSQL_TABLE_INFO)
|
||||
biz.ErrIsNilAppendErr(err, "获取表信息失败: %s")
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取表索引信息
|
||||
func (pm *PgsqlMetadata) GetTableIndex(tableName string) []map[string]interface{} {
|
||||
res, err := pm.di.innerSelect(fmt.Sprintf(PGSQL_INDEX_INFO, tableName))
|
||||
biz.ErrIsNilAppendErr(err, "获取表索引信息失败: %s")
|
||||
return res
|
||||
}
|
||||
|
||||
// 获取建表ddl
|
||||
func (mm *PgsqlMetadata) GetCreateTableDdl(tableName string) []map[string]interface{} {
|
||||
biz.IsTrue(tableName == "", "暂不支持获取pgsql建表DDL")
|
||||
return nil
|
||||
}
|
||||
630
server/internal/db/application/sqlx.go
Normal file
630
server/internal/db/application/sqlx.go
Normal file
@@ -0,0 +1,630 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// 将结果scan至结构体,copy至 sqlx库: https://github.com/jmoiron/sqlx
|
||||
func scanAll(rows *sql.Rows, dest interface{}, structOnly bool) error {
|
||||
var v, vp reflect.Value
|
||||
|
||||
value := reflect.ValueOf(dest)
|
||||
|
||||
// json.Unmarshal returns errors for these
|
||||
if value.Kind() != reflect.Ptr {
|
||||
return errors.New("must pass a pointer, not a value, to StructScan destination")
|
||||
}
|
||||
if value.IsNil() {
|
||||
return errors.New("nil pointer passed to StructScan destination")
|
||||
}
|
||||
direct := reflect.Indirect(value)
|
||||
|
||||
slice, err := baseType(value.Type(), reflect.Slice)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
direct.SetLen(0)
|
||||
|
||||
isPtr := slice.Elem().Kind() == reflect.Ptr
|
||||
base := Deref(slice.Elem())
|
||||
scannable := isScannable(base)
|
||||
|
||||
if structOnly && scannable {
|
||||
return structOnlyError(base)
|
||||
}
|
||||
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// if it's a base type make sure it only has 1 column; if not return an error
|
||||
if scannable && len(columns) > 1 {
|
||||
return fmt.Errorf("non-struct dest type %s with >1 columns (%d)", base.Kind(), len(columns))
|
||||
}
|
||||
|
||||
if !scannable {
|
||||
var values []interface{}
|
||||
var m *Mapper = mapper()
|
||||
|
||||
fields := m.TraversalsByName(base, columns)
|
||||
// if we are not unsafe and are missing fields, return an error
|
||||
if f, err := missingFields(fields); err != nil {
|
||||
return fmt.Errorf("missing destination name %s in %T", columns[f], dest)
|
||||
}
|
||||
values = make([]interface{}, len(columns))
|
||||
|
||||
for rows.Next() {
|
||||
// create a new struct type (which returns PtrTo) and indirect it
|
||||
vp = reflect.New(base)
|
||||
v = reflect.Indirect(vp)
|
||||
|
||||
err = fieldsByTraversal(v, fields, values, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// scan into the struct field pointers and append to our results
|
||||
err = rows.Scan(values...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if isPtr {
|
||||
direct.Set(reflect.Append(direct, vp))
|
||||
} else {
|
||||
direct.Set(reflect.Append(direct, v))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for rows.Next() {
|
||||
vp = reflect.New(base)
|
||||
err = rows.Scan(vp.Interface())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// append
|
||||
if isPtr {
|
||||
direct.Set(reflect.Append(direct, vp))
|
||||
} else {
|
||||
direct.Set(reflect.Append(direct, reflect.Indirect(vp)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func baseType(t reflect.Type, expected reflect.Kind) (reflect.Type, error) {
|
||||
t = Deref(t)
|
||||
if t.Kind() != expected {
|
||||
return nil, fmt.Errorf("expected %s but got %s", expected, t.Kind())
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// structOnlyError returns an error appropriate for type when a non-scannable
|
||||
// struct is expected but something else is given
|
||||
func structOnlyError(t reflect.Type) error {
|
||||
isStruct := t.Kind() == reflect.Struct
|
||||
isScanner := reflect.PtrTo(t).Implements(_scannerInterface)
|
||||
if !isStruct {
|
||||
return fmt.Errorf("expected %s but got %s", reflect.Struct, t.Kind())
|
||||
}
|
||||
if isScanner {
|
||||
return fmt.Errorf("structscan expects a struct dest but the provided struct type %s implements scanner", t.Name())
|
||||
}
|
||||
return fmt.Errorf("expected a struct, but struct %s has no exported fields", t.Name())
|
||||
}
|
||||
|
||||
var _scannerInterface = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
|
||||
|
||||
func isScannable(t reflect.Type) bool {
|
||||
if reflect.PtrTo(t).Implements(_scannerInterface) {
|
||||
return true
|
||||
}
|
||||
if t.Kind() != reflect.Struct {
|
||||
return true
|
||||
}
|
||||
|
||||
// it's not important that we use the right mapper for this particular object,
|
||||
// we're only concerned on how many exported fields this struct has
|
||||
return len(mapper().TypeMap(t).Index) == 0
|
||||
}
|
||||
|
||||
var NameMapper = strings.ToLower
|
||||
var origMapper = reflect.ValueOf(NameMapper)
|
||||
|
||||
// Rather than creating on init, this is created when necessary so that
|
||||
// importers have time to customize the NameMapper.
|
||||
var mpr *Mapper
|
||||
|
||||
// mprMu protects mpr.
|
||||
var mprMu sync.Mutex
|
||||
|
||||
// mapper returns a valid mapper using the configured NameMapper func.
|
||||
func mapper() *Mapper {
|
||||
mprMu.Lock()
|
||||
defer mprMu.Unlock()
|
||||
|
||||
if mpr == nil {
|
||||
mpr = NewMapperFunc("db", NameMapper)
|
||||
} else if origMapper != reflect.ValueOf(NameMapper) {
|
||||
// if NameMapper has changed, create a new mapper
|
||||
mpr = NewMapperFunc("db", NameMapper)
|
||||
origMapper = reflect.ValueOf(NameMapper)
|
||||
}
|
||||
return mpr
|
||||
}
|
||||
|
||||
func missingFields(transversals [][]int) (field int, err error) {
|
||||
for i, t := range transversals {
|
||||
if len(t) == 0 {
|
||||
return i, errors.New("missing field")
|
||||
}
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// fieldsByName fills a values interface with fields from the passed value based
|
||||
// on the traversals in int. If ptrs is true, return addresses instead of values.
|
||||
// We write this instead of using FieldsByName to save allocations and map lookups
|
||||
// when iterating over many rows. Empty traversals will get an interface pointer.
|
||||
// Because of the necessity of requesting ptrs or values, it's considered a bit too
|
||||
// specialized for inclusion in reflectx itself.
|
||||
func fieldsByTraversal(v reflect.Value, traversals [][]int, values []interface{}, ptrs bool) error {
|
||||
v = reflect.Indirect(v)
|
||||
if v.Kind() != reflect.Struct {
|
||||
return errors.New("argument not a struct")
|
||||
}
|
||||
|
||||
for i, traversal := range traversals {
|
||||
if len(traversal) == 0 {
|
||||
values[i] = new(interface{})
|
||||
continue
|
||||
}
|
||||
f := FieldByIndexes(v, traversal)
|
||||
if ptrs {
|
||||
values[i] = f.Addr().Interface()
|
||||
} else {
|
||||
values[i] = f.Interface()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// A FieldInfo is metadata for a struct field.
|
||||
type FieldInfo struct {
|
||||
Index []int
|
||||
Path string
|
||||
Field reflect.StructField
|
||||
Zero reflect.Value
|
||||
Name string
|
||||
Options map[string]string
|
||||
Embedded bool
|
||||
Children []*FieldInfo
|
||||
Parent *FieldInfo
|
||||
}
|
||||
|
||||
// A StructMap is an index of field metadata for a struct.
|
||||
type StructMap struct {
|
||||
Tree *FieldInfo
|
||||
Index []*FieldInfo
|
||||
Paths map[string]*FieldInfo
|
||||
Names map[string]*FieldInfo
|
||||
}
|
||||
|
||||
// GetByPath returns a *FieldInfo for a given string path.
|
||||
func (f StructMap) GetByPath(path string) *FieldInfo {
|
||||
return f.Paths[path]
|
||||
}
|
||||
|
||||
// GetByTraversal returns a *FieldInfo for a given integer path. It is
|
||||
// analogous to reflect.FieldByIndex, but using the cached traversal
|
||||
// rather than re-executing the reflect machinery each time.
|
||||
func (f StructMap) GetByTraversal(index []int) *FieldInfo {
|
||||
if len(index) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tree := f.Tree
|
||||
for _, i := range index {
|
||||
if i >= len(tree.Children) || tree.Children[i] == nil {
|
||||
return nil
|
||||
}
|
||||
tree = tree.Children[i]
|
||||
}
|
||||
return tree
|
||||
}
|
||||
|
||||
// Mapper is a general purpose mapper of names to struct fields. A Mapper
|
||||
// behaves like most marshallers in the standard library, obeying a field tag
|
||||
// for name mapping but also providing a basic transform function.
|
||||
type Mapper struct {
|
||||
cache map[reflect.Type]*StructMap
|
||||
tagName string
|
||||
tagMapFunc func(string) string
|
||||
mapFunc func(string) string
|
||||
mutex sync.Mutex
|
||||
}
|
||||
|
||||
// NewMapper returns a new mapper using the tagName as its struct field tag.
|
||||
// If tagName is the empty string, it is ignored.
|
||||
func NewMapper(tagName string) *Mapper {
|
||||
return &Mapper{
|
||||
cache: make(map[reflect.Type]*StructMap),
|
||||
tagName: tagName,
|
||||
}
|
||||
}
|
||||
|
||||
// NewMapperTagFunc returns a new mapper which contains a mapper for field names
|
||||
// AND a mapper for tag values. This is useful for tags like json which can
|
||||
// have values like "name,omitempty".
|
||||
func NewMapperTagFunc(tagName string, mapFunc, tagMapFunc func(string) string) *Mapper {
|
||||
return &Mapper{
|
||||
cache: make(map[reflect.Type]*StructMap),
|
||||
tagName: tagName,
|
||||
mapFunc: mapFunc,
|
||||
tagMapFunc: tagMapFunc,
|
||||
}
|
||||
}
|
||||
|
||||
// NewMapperFunc returns a new mapper which optionally obeys a field tag and
|
||||
// a struct field name mapper func given by f. Tags will take precedence, but
|
||||
// for any other field, the mapped name will be f(field.Name)
|
||||
func NewMapperFunc(tagName string, f func(string) string) *Mapper {
|
||||
return &Mapper{
|
||||
cache: make(map[reflect.Type]*StructMap),
|
||||
tagName: tagName,
|
||||
mapFunc: f,
|
||||
}
|
||||
}
|
||||
|
||||
// TypeMap returns a mapping of field strings to int slices representing
|
||||
// the traversal down the struct to reach the field.
|
||||
func (m *Mapper) TypeMap(t reflect.Type) *StructMap {
|
||||
m.mutex.Lock()
|
||||
mapping, ok := m.cache[t]
|
||||
if !ok {
|
||||
mapping = getMapping(t, m.tagName, m.mapFunc, m.tagMapFunc)
|
||||
m.cache[t] = mapping
|
||||
}
|
||||
m.mutex.Unlock()
|
||||
return mapping
|
||||
}
|
||||
|
||||
// FieldMap returns the mapper's mapping of field names to reflect values. Panics
|
||||
// if v's Kind is not Struct, or v is not Indirectable to a struct kind.
|
||||
func (m *Mapper) FieldMap(v reflect.Value) map[string]reflect.Value {
|
||||
v = reflect.Indirect(v)
|
||||
mustBe(v, reflect.Struct)
|
||||
|
||||
r := map[string]reflect.Value{}
|
||||
tm := m.TypeMap(v.Type())
|
||||
for tagName, fi := range tm.Names {
|
||||
r[tagName] = FieldByIndexes(v, fi.Index)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// FieldByName returns a field by its mapped name as a reflect.Value.
|
||||
// Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind.
|
||||
// Returns zero Value if the name is not found.
|
||||
func (m *Mapper) FieldByName(v reflect.Value, name string) reflect.Value {
|
||||
v = reflect.Indirect(v)
|
||||
mustBe(v, reflect.Struct)
|
||||
|
||||
tm := m.TypeMap(v.Type())
|
||||
fi, ok := tm.Names[name]
|
||||
if !ok {
|
||||
return v
|
||||
}
|
||||
return FieldByIndexes(v, fi.Index)
|
||||
}
|
||||
|
||||
// FieldsByName returns a slice of values corresponding to the slice of names
|
||||
// for the value. Panics if v's Kind is not Struct or v is not Indirectable
|
||||
// to a struct Kind. Returns zero Value for each name not found.
|
||||
func (m *Mapper) FieldsByName(v reflect.Value, names []string) []reflect.Value {
|
||||
v = reflect.Indirect(v)
|
||||
mustBe(v, reflect.Struct)
|
||||
|
||||
tm := m.TypeMap(v.Type())
|
||||
vals := make([]reflect.Value, 0, len(names))
|
||||
for _, name := range names {
|
||||
fi, ok := tm.Names[name]
|
||||
if !ok {
|
||||
vals = append(vals, *new(reflect.Value))
|
||||
} else {
|
||||
vals = append(vals, FieldByIndexes(v, fi.Index))
|
||||
}
|
||||
}
|
||||
return vals
|
||||
}
|
||||
|
||||
// TraversalsByName returns a slice of int slices which represent the struct
|
||||
// traversals for each mapped name. Panics if t is not a struct or Indirectable
|
||||
// to a struct. Returns empty int slice for each name not found.
|
||||
func (m *Mapper) TraversalsByName(t reflect.Type, names []string) [][]int {
|
||||
r := make([][]int, 0, len(names))
|
||||
m.TraversalsByNameFunc(t, names, func(_ int, i []int) error {
|
||||
if i == nil {
|
||||
r = append(r, []int{})
|
||||
} else {
|
||||
r = append(r, i)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
// TraversalsByNameFunc traverses the mapped names and calls fn with the index of
|
||||
// each name and the struct traversal represented by that name. Panics if t is not
|
||||
// a struct or Indirectable to a struct. Returns the first error returned by fn or nil.
|
||||
func (m *Mapper) TraversalsByNameFunc(t reflect.Type, names []string, fn func(int, []int) error) error {
|
||||
t = Deref(t)
|
||||
mustBe(t, reflect.Struct)
|
||||
tm := m.TypeMap(t)
|
||||
for i, name := range names {
|
||||
fi, ok := tm.Names[name]
|
||||
if !ok {
|
||||
if err := fn(i, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := fn(i, fi.Index); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FieldByIndexes returns a value for the field given by the struct traversal
|
||||
// for the given value.
|
||||
func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value {
|
||||
for _, i := range indexes {
|
||||
v = reflect.Indirect(v).Field(i)
|
||||
// if this is a pointer and it's nil, allocate a new value and set it
|
||||
if v.Kind() == reflect.Ptr && v.IsNil() {
|
||||
alloc := reflect.New(Deref(v.Type()))
|
||||
v.Set(alloc)
|
||||
}
|
||||
if v.Kind() == reflect.Map && v.IsNil() {
|
||||
v.Set(reflect.MakeMap(v.Type()))
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// FieldByIndexesReadOnly returns a value for a particular struct traversal,
|
||||
// but is not concerned with allocating nil pointers because the value is
|
||||
// going to be used for reading and not setting.
|
||||
func FieldByIndexesReadOnly(v reflect.Value, indexes []int) reflect.Value {
|
||||
for _, i := range indexes {
|
||||
v = reflect.Indirect(v).Field(i)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Deref is Indirect for reflect.Types
|
||||
func Deref(t reflect.Type) reflect.Type {
|
||||
if t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// -- helpers & utilities --
|
||||
|
||||
type kinder interface {
|
||||
Kind() reflect.Kind
|
||||
}
|
||||
|
||||
// mustBe checks a value against a kind, panicing with a reflect.ValueError
|
||||
// if the kind isn't that which is required.
|
||||
func mustBe(v kinder, expected reflect.Kind) {
|
||||
if k := v.Kind(); k != expected {
|
||||
panic(&reflect.ValueError{Method: methodName(), Kind: k})
|
||||
}
|
||||
}
|
||||
|
||||
// methodName returns the caller of the function calling methodName
|
||||
func methodName() string {
|
||||
pc, _, _, _ := runtime.Caller(2)
|
||||
f := runtime.FuncForPC(pc)
|
||||
if f == nil {
|
||||
return "unknown method"
|
||||
}
|
||||
return f.Name()
|
||||
}
|
||||
|
||||
type typeQueue struct {
|
||||
t reflect.Type
|
||||
fi *FieldInfo
|
||||
pp string // Parent path
|
||||
}
|
||||
|
||||
// A copying append that creates a new slice each time.
|
||||
func apnd(is []int, i int) []int {
|
||||
x := make([]int, len(is)+1)
|
||||
copy(x, is)
|
||||
x[len(x)-1] = i
|
||||
return x
|
||||
}
|
||||
|
||||
type mapf func(string) string
|
||||
|
||||
// parseName parses the tag and the target name for the given field using
|
||||
// the tagName (eg 'json' for `json:"foo"` tags), mapFunc for mapping the
|
||||
// field's name to a target name, and tagMapFunc for mapping the tag to
|
||||
// a target name.
|
||||
func parseName(field reflect.StructField, tagName string, mapFunc, tagMapFunc mapf) (tag, fieldName string) {
|
||||
// first, set the fieldName to the field's name
|
||||
fieldName = field.Name
|
||||
// if a mapFunc is set, use that to override the fieldName
|
||||
if mapFunc != nil {
|
||||
fieldName = mapFunc(fieldName)
|
||||
}
|
||||
|
||||
// if there's no tag to look for, return the field name
|
||||
if tagName == "" {
|
||||
return "", fieldName
|
||||
}
|
||||
|
||||
// if this tag is not set using the normal convention in the tag,
|
||||
// then return the fieldname.. this check is done because according
|
||||
// to the reflect documentation:
|
||||
// If the tag does not have the conventional format,
|
||||
// the value returned by Get is unspecified.
|
||||
// which doesn't sound great.
|
||||
if !strings.Contains(string(field.Tag), tagName+":") {
|
||||
return "", fieldName
|
||||
}
|
||||
|
||||
// at this point we're fairly sure that we have a tag, so lets pull it out
|
||||
tag = field.Tag.Get(tagName)
|
||||
|
||||
// if we have a mapper function, call it on the whole tag
|
||||
// XXX: this is a change from the old version, which pulled out the name
|
||||
// before the tagMapFunc could be run, but I think this is the right way
|
||||
if tagMapFunc != nil {
|
||||
tag = tagMapFunc(tag)
|
||||
}
|
||||
|
||||
// finally, split the options from the name
|
||||
parts := strings.Split(tag, ",")
|
||||
fieldName = parts[0]
|
||||
|
||||
return tag, fieldName
|
||||
}
|
||||
|
||||
// parseOptions parses options out of a tag string, skipping the name
|
||||
func parseOptions(tag string) map[string]string {
|
||||
parts := strings.Split(tag, ",")
|
||||
options := make(map[string]string, len(parts))
|
||||
if len(parts) > 1 {
|
||||
for _, opt := range parts[1:] {
|
||||
// short circuit potentially expensive split op
|
||||
if strings.Contains(opt, "=") {
|
||||
kv := strings.Split(opt, "=")
|
||||
options[kv[0]] = kv[1]
|
||||
continue
|
||||
}
|
||||
options[opt] = ""
|
||||
}
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// getMapping returns a mapping for the t type, using the tagName, mapFunc and
|
||||
// tagMapFunc to determine the canonical names of fields.
|
||||
func getMapping(t reflect.Type, tagName string, mapFunc, tagMapFunc mapf) *StructMap {
|
||||
m := []*FieldInfo{}
|
||||
|
||||
root := &FieldInfo{}
|
||||
queue := []typeQueue{}
|
||||
queue = append(queue, typeQueue{Deref(t), root, ""})
|
||||
|
||||
QueueLoop:
|
||||
for len(queue) != 0 {
|
||||
// pop the first item off of the queue
|
||||
tq := queue[0]
|
||||
queue = queue[1:]
|
||||
|
||||
// ignore recursive field
|
||||
for p := tq.fi.Parent; p != nil; p = p.Parent {
|
||||
if tq.fi.Field.Type == p.Field.Type {
|
||||
continue QueueLoop
|
||||
}
|
||||
}
|
||||
|
||||
nChildren := 0
|
||||
if tq.t.Kind() == reflect.Struct {
|
||||
nChildren = tq.t.NumField()
|
||||
}
|
||||
tq.fi.Children = make([]*FieldInfo, nChildren)
|
||||
|
||||
// iterate through all of its fields
|
||||
for fieldPos := 0; fieldPos < nChildren; fieldPos++ {
|
||||
|
||||
f := tq.t.Field(fieldPos)
|
||||
|
||||
// parse the tag and the target name using the mapping options for this field
|
||||
tag, name := parseName(f, tagName, mapFunc, tagMapFunc)
|
||||
|
||||
// if the name is "-", disabled via a tag, skip it
|
||||
if name == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
fi := FieldInfo{
|
||||
Field: f,
|
||||
Name: name,
|
||||
Zero: reflect.New(f.Type).Elem(),
|
||||
Options: parseOptions(tag),
|
||||
}
|
||||
|
||||
// if the path is empty this path is just the name
|
||||
if tq.pp == "" {
|
||||
fi.Path = fi.Name
|
||||
} else {
|
||||
fi.Path = tq.pp + "." + fi.Name
|
||||
}
|
||||
|
||||
// skip unexported fields
|
||||
if len(f.PkgPath) != 0 && !f.Anonymous {
|
||||
continue
|
||||
}
|
||||
|
||||
// bfs search of anonymous embedded structs
|
||||
if f.Anonymous {
|
||||
pp := tq.pp
|
||||
if tag != "" {
|
||||
pp = fi.Path
|
||||
}
|
||||
|
||||
fi.Embedded = true
|
||||
fi.Index = apnd(tq.fi.Index, fieldPos)
|
||||
nChildren := 0
|
||||
ft := Deref(f.Type)
|
||||
if ft.Kind() == reflect.Struct {
|
||||
nChildren = ft.NumField()
|
||||
}
|
||||
fi.Children = make([]*FieldInfo, nChildren)
|
||||
queue = append(queue, typeQueue{Deref(f.Type), &fi, pp})
|
||||
} else if fi.Zero.Kind() == reflect.Struct || (fi.Zero.Kind() == reflect.Ptr && fi.Zero.Type().Elem().Kind() == reflect.Struct) {
|
||||
fi.Index = apnd(tq.fi.Index, fieldPos)
|
||||
fi.Children = make([]*FieldInfo, Deref(f.Type).NumField())
|
||||
queue = append(queue, typeQueue{Deref(f.Type), &fi, fi.Path})
|
||||
}
|
||||
|
||||
fi.Index = apnd(tq.fi.Index, fieldPos)
|
||||
fi.Parent = tq.fi
|
||||
tq.fi.Children[fieldPos] = &fi
|
||||
m = append(m, &fi)
|
||||
}
|
||||
}
|
||||
|
||||
flds := &StructMap{Index: m, Tree: root, Paths: map[string]*FieldInfo{}, Names: map[string]*FieldInfo{}}
|
||||
for _, fi := range flds.Index {
|
||||
// check if nothing has already been pushed with the same path
|
||||
// sometimes you can choose to override a type using embedded struct
|
||||
fld, ok := flds.Paths[fi.Path]
|
||||
if !ok || fld.Embedded {
|
||||
flds.Paths[fi.Path] = fi
|
||||
if fi.Name != "" && !fi.Embedded {
|
||||
flds.Names[fi.Path] = fi
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return flds
|
||||
}
|
||||
55
server/internal/db/domain/entity/db.go
Normal file
55
server/internal/db/domain/entity/db.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mayfly-go/internal/common/utils"
|
||||
"mayfly-go/pkg/model"
|
||||
)
|
||||
|
||||
type Db struct {
|
||||
model.Model
|
||||
|
||||
Name string `orm:"column(name)" json:"name"`
|
||||
Type string `orm:"column(type)" json:"type"` // 类型,mysql oracle等
|
||||
Host string `orm:"column(host)" json:"host"`
|
||||
Port int `orm:"column(port)" json:"port"`
|
||||
Network string `orm:"column(network)" json:"network"`
|
||||
Username string `orm:"column(username)" json:"username"`
|
||||
Password string `orm:"column(password)" json:"-"`
|
||||
Database string `orm:"column(database)" json:"database"`
|
||||
Params string `json:"params"`
|
||||
Remark string `json:"remark"`
|
||||
TagId uint64
|
||||
TagPath string
|
||||
|
||||
EnableSshTunnel int8 `orm:"column(enable_ssh_tunnel)" json:"enableSshTunnel"` // 是否启用ssh隧道
|
||||
SshTunnelMachineId uint64 `orm:"column(ssh_tunnel_machine_id)" json:"sshTunnelMachineId"` // ssh隧道机器id
|
||||
}
|
||||
|
||||
// 获取数据库连接网络, 若没有使用ssh隧道,则直接返回。否则返回拼接的网络需要注册至指定dial
|
||||
func (d *Db) GetNetwork() string {
|
||||
network := d.Network
|
||||
if d.EnableSshTunnel == 0 || d.EnableSshTunnel == -1 {
|
||||
if network == "" {
|
||||
return "tcp"
|
||||
} else {
|
||||
return network
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s+ssh:%d", d.Type, d.SshTunnelMachineId)
|
||||
}
|
||||
|
||||
func (d *Db) PwdEncrypt() {
|
||||
// 密码替换为加密后的密码
|
||||
d.Password = utils.PwdAesEncrypt(d.Password)
|
||||
}
|
||||
|
||||
func (d *Db) PwdDecrypt() {
|
||||
// 密码替换为解密后的密码
|
||||
d.Password = utils.PwdAesDecrypt(d.Password)
|
||||
}
|
||||
|
||||
const (
|
||||
DbTypeMysql = "mysql"
|
||||
DbTypePostgres = "postgres"
|
||||
)
|
||||
24
server/internal/db/domain/entity/query.go
Normal file
24
server/internal/db/domain/entity/query.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package entity
|
||||
|
||||
import "mayfly-go/pkg/model"
|
||||
|
||||
// 数据库查询实体,不与数据库表字段一一对应
|
||||
type DbQuery struct {
|
||||
model.Model
|
||||
|
||||
Name string `orm:"column(name)" json:"name"`
|
||||
Type string `orm:"column(type)" json:"type"` // 类型,mysql oracle等
|
||||
Host string `orm:"column(host)" json:"host"`
|
||||
Port int `orm:"column(port)" json:"port"`
|
||||
Network string `orm:"column(network)" json:"network"`
|
||||
Username string `orm:"column(username)" json:"username"`
|
||||
Password string `orm:"column(password)" json:"-"`
|
||||
Database string `orm:"column(database)" json:"database"`
|
||||
Params string `json:"params"`
|
||||
Remark string `json:"remark"`
|
||||
TagId uint64
|
||||
|
||||
ProjectIds []uint64
|
||||
TagIds []uint64
|
||||
TagPathLike string
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/devops/domain/entity"
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/pkg/model"
|
||||
)
|
||||
|
||||
type Db interface {
|
||||
// 分页获取机器信息列表
|
||||
GetDbList(condition *entity.Db, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult
|
||||
GetDbList(condition *entity.DbQuery, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult
|
||||
|
||||
Count(condition *entity.Db) int64
|
||||
Count(condition *entity.DbQuery) int64
|
||||
|
||||
// 根据条件获取账号信息
|
||||
GetDb(condition *entity.Db, cols ...string) error
|
||||
@@ -1,6 +1,6 @@
|
||||
package repository
|
||||
|
||||
import "mayfly-go/internal/devops/domain/entity"
|
||||
import "mayfly-go/internal/db/domain/entity"
|
||||
|
||||
type DbSql interface {
|
||||
DeleteBy(condition *entity.DbSql)
|
||||
@@ -1,7 +1,7 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/devops/domain/entity"
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/pkg/model"
|
||||
)
|
||||
|
||||
74
server/internal/db/infrastructure/persistence/db.go
Normal file
74
server/internal/db/infrastructure/persistence/db.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/internal/db/domain/repository"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/utils"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type dbRepoImpl struct{}
|
||||
|
||||
func newDbRepo() repository.Db {
|
||||
return new(dbRepoImpl)
|
||||
}
|
||||
|
||||
// 分页获取数据库信息列表
|
||||
func (d *dbRepoImpl) GetDbList(condition *entity.DbQuery, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult {
|
||||
sql := "SELECT d.* FROM t_db d WHERE 1 = 1 "
|
||||
if condition.Host != "" {
|
||||
sql = sql + " AND d.host LIKE '%" + condition.Host + "%'"
|
||||
}
|
||||
if condition.Database != "" {
|
||||
sql = sql + " AND d.database LIKE '%" + condition.Database + "%'"
|
||||
}
|
||||
if len(condition.TagIds) > 0 {
|
||||
sql = sql + " AND d.tag_id IN " + fmt.Sprintf("(%s)", strings.Join(utils.NumberArr2StrArr(condition.TagIds), ","))
|
||||
}
|
||||
if condition.TagPathLike != "" {
|
||||
sql = sql + " AND d.tag_path LIKE '" + condition.TagPathLike + "%'"
|
||||
}
|
||||
sql = sql + " ORDER BY d.create_time DESC"
|
||||
return model.GetPageBySql(sql, pageParam, toEntity)
|
||||
}
|
||||
|
||||
func (d *dbRepoImpl) Count(condition *entity.DbQuery) int64 {
|
||||
where := make(map[string]interface{})
|
||||
if len(condition.TagIds) > 0 {
|
||||
where["tag_id"] = condition.TagIds
|
||||
}
|
||||
if condition.TagId != 0 {
|
||||
where["tag_id"] = condition.TagId
|
||||
}
|
||||
return model.CountByMap(new(entity.Db), where)
|
||||
}
|
||||
|
||||
// 根据条件获取账号信息
|
||||
func (d *dbRepoImpl) GetDb(condition *entity.Db, cols ...string) error {
|
||||
return model.GetBy(condition, cols...)
|
||||
}
|
||||
|
||||
// 根据id获取
|
||||
func (d *dbRepoImpl) GetById(id uint64, cols ...string) *entity.Db {
|
||||
db := new(entity.Db)
|
||||
if err := model.GetById(db, id, cols...); err != nil {
|
||||
return nil
|
||||
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (d *dbRepoImpl) Insert(db *entity.Db) {
|
||||
biz.ErrIsNil(model.Insert(db), "新增数据库信息失败")
|
||||
}
|
||||
|
||||
func (d *dbRepoImpl) Update(db *entity.Db) {
|
||||
biz.ErrIsNil(model.UpdateById(db), "更新数据库信息失败")
|
||||
}
|
||||
|
||||
func (d *dbRepoImpl) Delete(id uint64) {
|
||||
model.DeleteById(new(entity.Db), id)
|
||||
}
|
||||
19
server/internal/db/infrastructure/persistence/db_sql.go
Normal file
19
server/internal/db/infrastructure/persistence/db_sql.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/internal/db/domain/repository"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/model"
|
||||
)
|
||||
|
||||
type dbSqlRepoImpl struct{}
|
||||
|
||||
func newDbSqlRepo() repository.DbSql {
|
||||
return new(dbSqlRepoImpl)
|
||||
}
|
||||
|
||||
// 分页获取数据库信息列表
|
||||
func (d *dbSqlRepoImpl) DeleteBy(condition *entity.DbSql) {
|
||||
biz.ErrIsNil(model.DeleteByCondition(condition), "删除sql失败")
|
||||
}
|
||||
27
server/internal/db/infrastructure/persistence/db_sql_exec.go
Normal file
27
server/internal/db/infrastructure/persistence/db_sql_exec.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/internal/db/domain/repository"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/model"
|
||||
)
|
||||
|
||||
type dbSqlExecRepoImpl struct{}
|
||||
|
||||
func newDbSqlExecRepo() repository.DbSqlExec {
|
||||
return new(dbSqlExecRepoImpl)
|
||||
}
|
||||
|
||||
func (d *dbSqlExecRepoImpl) Insert(dse *entity.DbSqlExec) {
|
||||
model.Insert(dse)
|
||||
}
|
||||
|
||||
func (d *dbSqlExecRepoImpl) DeleteBy(condition *entity.DbSqlExec) {
|
||||
biz.ErrIsNil(model.DeleteByCondition(condition), "删除sql执行记录失败")
|
||||
}
|
||||
|
||||
// 分页获取
|
||||
func (d *dbSqlExecRepoImpl) GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult {
|
||||
return model.GetPage(pageParam, condition, condition, toEntity, orderBy...)
|
||||
}
|
||||
21
server/internal/db/infrastructure/persistence/persistence.go
Normal file
21
server/internal/db/infrastructure/persistence/persistence.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package persistence
|
||||
|
||||
import "mayfly-go/internal/db/domain/repository"
|
||||
|
||||
var (
|
||||
dbRepo repository.Db = newDbRepo()
|
||||
dbSqlRepo repository.DbSql = newDbSqlRepo()
|
||||
dbSqlExecRepo repository.DbSqlExec = newDbSqlExecRepo()
|
||||
)
|
||||
|
||||
func GetDbRepo() repository.Db {
|
||||
return dbRepo
|
||||
}
|
||||
|
||||
func GetDbSqlRepo() repository.DbSql {
|
||||
return dbSqlRepo
|
||||
}
|
||||
|
||||
func GetDbSqlExecRepo() repository.DbSqlExec {
|
||||
return dbSqlExecRepo
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/devops/api"
|
||||
"mayfly-go/internal/devops/application"
|
||||
sysApplication "mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/db/api"
|
||||
"mayfly-go/internal/db/application"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
tagapp "mayfly-go/internal/tag/application"
|
||||
"mayfly-go/pkg/ctx"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -13,15 +14,14 @@ func InitDbRouter(router *gin.RouterGroup) {
|
||||
db := router.Group("dbs")
|
||||
{
|
||||
d := &api.Db{
|
||||
DbApp: application.DbApp,
|
||||
DbSqlExecApp: application.DbSqlExecApp,
|
||||
MsgApp: sysApplication.MsgApp,
|
||||
ProjectApp: application.ProjectApp,
|
||||
DbApp: application.GetDbApp(),
|
||||
DbSqlExecApp: application.GetDbSqlExecApp(),
|
||||
MsgApp: sysapp.GetMsgApp(),
|
||||
TagApp: tagapp.GetTagTreeApp(),
|
||||
}
|
||||
// 获取所有数据库列表
|
||||
db.GET("", func(c *gin.Context) {
|
||||
rc := ctx.NewReqCtxWithGin(c)
|
||||
rc.Handle(d.Dbs)
|
||||
ctx.NewReqCtxWithGin(c).Handle(d.Dbs)
|
||||
})
|
||||
|
||||
saveDb := ctx.NewLogInfo("保存数据库信息").WithSave(true)
|
||||
@@ -31,6 +31,16 @@ func InitDbRouter(router *gin.RouterGroup) {
|
||||
Handle(d.Save)
|
||||
})
|
||||
|
||||
// 获取数据库实例的所有数据库名
|
||||
db.POST("databases", func(c *gin.Context) {
|
||||
ctx.NewReqCtxWithGin(c).
|
||||
Handle(d.GetDatabaseNames)
|
||||
})
|
||||
|
||||
db.GET(":dbId/pwd", func(c *gin.Context) {
|
||||
ctx.NewReqCtxWithGin(c).Handle(d.GetDbPwd)
|
||||
})
|
||||
|
||||
deleteDb := ctx.NewLogInfo("删除数据库信息").WithSave(true)
|
||||
db.DELETE(":dbId", func(c *gin.Context) {
|
||||
ctx.NewReqCtxWithGin(c).
|
||||
@@ -1,8 +1,8 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/devops/api"
|
||||
"mayfly-go/internal/devops/application"
|
||||
"mayfly-go/internal/db/api"
|
||||
"mayfly-go/internal/db/application"
|
||||
"mayfly-go/pkg/ctx"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -12,7 +12,7 @@ func InitDbSqlExecRouter(router *gin.RouterGroup) {
|
||||
db := router.Group("/dbs/:dbId/sql-execs")
|
||||
{
|
||||
d := &api.DbSqlExec{
|
||||
DbSqlExecApp: application.DbSqlExecApp,
|
||||
DbSqlExecApp: application.GetDbSqlExecApp(),
|
||||
}
|
||||
// 获取所有数据库sql执行记录列表
|
||||
db.GET("", func(c *gin.Context) {
|
||||
8
server/internal/db/router/router.go
Normal file
8
server/internal/db/router/router.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package router
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func Init(router *gin.RouterGroup) {
|
||||
InitDbRouter(router)
|
||||
InitDbSqlExecRouter(router)
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package form
|
||||
|
||||
type DbForm struct {
|
||||
Id uint64
|
||||
Name string `binding:"required" json:"name"`
|
||||
Type string `binding:"required" json:"type"` // 类型,mysql oracle等
|
||||
Host string `binding:"required" json:"host"`
|
||||
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"`
|
||||
Env string `json:"env"`
|
||||
EnvId uint64 `binding:"required" json:"envId"`
|
||||
|
||||
EnableSshTunnel int8 `json:"enableSshTunnel"`
|
||||
SshTunnelMachineId uint64 `json:"sshTunnelMachineId"`
|
||||
}
|
||||
|
||||
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"` //数据库名
|
||||
Sql string `binding:"required" json:"sql"` // 执行sql
|
||||
Remark string `json:"remark"` // 执行备注
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mayfly-go/internal/devops/api/vo"
|
||||
"mayfly-go/internal/devops/application"
|
||||
"mayfly-go/internal/devops/domain/entity"
|
||||
sys_applicaiton "mayfly-go/internal/sys/application"
|
||||
sys_entity "mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/ctx"
|
||||
"mayfly-go/pkg/ginx"
|
||||
)
|
||||
|
||||
type Project struct {
|
||||
ProjectApp application.Project
|
||||
AccountApp sys_applicaiton.Account
|
||||
}
|
||||
|
||||
// 获取当前登录用户可以访问的项目列表
|
||||
func (p *Project) GetProjectsByLoginAccount(rc *ctx.ReqCtx) {
|
||||
// 获取登录用户拥有的项目ids
|
||||
projectMembers := &[]entity.ProjectMember{}
|
||||
p.ProjectApp.ListMember(&entity.ProjectMember{AccountId: rc.LoginAccount.Id}, projectMembers)
|
||||
var pids []uint64
|
||||
for _, pm := range *projectMembers {
|
||||
pids = append(pids, pm.ProjectId)
|
||||
}
|
||||
|
||||
// 获取项目信息
|
||||
projects := &vo.AccountProjects{}
|
||||
p.ProjectApp.ListProjectByIds(pids, projects)
|
||||
rc.ResData = projects
|
||||
}
|
||||
|
||||
func (p *Project) GetProjects(rc *ctx.ReqCtx) {
|
||||
condition := &entity.Project{}
|
||||
ginx.BindQuery(rc.GinCtx, condition)
|
||||
// condition.Name = rc.GinCtx.Query("name")
|
||||
rc.ResData = p.ProjectApp.GetPageList(condition, ginx.GetPageParam(rc.GinCtx), new([]entity.Project))
|
||||
}
|
||||
|
||||
func (p *Project) SaveProject(rc *ctx.ReqCtx) {
|
||||
project := &entity.Project{}
|
||||
ginx.BindJsonAndValid(rc.GinCtx, project)
|
||||
|
||||
rc.ReqParam = fmt.Sprintf("projectId: %d, projectName: %s, remark: %s", project.Id, project.Name, project.Remark)
|
||||
|
||||
project.SetBaseInfo(rc.LoginAccount)
|
||||
p.ProjectApp.SaveProject(project)
|
||||
}
|
||||
|
||||
func (p *Project) DelProject(rc *ctx.ReqCtx) {
|
||||
p.ProjectApp.DelProject(uint64(ginx.QueryInt(rc.GinCtx, "id", 0)))
|
||||
}
|
||||
|
||||
// 获取项目下的环境信息
|
||||
func (p *Project) GetProjectEnvs(rc *ctx.ReqCtx) {
|
||||
projectEnvs := &[]entity.ProjectEnv{}
|
||||
p.ProjectApp.ListEnvByProjectId(uint64(ginx.PathParamInt(rc.GinCtx, "projectId")), projectEnvs)
|
||||
rc.ResData = projectEnvs
|
||||
}
|
||||
|
||||
//保存项目下的环境信息
|
||||
func (p *Project) SaveProjectEnvs(rc *ctx.ReqCtx) {
|
||||
projectEnv := &entity.ProjectEnv{}
|
||||
ginx.BindJsonAndValid(rc.GinCtx, projectEnv)
|
||||
rc.ReqParam = projectEnv
|
||||
|
||||
projectEnv.SetBaseInfo(rc.LoginAccount)
|
||||
p.ProjectApp.SaveProjectEnv(projectEnv)
|
||||
}
|
||||
|
||||
// 获取项目下的成员信息
|
||||
func (p *Project) GetProjectMembers(rc *ctx.ReqCtx) {
|
||||
projectMems := &[]entity.ProjectMember{}
|
||||
rc.ResData = p.ProjectApp.GetMemberPage(&entity.ProjectMember{ProjectId: uint64(ginx.PathParamInt(rc.GinCtx, "projectId"))},
|
||||
ginx.GetPageParam(rc.GinCtx), projectMems)
|
||||
}
|
||||
|
||||
//保存项目的成员信息
|
||||
func (p *Project) SaveProjectMember(rc *ctx.ReqCtx) {
|
||||
projectMem := &entity.ProjectMember{}
|
||||
ginx.BindJsonAndValid(rc.GinCtx, projectMem)
|
||||
|
||||
rc.ReqParam = fmt.Sprintf("projectId: %d, username: %s", projectMem.ProjectId, projectMem.Username)
|
||||
|
||||
// 校验账号,并赋值username
|
||||
account := &sys_entity.Account{}
|
||||
account.Id = projectMem.AccountId
|
||||
biz.ErrIsNil(p.AccountApp.GetAccount(account, "Id", "Username"), "账号不存在")
|
||||
projectMem.Username = account.Username
|
||||
|
||||
projectMem.SetBaseInfo(rc.LoginAccount)
|
||||
p.ProjectApp.SaveProjectMember(projectMem)
|
||||
}
|
||||
|
||||
//删除项目成员
|
||||
func (p *Project) DelProjectMember(rc *ctx.ReqCtx) {
|
||||
g := rc.GinCtx
|
||||
pid := ginx.PathParamInt(g, "projectId")
|
||||
aid := ginx.PathParamInt(g, "accountId")
|
||||
rc.ReqParam = fmt.Sprintf("projectId: %d, accountId: %d", pid, aid)
|
||||
|
||||
p.ProjectApp.DeleteMember(uint64(pid), uint64(aid))
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user