fix: mysql 数据库删除增加使用判断

This commit is contained in:
ssongliu 2022-12-04 17:28:03 +08:00 committed by ssongliu
parent 8a78657519
commit 1c4da6d88b
7 changed files with 126 additions and 39 deletions

View file

@ -145,18 +145,29 @@ func (b *BaseApi) RecoverMysql(c *gin.Context) {
helper.SuccessWithData(c, nil)
}
func (b *BaseApi) DeleteMysql(c *gin.Context) {
var req dto.BatchDeleteReq
if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return
}
if err := global.VALID.Struct(req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
func (b *BaseApi) DeleteCheckMysql(c *gin.Context) {
id, err := helper.GetParamID(c)
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInternalServer, nil)
return
}
if err := mysqlService.Delete(req.Ids); err != nil {
apps, err := mysqlService.DeleteCheck(id)
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}
helper.SuccessWithData(c, apps)
}
func (b *BaseApi) DeleteMysql(c *gin.Context) {
id, err := helper.GetParamID(c)
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInternalServer, nil)
return
}
if err := mysqlService.Delete(id); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}

View file

@ -23,6 +23,12 @@ func (a AppInstallResourceRpo) WithLinkId(linkId uint) DBOption {
}
}
func (a AppInstallResourceRpo) WithResourceId(resourceId uint) DBOption {
return func(db *gorm.DB) *gorm.DB {
return db.Where("resource_id = ?", resourceId)
}
}
func (a AppInstallResourceRpo) GetBy(opts ...DBOption) ([]model.AppInstallResource, error) {
db := global.DB.Model(&model.AppInstallResource{})
var resources []model.AppInstallResource

View file

@ -40,7 +40,8 @@ type IMysqlService interface {
Backup(db dto.BackupDB) error
Recover(db dto.RecoverDB) error
Delete(ids []uint) error
DeleteCheck(id uint) ([]string, error)
Delete(id uint) error
LoadStatus() (*dto.MysqlStatus, error)
LoadVariables() (*dto.MysqlVariables, error)
LoadBaseInfo() (*dto.DBBaseInfo, error)
@ -225,28 +226,46 @@ func (u *MysqlService) Recover(db dto.RecoverDB) error {
return nil
}
func (u *MysqlService) Delete(ids []uint) error {
func (u *MysqlService) DeleteCheck(id uint) ([]string, error) {
var appInUsed []string
app, err := appInstallRepo.LoadBaseInfoByKey("mysql")
if err != nil {
return appInUsed, err
}
db, err := mysqlRepo.Get(commonRepo.WithByID(id))
if err != nil {
return appInUsed, err
}
apps, _ := appInstallResourceRepo.GetBy(appInstallResourceRepo.WithResourceId(app.ID), appInstallResourceRepo.WithLinkId(db.ID))
for _, app := range apps {
appInstall, _ := appInstallRepo.GetFirst(commonRepo.WithByID(app.ID))
if appInstall.ID != 0 {
appInUsed = append(appInUsed, appInstall.Name)
}
}
return appInUsed, nil
}
func (u *MysqlService) Delete(id uint) error {
app, err := appInstallRepo.LoadBaseInfoByKey("mysql")
if err != nil {
return err
}
dbs, err := mysqlRepo.List(commonRepo.WithIdsIn(ids))
db, err := mysqlRepo.Get(commonRepo.WithByID(id))
if err != nil {
return err
}
for _, db := range dbs {
if len(db.Name) != 0 {
if err := excuteSql(app.ContainerName, app.Password, fmt.Sprintf("drop user if exists '%s'@'%s'", db.Name, db.Permission)); err != nil {
return err
}
if err := excuteSql(app.ContainerName, app.Password, fmt.Sprintf("drop database if exists %s", db.Name)); err != nil {
return err
}
}
_ = mysqlRepo.Delete(context.Background(), commonRepo.WithByID(db.ID))
if err := excuteSql(app.ContainerName, app.Password, fmt.Sprintf("drop user if exists '%s'@'%s'", db.Name, db.Permission)); err != nil {
return err
}
if err := excuteSql(app.ContainerName, app.Password, fmt.Sprintf("drop database if exists %s", db.Name)); err != nil {
return err
}
_ = mysqlRepo.Delete(context.Background(), commonRepo.WithByID(db.ID))
return nil
}

View file

@ -26,7 +26,8 @@ func (s *DatabaseRouter) InitDatabaseRouter(Router *gin.RouterGroup) {
withRecordRouter.POST("/backup", baseApi.BackupMysql)
withRecordRouter.POST("/recover/byupload", baseApi.RecoverMysqlByUpload)
withRecordRouter.POST("/recover", baseApi.RecoverMysql)
withRecordRouter.POST("/del", baseApi.DeleteMysql)
withRecordRouter.POST("/del/check/:id", baseApi.DeleteCheckMysql)
withRecordRouter.POST("/del/:id", baseApi.DeleteMysql)
withRecordRouter.POST("/variables/update", baseApi.UpdateMysqlVariables)
withRecordRouter.POST("/conf/update/byfile", baseApi.UpdateMysqlConfByFile)
cmdRouter.POST("/search", baseApi.SearchMysql)

View file

@ -28,8 +28,11 @@ export const updateMysqlVariables = (params: Array<Database.VariablesUpdate>) =>
export const updateMysqlConfByFile = (params: Database.MysqlConfUpdateByFile) => {
return http.post(`/databases/conf/update/byfile`, params);
};
export const deleteMysqlDB = (params: { ids: number[] }) => {
return http.post(`/databases/del`, params);
export const deleteCheckMysqlDB = (id: number) => {
return http.post<Array<string>>(`/databases/del/check/${id}`);
};
export const deleteMysqlDB = (id: number) => {
return http.post(`/databases/del/${id}`);
};
export const loadMysqlBaseInfo = () => {

View file

@ -0,0 +1,48 @@
<template>
<el-dialog
v-model="open"
:title="$t('app.checkTitle')"
width="50%"
:close-on-click-modal="false"
:destroy-on-close="true"
>
<el-row>
<el-alert type="warning" :description="$t('app.deleteHelper')" center show-icon :closable="false" />
<el-col :span="12" :offset="6">
<br />
<el-descriptions border :column="1">
<el-descriptions-item>
<template #label>
<a href="javascript:void(0);" @click="toApp()">{{ $t('app.app') }}</a>
</template>
{{ installData.join(',') }}
</el-descriptions-item>
</el-descriptions>
</el-col>
</el-row>
</el-dialog>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();
interface InstallRrops {
items: Array<string>;
}
const installData = ref();
let open = ref(false);
const acceptParams = (props: InstallRrops) => {
installData.value = props.items;
open.value = true;
};
const toApp = () => {
router.push({ name: 'App' });
};
defineExpose({
acceptParams,
});
</script>

View file

@ -17,9 +17,6 @@
{{ $t('commons.button.create') }}
</el-button>
<el-button>phpMyAdmin</el-button>
<el-button type="danger" plain :disabled="selects.length === 0" @click="onBatchDelete(null)">
{{ $t('commons.button.delete') }}
</el-button>
</template>
<el-table-column type="selection" fix />
<el-table-column :label="$t('commons.table.name')" prop="name" />
@ -112,6 +109,8 @@
<UploadDialog ref="uploadRef" />
<OperatrDialog @search="search" ref="dialogRef" />
<BackupRecords ref="dialogBackupRef" />
<AppResources ref="checkRef"></AppResources>
</div>
</template>
@ -120,12 +119,13 @@ import ComplexTable from '@/components/complex-table/index.vue';
import OperatrDialog from '@/views/database/mysql/create/index.vue';
import BackupRecords from '@/views/database/mysql/backup/index.vue';
import UploadDialog from '@/views/database/mysql/upload/index.vue';
import AppResources from '@/views/database/mysql/check/index.vue';
import Setting from '@/views/database/mysql/setting/index.vue';
import AppStatus from '@/components/app-status/index.vue';
import Submenu from '@/views/database/index.vue';
import { dateFromat } from '@/utils/util';
import { reactive, ref } from 'vue';
import { deleteMysqlDB, searchMysqlDBs, updateMysqlDBInfo } from '@/api/modules/database';
import { deleteCheckMysqlDB, deleteMysqlDB, searchMysqlDBs, updateMysqlDBInfo } from '@/api/modules/database';
import i18n from '@/lang';
import { useDeleteData } from '@/hooks/use-delete-data';
import { ElForm, ElMessage } from 'element-plus';
@ -137,6 +137,8 @@ const selects = ref<any>([]);
const mysqlName = ref();
const isOnSetting = ref<boolean>();
const checkRef = ref();
const data = ref();
const paginationConfig = reactive({
currentPage: 1,
@ -218,17 +220,14 @@ const checkExist = (data: App.CheckInstalled) => {
}
};
const onBatchDelete = async (row: Database.MysqlDBInfo | null) => {
let ids: Array<number> = [];
if (row) {
ids.push(row.id);
const onDelete = async (row: Database.MysqlDBInfo) => {
const res = await deleteCheckMysqlDB(row.id);
if (res.data && res.data.length > 0) {
checkRef.value.acceptParams({ items: res.data });
} else {
selects.value.forEach((item: Database.MysqlDBInfo) => {
ids.push(item.id);
});
await useDeleteData(deleteMysqlDB, row.id, 'app.deleteWarn');
search();
}
await useDeleteData(deleteMysqlDB, { ids: ids }, 'commons.msg.delete');
search();
};
const buttons = [
{
@ -273,7 +272,7 @@ const buttons = [
{
label: i18n.global.t('commons.button.delete'),
click: (row: Database.MysqlDBInfo) => {
onBatchDelete(row);
onDelete(row);
},
},
];