fix: 数据库部分逻辑调整 (#2316)

This commit is contained in:
ssongliu 2023-09-16 13:16:15 +08:00 committed by GitHub
parent 173e3e9cc1
commit 52198e9c0c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 582 additions and 469 deletions

View File

@ -233,11 +233,11 @@ func (b *BaseApi) ListDBName(c *gin.Context) {
// @Summary Load mysql database from remote // @Summary Load mysql database from remote
// @Description 从服务器获取 // @Description 从服务器获取
// @Accept json // @Accept json
// @Param request body dto.OperateByID true "request" // @Param request body dto.MysqlLoadDB true "request"
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Router /databases/load [post] // @Router /databases/load [post]
func (b *BaseApi) LoadDBFromRemote(c *gin.Context) { func (b *BaseApi) LoadDBFromRemote(c *gin.Context) {
var req dto.OperateByID var req dto.MysqlLoadDB
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return return
@ -315,12 +315,12 @@ func (b *BaseApi) DeleteMysql(c *gin.Context) {
// @Summary Load mysql base info // @Summary Load mysql base info
// @Description 获取 mysql 基础信息 // @Description 获取 mysql 基础信息
// @Accept json // @Accept json
// @Param request body dto.OperateByID true "request" // @Param request body dto.OperationWithNameAndType true "request"
// @Success 200 {object} dto.DBBaseInfo // @Success 200 {object} dto.DBBaseInfo
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Router /databases/baseinfo [post] // @Router /databases/baseinfo [post]
func (b *BaseApi) LoadBaseinfo(c *gin.Context) { func (b *BaseApi) LoadBaseinfo(c *gin.Context) {
var req dto.OperateByID var req dto.OperationWithNameAndType
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return return
@ -360,12 +360,12 @@ func (b *BaseApi) LoadDatabaseFile(c *gin.Context) {
// @Summary Load mysql remote access // @Summary Load mysql remote access
// @Description 获取 mysql 远程访问权限 // @Description 获取 mysql 远程访问权限
// @Accept json // @Accept json
// @Param request body dto.OperateByID true "request" // @Param request body dto.OperationWithNameAndType true "request"
// @Success 200 {boolean} isRemote // @Success 200 {boolean} isRemote
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Router /databases/remote [post] // @Router /databases/remote [post]
func (b *BaseApi) LoadRemoteAccess(c *gin.Context) { func (b *BaseApi) LoadRemoteAccess(c *gin.Context) {
var req dto.OperateByID var req dto.OperationWithNameAndType
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return return
@ -383,12 +383,12 @@ func (b *BaseApi) LoadRemoteAccess(c *gin.Context) {
// @Summary Load mysql status info // @Summary Load mysql status info
// @Description 获取 mysql 状态信息 // @Description 获取 mysql 状态信息
// @Accept json // @Accept json
// @Param request body dto.OperateByID true "request" // @Param request body dto.OperationWithNameAndType true "request"
// @Success 200 {object} dto.MysqlStatus // @Success 200 {object} dto.MysqlStatus
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Router /databases/status [post] // @Router /databases/status [post]
func (b *BaseApi) LoadStatus(c *gin.Context) { func (b *BaseApi) LoadStatus(c *gin.Context) {
var req dto.OperateByID var req dto.OperationWithNameAndType
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return return
@ -406,12 +406,12 @@ func (b *BaseApi) LoadStatus(c *gin.Context) {
// @Summary Load mysql variables info // @Summary Load mysql variables info
// @Description 获取 mysql 性能参数信息 // @Description 获取 mysql 性能参数信息
// @Accept json // @Accept json
// @Param request body dto.OperateByID true "request" // @Param request body dto.OperationWithNameAndType true "request"
// @Success 200 {object} dto.MysqlVariables // @Success 200 {object} dto.MysqlVariables
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Router /databases/variables [post] // @Router /databases/variables [post]
func (b *BaseApi) LoadVariables(c *gin.Context) { func (b *BaseApi) LoadVariables(c *gin.Context) {
var req dto.OperateByID var req dto.OperationWithNameAndType
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return return

View File

@ -4,10 +4,10 @@ import "time"
type MysqlDBSearch struct { type MysqlDBSearch struct {
PageInfo PageInfo
Info string `json:"info"` Info string `json:"info"`
DatabaseID uint `json:"databaseID" validate:"required"` Database string `json:"database" validate:"required"`
OrderBy string `json:"orderBy"` OrderBy string `json:"orderBy"`
Order string `json:"order"` Order string `json:"order"`
} }
type MysqlDBInfo struct { type MysqlDBInfo struct {
@ -15,7 +15,7 @@ type MysqlDBInfo struct {
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
Name string `json:"name"` Name string `json:"name"`
From string `json:"from"` From string `json:"from"`
DatabaseID uint `json:"databaseID"` MysqlName string `json:"mysqlName"`
Format string `json:"format"` Format string `json:"format"`
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
@ -25,18 +25,17 @@ type MysqlDBInfo struct {
} }
type MysqlOption struct { type MysqlOption struct {
ID uint `json:"id"` ID uint `json:"id"`
From string `json:"from"` From string `json:"from"`
Type string `json:"type"` Type string `json:"type"`
DatabaseID uint `json:"databaseID"` Database string `json:"database"`
Database string `json:"database"` Name string `json:"name"`
Name string `json:"name"`
} }
type MysqlDBCreate struct { type MysqlDBCreate struct {
Name string `json:"name" validate:"required"` Name string `json:"name" validate:"required"`
From string `json:"from" validate:"required,oneof=local remote"` From string `json:"from" validate:"required,oneof=local remote"`
DatabaseID uint `json:"databaseID" validate:"required"` Database string `json:"database" validate:"required"`
Format string `json:"format" validate:"required,oneof=utf8mb4 utf8 gbk big5"` Format string `json:"format" validate:"required,oneof=utf8mb4 utf8 gbk big5"`
Username string `json:"username" validate:"required"` Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"` Password string `json:"password" validate:"required"`
@ -44,15 +43,24 @@ type MysqlDBCreate struct {
Description string `json:"description"` Description string `json:"description"`
} }
type MysqlLoadDB struct {
From string `json:"from" validate:"required,oneof=local remote"`
Type string `json:"type" validate:"required,oneof=mysql mariadb"`
Database string `json:"database" validate:"required"`
}
type MysqlDBDeleteCheck struct { type MysqlDBDeleteCheck struct {
ID uint `json:"id" validate:"required"` ID uint `json:"id" validate:"required"`
DatabaseID uint `json:"databaseID" validate:"required"` Type string `json:"type" validate:"required,oneof=mysql mariadb"`
Database string `json:"database" validate:"required"`
} }
type MysqlDBDelete struct { type MysqlDBDelete struct {
ID uint `json:"id" validate:"required"` ID uint `json:"id" validate:"required"`
ForceDelete bool `json:"forceDelete"` Type string `json:"type" validate:"required,oneof=mysql mariadb"`
DeleteBackup bool `json:"deleteBackup"` Database string `json:"database" validate:"required"`
ForceDelete bool `json:"forceDelete"`
DeleteBackup bool `json:"deleteBackup"`
} }
type MysqlStatus struct { type MysqlStatus struct {
@ -116,8 +124,9 @@ type MysqlVariables struct {
} }
type MysqlVariablesUpdate struct { type MysqlVariablesUpdate struct {
DatabaseID uint `json:"databaseID" validate:"required"` Type string `json:"type" validate:"required,oneof=mysql mariadb"`
Variables []MysqlVariablesUpdateHelper `json:"variables"` Database string `json:"database" validate:"required"`
Variables []MysqlVariablesUpdateHelper `json:"variables"`
} }
type MysqlVariablesUpdateHelper struct { type MysqlVariablesUpdateHelper struct {
@ -125,16 +134,17 @@ type MysqlVariablesUpdateHelper struct {
Value interface{} `json:"value"` Value interface{} `json:"value"`
} }
type MysqlConfUpdateByFile struct { type MysqlConfUpdateByFile struct {
DatabaseID uint `json:"databaseID" validate:"required"` Type string `json:"type" validate:"required,oneof=mysql mariadb"`
File string `json:"file"` Database string `json:"database" validate:"required"`
File string `json:"file"`
} }
type ChangeDBInfo struct { type ChangeDBInfo struct {
ID uint `json:"id"` ID uint `json:"id"`
From string `json:"from" validate:"required,oneof=local remote"` From string `json:"from" validate:"required,oneof=local remote"`
Type string `json:"type" validate:"required,oneof=mysql mariadb"` Type string `json:"type" validate:"required,oneof=mysql mariadb"`
DatabaseID uint `json:"databaseID" validate:"required"` Database string `json:"database" validate:"required"`
Value string `json:"value" validate:"required"` Value string `json:"value" validate:"required"`
} }
type DBBaseInfo struct { type DBBaseInfo struct {

View File

@ -3,7 +3,7 @@ package model
type Database struct { type Database struct {
BaseModel BaseModel
AppInstallID uint `json:"appInstallID" gorm:"type:decimal"` AppInstallID uint `json:"appInstallID" gorm:"type:decimal"`
Name string `json:"name" gorm:"type:varchar(64);not null"` Name string `json:"name" gorm:"type:varchar(64);not null;unique"`
Type string `json:"type" gorm:"type:varchar(64);not null"` Type string `json:"type" gorm:"type:varchar(64);not null"`
Version string `json:"version" gorm:"type:varchar(64);not null"` Version string `json:"version" gorm:"type:varchar(64);not null"`
From string `json:"from" gorm:"type:varchar(64);not null"` From string `json:"from" gorm:"type:varchar(64);not null"`

View File

@ -4,12 +4,10 @@ type DatabaseMysql struct {
BaseModel BaseModel
Name string `json:"name" gorm:"type:varchar(256);not null"` Name string `json:"name" gorm:"type:varchar(256);not null"`
From string `json:"from" gorm:"type:varchar(256);not null;default:local"` From string `json:"from" gorm:"type:varchar(256);not null;default:local"`
MysqlName string `json:"mysqlName" gorm:"type:varchar(64);not null"` // 已废弃 MysqlName string `json:"mysqlName" gorm:"type:varchar(64);not null"`
Format string `json:"format" gorm:"type:varchar(64);not null"` Format string `json:"format" gorm:"type:varchar(64);not null"`
Username string `json:"username" gorm:"type:varchar(256);not null"` Username string `json:"username" gorm:"type:varchar(256);not null"`
Password string `json:"password" gorm:"type:varchar(256);not null"` Password string `json:"password" gorm:"type:varchar(256);not null"`
Permission string `json:"permission" gorm:"type:varchar(256);not null"` Permission string `json:"permission" gorm:"type:varchar(256);not null"`
Description string `json:"description" gorm:"type:varchar(256);"` Description string `json:"description" gorm:"type:varchar(256);"`
DatabaseID uint `json:"databaseID" gorm:"type:decimal"`
} }

View File

@ -14,7 +14,7 @@ type MysqlRepo struct{}
type IMysqlRepo interface { type IMysqlRepo interface {
Get(opts ...DBOption) (model.DatabaseMysql, error) Get(opts ...DBOption) (model.DatabaseMysql, error)
WithByDatabase(databaseID uint) DBOption WithByMysqlName(mysqlName string) DBOption
WithByFrom(from string) DBOption WithByFrom(from string) DBOption
List(opts ...DBOption) ([]model.DatabaseMysql, error) List(opts ...DBOption) ([]model.DatabaseMysql, error)
Page(limit, offset int, opts ...DBOption) (int64, []model.DatabaseMysql, error) Page(limit, offset int, opts ...DBOption) (int64, []model.DatabaseMysql, error)
@ -107,9 +107,9 @@ func (u *MysqlRepo) Update(id uint, vars map[string]interface{}) error {
return global.DB.Model(&model.DatabaseMysql{}).Where("id = ?", id).Updates(vars).Error return global.DB.Model(&model.DatabaseMysql{}).Where("id = ?", id).Updates(vars).Error
} }
func (u *MysqlRepo) WithByDatabase(databaseID uint) DBOption { func (u *MysqlRepo) WithByMysqlName(mysqlName string) DBOption {
return func(g *gorm.DB) *gorm.DB { return func(g *gorm.DB) *gorm.DB {
return g.Where("database_id = ?", databaseID) return g.Where("mysql_name = ?", mysqlName)
} }
} }

View File

@ -187,25 +187,19 @@ func createLink(ctx context.Context, app model.App, appInstall *model.AppInstall
return buserr.New(constant.ErrDbUserNotValid) return buserr.New(constant.ErrDbUserNotValid)
} }
} else { } else {
if databaseID, ok := params["PANEL_DB_HOST_ID"]; ok { var createMysql dto.MysqlDBCreate
database, err := databaseRepo.Get(commonRepo.WithByID(databaseID.(uint))) createMysql.Name = dbConfig.DbName
if err != nil { createMysql.Username = dbConfig.DbUser
return err createMysql.Database = dbInstall.Name
} createMysql.Format = "utf8mb4"
var createMysql dto.MysqlDBCreate createMysql.Permission = "%"
createMysql.Name = dbConfig.DbName createMysql.Password = dbConfig.Password
createMysql.Username = dbConfig.DbUser createMysql.From = "local"
createMysql.DatabaseID = database.ID mysqldb, err := NewIMysqlService().Create(ctx, createMysql)
createMysql.Format = "utf8mb4" if err != nil {
createMysql.Permission = "%" return err
createMysql.Password = dbConfig.Password
createMysql.From = "local"
mysqldb, err := NewIMysqlService().Create(ctx, createMysql)
if err != nil {
return err
}
resourceId = mysqldb.ID
} }
resourceId = mysqldb.ID
} }
} }
var installResource model.AppInstallResource var installResource model.AppInstallResource
@ -258,6 +252,7 @@ func deleteAppInstall(install model.AppInstall, deleteBackup bool, forceDelete b
if err := deleteLink(ctx, &install, deleteDB, forceDelete, deleteBackup); err != nil && !forceDelete { if err := deleteLink(ctx, &install, deleteDB, forceDelete, deleteBackup); err != nil && !forceDelete {
return err return err
} }
if DatabaseKeys[install.App.Key] > 0 { if DatabaseKeys[install.App.Key] > 0 {
_ = databaseRepo.Delete(ctx, databaseRepo.WithAppInstallID(install.ID)) _ = databaseRepo.Delete(ctx, databaseRepo.WithAppInstallID(install.ID))
} }
@ -267,10 +262,7 @@ func deleteAppInstall(install model.AppInstall, deleteBackup bool, forceDelete b
_ = websiteRepo.DeleteAll(ctx) _ = websiteRepo.DeleteAll(ctx)
_ = websiteDomainRepo.DeleteAll(ctx) _ = websiteDomainRepo.DeleteAll(ctx)
case constant.AppMysql, constant.AppMariaDB: case constant.AppMysql, constant.AppMariaDB:
database, _ := databaseRepo.Get(databaseRepo.WithAppInstallID(install.ID)) _ = mysqlRepo.Delete(ctx, mysqlRepo.WithByMysqlName(install.Name))
if database.ID > 0 {
_ = mysqlRepo.Delete(ctx, mysqlRepo.WithByDatabase(database.ID))
}
} }
_ = backupRepo.DeleteRecord(ctx, commonRepo.WithByType("app"), commonRepo.WithByName(install.App.Key), backupRepo.WithByDetailName(install.Name)) _ = backupRepo.DeleteRecord(ctx, commonRepo.WithByType("app"), commonRepo.WithByName(install.App.Key), backupRepo.WithByDetailName(install.Name))
@ -292,6 +284,7 @@ func deleteAppInstall(install model.AppInstall, deleteBackup bool, forceDelete b
} }
func deleteLink(ctx context.Context, install *model.AppInstall, deleteDB bool, forceDelete bool, deleteBackup bool) error { func deleteLink(ctx context.Context, install *model.AppInstall, deleteDB bool, forceDelete bool, deleteBackup bool) error {
resources, _ := appInstallResourceRepo.GetBy(appInstallResourceRepo.WithAppInstallId(install.ID)) resources, _ := appInstallResourceRepo.GetBy(appInstallResourceRepo.WithAppInstallId(install.ID))
if len(resources) == 0 { if len(resources) == 0 {
return nil return nil
@ -299,14 +292,16 @@ func deleteLink(ctx context.Context, install *model.AppInstall, deleteDB bool, f
for _, re := range resources { for _, re := range resources {
mysqlService := NewIMysqlService() mysqlService := NewIMysqlService()
if (re.Key == constant.AppMysql || re.Key == constant.AppMariaDB) && deleteDB { if (re.Key == constant.AppMysql || re.Key == constant.AppMariaDB) && deleteDB {
mysqlDatabase, _ := mysqlRepo.Get(commonRepo.WithByID(re.ResourceId)) database, _ := mysqlRepo.Get(commonRepo.WithByID(re.ResourceId))
if mysqlDatabase.ID == 0 { if reflect.DeepEqual(database, model.DatabaseMysql{}) {
continue continue
} }
if err := mysqlService.Delete(ctx, dto.MysqlDBDelete{ if err := mysqlService.Delete(ctx, dto.MysqlDBDelete{
ID: mysqlDatabase.ID, ID: database.ID,
ForceDelete: forceDelete, ForceDelete: forceDelete,
DeleteBackup: deleteBackup, DeleteBackup: deleteBackup,
Type: re.Key,
Database: database.MysqlName,
}); err != nil && !forceDelete { }); err != nil && !forceDelete {
return err return err
} }

View File

@ -111,7 +111,7 @@ func handleAppBackup(install *model.AppInstall, backupDir, fileName string) erro
if err != nil { if err != nil {
return err return err
} }
if err := handleMysqlBackup(db.DatabaseID, db.Name, tmpDir, fmt.Sprintf("%s.sql.gz", install.Name)); err != nil { if err := handleMysqlBackup(db.MysqlName, db.Name, tmpDir, fmt.Sprintf("%s.sql.gz", install.Name)); err != nil {
return err return err
} }
} }
@ -190,7 +190,7 @@ func handleAppRecover(install *model.AppInstall, recoverFile string, isRollback
return err return err
} }
newDB, envMap, err := reCreateDB(db, resourceApp, oldInstall.Env) newDB, envMap, err := reCreateDB(db.ID, resourceApp, oldInstall.Env)
if err != nil { if err != nil {
return err return err
} }
@ -205,7 +205,7 @@ func handleAppRecover(install *model.AppInstall, recoverFile string, isRollback
_ = appInstallResourceRepo.BatchUpdateBy(map[string]interface{}{"resource_id": newDB.ID}, commonRepo.WithByID(resource.ID)) _ = appInstallResourceRepo.BatchUpdateBy(map[string]interface{}{"resource_id": newDB.ID}, commonRepo.WithByID(resource.ID))
if err := handleMysqlRecover(dto.CommonRecover{ if err := handleMysqlRecover(dto.CommonRecover{
Name: fmt.Sprintf("%d", newDB.DatabaseID), Name: newDB.MysqlName,
DetailName: newDB.Name, DetailName: newDB.Name,
File: fmt.Sprintf("%s/%s.sql.gz", tmpPath, install.Name), File: fmt.Sprintf("%s/%s.sql.gz", tmpPath, install.Name),
}, true); err != nil { }, true); err != nil {
@ -252,10 +252,10 @@ func handleAppRecover(install *model.AppInstall, recoverFile string, isRollback
return nil return nil
} }
func reCreateDB(db model.DatabaseMysql, app model.AppInstall, oldEnv string) (*model.DatabaseMysql, map[string]interface{}, error) { func reCreateDB(dbID uint, app model.AppInstall, oldEnv string) (*model.DatabaseMysql, map[string]interface{}, error) {
mysqlService := NewIMysqlService() mysqlService := NewIMysqlService()
ctx := context.Background() ctx := context.Background()
_ = mysqlService.Delete(ctx, dto.MysqlDBDelete{ID: db.ID, DeleteBackup: true, ForceDelete: true}) _ = mysqlService.Delete(ctx, dto.MysqlDBDelete{ID: dbID, Database: app.Name, Type: app.App.Key, DeleteBackup: true, ForceDelete: true})
envMap := make(map[string]interface{}) envMap := make(map[string]interface{})
if err := json.Unmarshal([]byte(oldEnv), &envMap); err != nil { if err := json.Unmarshal([]byte(oldEnv), &envMap); err != nil {
@ -267,7 +267,7 @@ func reCreateDB(db model.DatabaseMysql, app model.AppInstall, oldEnv string) (*m
createDB, err := mysqlService.Create(context.Background(), dto.MysqlDBCreate{ createDB, err := mysqlService.Create(context.Background(), dto.MysqlDBCreate{
Name: oldName, Name: oldName,
From: "local", From: "local",
DatabaseID: db.DatabaseID, Database: app.Name,
Format: "utf8mb4", Format: "utf8mb4",
Username: oldUser, Username: oldUser,
Password: oldPassword, Password: oldPassword,

View File

@ -5,7 +5,6 @@ import (
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"time" "time"
@ -24,25 +23,16 @@ func (u *BackupService) MysqlBackup(req dto.CommonBackup) error {
} }
timeNow := time.Now().Format("20060102150405") timeNow := time.Now().Format("20060102150405")
databaseID, err := strconv.Atoi(req.Name) targetDir := path.Join(localDir, fmt.Sprintf("database/%s/%s/%s", req.Type, req.Name, req.DetailName))
if err != nil {
return err
}
database, err := databaseRepo.Get(commonRepo.WithByID(uint(databaseID)))
if err != nil {
return err
}
dirName := fmt.Sprintf("%s-%s", database.From, database.Name)
targetDir := path.Join(localDir, fmt.Sprintf("database/%s/%s/%s", req.Type, dirName, req.DetailName))
fileName := fmt.Sprintf("%s_%s.sql.gz", req.DetailName, timeNow) fileName := fmt.Sprintf("%s_%s.sql.gz", req.DetailName, timeNow)
if err := handleMysqlBackup(uint(databaseID), req.DetailName, targetDir, fileName); err != nil { if err := handleMysqlBackup(req.Name, req.DetailName, targetDir, fileName); err != nil {
return err return err
} }
record := &model.BackupRecord{ record := &model.BackupRecord{
Type: req.Type, Type: req.Type,
Name: fmt.Sprintf("%v", database.ID), Name: req.Name,
DetailName: req.DetailName, DetailName: req.DetailName,
Source: "LOCAL", Source: "LOCAL",
BackupType: "LOCAL", BackupType: "LOCAL",
@ -107,12 +97,12 @@ func (u *BackupService) MysqlRecoverByUpload(req dto.CommonRecover) error {
return nil return nil
} }
func handleMysqlBackup(databaseID uint, dbName, targetDir, fileName string) error { func handleMysqlBackup(database, dbName, targetDir, fileName string) error {
cli, _, _, err := LoadMysqlClientByFrom(databaseID) dbInfo, err := mysqlRepo.Get(commonRepo.WithByName(dbName), mysqlRepo.WithByMysqlName(database))
if err != nil { if err != nil {
return err return err
} }
dbInfo, err := mysqlRepo.Get(commonRepo.WithByName(dbName), mysqlRepo.WithByDatabase(databaseID)) cli, _, err := LoadMysqlClientByFrom(database)
if err != nil { if err != nil {
return err return err
} }
@ -137,15 +127,11 @@ func handleMysqlRecover(req dto.CommonRecover, isRollback bool) error {
if !fileOp.Stat(req.File) { if !fileOp.Stat(req.File) {
return errors.New(fmt.Sprintf("%s file is not exist", req.File)) return errors.New(fmt.Sprintf("%s file is not exist", req.File))
} }
databaseID, err := strconv.Atoi(req.Name) dbInfo, err := mysqlRepo.Get(commonRepo.WithByName(req.DetailName), mysqlRepo.WithByMysqlName(req.Name))
if err != nil { if err != nil {
return err return err
} }
cli, _, _, err := LoadMysqlClientByFrom(uint(databaseID)) cli, _, err := LoadMysqlClientByFrom(req.Name)
if err != nil {
return err
}
dbInfo, err := mysqlRepo.Get(commonRepo.WithByName(req.DetailName), mysqlRepo.WithByDatabase(uint(databaseID)))
if err != nil { if err != nil {
return err return err
} }

View File

@ -292,16 +292,16 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, backup model.Back
for _, dbInfo := range dbs { for _, dbInfo := range dbs {
var record model.BackupRecord var record model.BackupRecord
database, _ := databaseRepo.Get(commonRepo.WithByID(dbInfo.DatabaseID))
database, _ := databaseRepo.Get(commonRepo.WithByName(dbInfo.MysqlName))
record.Type = database.Type record.Type = database.Type
record.Source = "LOCAL" record.Source = "LOCAL"
record.BackupType = backup.Type record.BackupType = backup.Type
dirName := fmt.Sprintf("%s-%s", database.From, database.Name) record.Name = dbInfo.MysqlName
record.Name = fmt.Sprintf("%v", database.ID) backupDir := path.Join(localDir, fmt.Sprintf("database/%s/%s/%s", database.Type, record.Name, dbInfo.Name))
backupDir := path.Join(localDir, fmt.Sprintf("database/%s/%s/%s", database.Type, dirName, dbInfo.Name))
record.FileName = fmt.Sprintf("db_%s_%s.sql.gz", dbInfo.Name, startTime.Format("20060102150405")) record.FileName = fmt.Sprintf("db_%s_%s.sql.gz", dbInfo.Name, startTime.Format("20060102150405"))
if err = handleMysqlBackup(dbInfo.DatabaseID, dbInfo.Name, backupDir, record.FileName); err != nil { if err = handleMysqlBackup(dbInfo.MysqlName, dbInfo.Name, backupDir, record.FileName); err != nil {
return paths, err return paths, err
} }

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/backend/app/dto" "github.com/1Panel-dev/1Panel/backend/app/dto"
"github.com/1Panel-dev/1Panel/backend/buserr"
"github.com/1Panel-dev/1Panel/backend/constant" "github.com/1Panel-dev/1Panel/backend/constant"
"github.com/1Panel-dev/1Panel/backend/utils/encrypt" "github.com/1Panel-dev/1Panel/backend/utils/encrypt"
"github.com/1Panel-dev/1Panel/backend/utils/mysql" "github.com/1Panel-dev/1Panel/backend/utils/mysql"
@ -87,12 +88,15 @@ func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool {
} }
func (u *DatabaseService) Create(req dto.DatabaseCreate) error { func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
db, _ := databaseRepo.Get(commonRepo.WithByName(req.Name), commonRepo.WithByType(req.Type), databaseRepo.WithByFrom(req.From)) db, _ := databaseRepo.Get(commonRepo.WithByName(req.Name))
if db.ID != 0 { if db.ID != 0 {
if db.From == "local" {
return buserr.New(constant.ErrLocalExist)
}
return constant.ErrRecordExist return constant.ErrRecordExist
} }
if _, err := mysql.NewMysqlClient(client.DBInfo{ if _, err := mysql.NewMysqlClient(client.DBInfo{
From: req.From, From: "remote",
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
Username: req.Username, Username: req.Username,
@ -119,7 +123,7 @@ func (u *DatabaseService) Delete(id uint) error {
return err return err
} }
if db.From != "local" { if db.From != "local" {
if err := mysqlRepo.Delete(context.Background(), mysqlRepo.WithByDatabase(db.ID)); err != nil { if err := mysqlRepo.Delete(context.Background(), mysqlRepo.WithByMysqlName(db.Name)); err != nil {
return err return err
} }
} }

View File

@ -35,6 +35,7 @@ type IMysqlService interface {
SearchWithPage(search dto.MysqlDBSearch) (int64, interface{}, error) SearchWithPage(search dto.MysqlDBSearch) (int64, interface{}, error)
ListDBOption() ([]dto.MysqlOption, error) ListDBOption() ([]dto.MysqlOption, error)
Create(ctx context.Context, req dto.MysqlDBCreate) (*model.DatabaseMysql, error) Create(ctx context.Context, req dto.MysqlDBCreate) (*model.DatabaseMysql, error)
LoadFromRemote(req dto.MysqlLoadDB) error
ChangeAccess(info dto.ChangeDBInfo) error ChangeAccess(info dto.ChangeDBInfo) error
ChangePassword(info dto.ChangeDBInfo) error ChangePassword(info dto.ChangeDBInfo) error
UpdateVariables(req dto.MysqlVariablesUpdate) error UpdateVariables(req dto.MysqlVariablesUpdate) error
@ -43,11 +44,10 @@ type IMysqlService interface {
DeleteCheck(req dto.MysqlDBDeleteCheck) ([]string, error) DeleteCheck(req dto.MysqlDBDeleteCheck) ([]string, error)
Delete(ctx context.Context, req dto.MysqlDBDelete) error Delete(ctx context.Context, req dto.MysqlDBDelete) error
LoadFromRemote(req dto.OperateByID) error LoadStatus(req dto.OperationWithNameAndType) (*dto.MysqlStatus, error)
LoadStatus(req dto.OperateByID) (*dto.MysqlStatus, error) LoadVariables(req dto.OperationWithNameAndType) (*dto.MysqlVariables, error)
LoadVariables(req dto.OperateByID) (*dto.MysqlVariables, error) LoadBaseInfo(req dto.OperationWithNameAndType) (*dto.DBBaseInfo, error)
LoadBaseInfo(req dto.OperateByID) (*dto.DBBaseInfo, error) LoadRemoteAccess(req dto.OperationWithNameAndType) (bool, error)
LoadRemoteAccess(req dto.OperateByID) (bool, error)
LoadDatabaseFile(req dto.OperationWithNameAndType) (string, error) LoadDatabaseFile(req dto.OperationWithNameAndType) (string, error)
} }
@ -58,11 +58,10 @@ func NewIMysqlService() IMysqlService {
func (u *MysqlService) SearchWithPage(search dto.MysqlDBSearch) (int64, interface{}, error) { func (u *MysqlService) SearchWithPage(search dto.MysqlDBSearch) (int64, interface{}, error) {
total, mysqls, err := mysqlRepo.Page(search.Page, search.PageSize, total, mysqls, err := mysqlRepo.Page(search.Page, search.PageSize,
mysqlRepo.WithByDatabase(search.DatabaseID), mysqlRepo.WithByMysqlName(search.Database),
commonRepo.WithLikeName(search.Info), commonRepo.WithLikeName(search.Info),
commonRepo.WithOrderRuleBy(search.OrderBy, search.Order), commonRepo.WithOrderRuleBy(search.OrderBy, search.Order),
) )
var dtoMysqls []dto.MysqlDBInfo var dtoMysqls []dto.MysqlDBInfo
for _, mysql := range mysqls { for _, mysql := range mysqls {
var item dto.MysqlDBInfo var item dto.MysqlDBInfo
@ -90,10 +89,10 @@ func (u *MysqlService) ListDBOption() ([]dto.MysqlOption, error) {
if err := copier.Copy(&item, &mysql); err != nil { if err := copier.Copy(&item, &mysql); err != nil {
return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) return nil, errors.WithMessage(constant.ErrStructTransform, err.Error())
} }
item.Database = mysql.MysqlName
for _, database := range databases { for _, database := range databases {
if database.ID == item.DatabaseID { if database.Name == item.Database {
item.Type = database.Type item.Type = database.Type
item.Database = database.Name
} }
} }
dbs = append(dbs, item) dbs = append(dbs, item)
@ -106,7 +105,7 @@ func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*mode
return nil, buserr.New(constant.ErrCmdIllegal) return nil, buserr.New(constant.ErrCmdIllegal)
} }
mysql, _ := mysqlRepo.Get(commonRepo.WithByName(req.Name), mysqlRepo.WithByDatabase(req.DatabaseID)) mysql, _ := mysqlRepo.Get(commonRepo.WithByName(req.Name), mysqlRepo.WithByMysqlName(req.Database), databaseRepo.WithByFrom(req.From))
if mysql.ID != 0 { if mysql.ID != 0 {
return nil, constant.ErrRecordExist return nil, constant.ErrRecordExist
} }
@ -116,14 +115,15 @@ func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*mode
return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) return nil, errors.WithMessage(constant.ErrStructTransform, err.Error())
} }
if req.Username == "root" { if req.From == "local" && req.Username == "root" {
return nil, errors.New("Cannot set root as user name") return nil, errors.New("Cannot set root as user name")
} }
cli, version, _, err := LoadMysqlClientByFrom(req.DatabaseID) cli, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil { if err != nil {
return nil, err return nil, err
} }
createItem.MysqlName = req.Database
defer cli.Close() defer cli.Close()
if err := cli.Create(client.CreateInfo{ if err := cli.Create(client.CreateInfo{
Name: req.Name, Name: req.Name,
@ -144,13 +144,13 @@ func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*mode
return &createItem, nil return &createItem, nil
} }
func (u *MysqlService) LoadFromRemote(req dto.OperateByID) error { func (u *MysqlService) LoadFromRemote(req dto.MysqlLoadDB) error {
client, version, _, err := LoadMysqlClientByFrom(req.ID) client, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil { if err != nil {
return err return err
} }
dbs, err := mysqlRepo.List(mysqlRepo.WithByDatabase(req.ID)) databases, err := mysqlRepo.List(databaseRepo.WithByFrom(req.From))
if err != nil { if err != nil {
return err return err
} }
@ -160,8 +160,8 @@ func (u *MysqlService) LoadFromRemote(req dto.OperateByID) error {
} }
for _, data := range datas { for _, data := range datas {
hasOld := false hasOld := false
for _, oldData := range dbs { for _, oldData := range databases {
if strings.EqualFold(oldData.Name, data.Name) { if strings.EqualFold(oldData.Name, data.Name) && strings.EqualFold(oldData.MysqlName, data.MysqlName) {
hasOld = true hasOld = true
break break
} }
@ -171,7 +171,6 @@ func (u *MysqlService) LoadFromRemote(req dto.OperateByID) error {
if err := copier.Copy(&createItem, &data); err != nil { if err := copier.Copy(&createItem, &data); err != nil {
return errors.WithMessage(constant.ErrStructTransform, err.Error()) return errors.WithMessage(constant.ErrStructTransform, err.Error())
} }
createItem.DatabaseID = req.ID
if err := mysqlRepo.Create(context.Background(), &createItem); err != nil { if err := mysqlRepo.Create(context.Background(), &createItem); err != nil {
return err return err
} }
@ -190,12 +189,9 @@ func (u *MysqlService) DeleteCheck(req dto.MysqlDBDeleteCheck) ([]string, error)
if err != nil { if err != nil {
return appInUsed, err return appInUsed, err
} }
database, err := databaseRepo.Get(commonRepo.WithByID(req.DatabaseID))
if err != nil {
return appInUsed, err
}
if db.From == "local" { if db.From == "local" {
app, err := appInstallRepo.LoadBaseInfo(database.Type, database.Name) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Database)
if err != nil { if err != nil {
return appInUsed, err return appInUsed, err
} }
@ -224,11 +220,7 @@ func (u *MysqlService) Delete(ctx context.Context, req dto.MysqlDBDelete) error
if err != nil && !req.ForceDelete { if err != nil && !req.ForceDelete {
return err return err
} }
database, err := databaseRepo.Get(commonRepo.WithByID(db.DatabaseID)) cli, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil && !req.ForceDelete {
return err
}
cli, version, _, err := LoadMysqlClientByFrom(db.DatabaseID)
if err != nil { if err != nil {
return err return err
} }
@ -243,24 +235,22 @@ func (u *MysqlService) Delete(ctx context.Context, req dto.MysqlDBDelete) error
return err return err
} }
uploadDir2 := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/database/%s/%s-%s/%s", database.Type, database.From, database.Name, db.Name)) uploadDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/database/%s/%s/%s", req.Type, req.Database, db.Name))
if _, err := os.Stat(uploadDir2); err == nil { if _, err := os.Stat(uploadDir); err == nil {
_ = os.RemoveAll(uploadDir2) _ = os.RemoveAll(uploadDir)
} }
if req.DeleteBackup { if req.DeleteBackup {
localDir, err := loadLocalDir() localDir, err := loadLocalDir()
if err != nil && !req.ForceDelete { if err != nil && !req.ForceDelete {
return err return err
} }
backupDir := path.Join(localDir, fmt.Sprintf("database/%s/%s-%s/%s", database.Type, db.From, database.Name, db.Name)) backupDir := path.Join(localDir, fmt.Sprintf("database/%s/%s/%s", req.Type, db.MysqlName, db.Name))
if _, err := os.Stat(backupDir); err == nil { if _, err := os.Stat(backupDir); err == nil {
_ = os.RemoveAll(backupDir) _ = os.RemoveAll(backupDir)
} }
global.LOG.Infof("delete database %s-%s backups successful", database.Name, db.Name) global.LOG.Infof("delete database %s-%s backups successful", req.Database, db.Name)
} }
_ = backupRepo.DeleteRecord(ctx, commonRepo.WithByType(database.Type), _ = backupRepo.DeleteRecord(ctx, commonRepo.WithByType(req.Type), commonRepo.WithByName(req.Database), backupRepo.WithByDetailName(db.Name))
commonRepo.WithByName(fmt.Sprintf("%v", database.ID)),
backupRepo.WithByDetailName(db.Name))
_ = mysqlRepo.Delete(ctx, commonRepo.WithByID(db.ID)) _ = mysqlRepo.Delete(ctx, commonRepo.WithByID(db.ID))
return nil return nil
@ -270,7 +260,7 @@ func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error {
if cmd.CheckIllegal(req.Value) { if cmd.CheckIllegal(req.Value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New(constant.ErrCmdIllegal)
} }
cli, version, database, err := LoadMysqlClientByFrom(req.DatabaseID) cli, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil { if err != nil {
return err return err
} }
@ -301,7 +291,7 @@ func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error {
if req.ID != 0 { if req.ID != 0 {
var appRess []model.AppInstallResource var appRess []model.AppInstallResource
if req.From == "local" { if req.From == "local" {
app, err := appInstallRepo.LoadBaseInfo(req.Type, database) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Database)
if err != nil { if err != nil {
return err return err
} }
@ -333,7 +323,7 @@ func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error {
return nil return nil
} }
if err := updateInstallInfoInDB(req.Type, database, "password", false, req.Value); err != nil { if err := updateInstallInfoInDB(req.Type, req.Database, "password", false, req.Value); err != nil {
return err return err
} }
return nil return nil
@ -343,7 +333,7 @@ func (u *MysqlService) ChangeAccess(req dto.ChangeDBInfo) error {
if cmd.CheckIllegal(req.Value) { if cmd.CheckIllegal(req.Value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New(constant.ErrCmdIllegal)
} }
cli, version, _, err := LoadMysqlClientByFrom(req.DatabaseID) cli, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil { if err != nil {
return err return err
} }
@ -380,11 +370,11 @@ func (u *MysqlService) ChangeAccess(req dto.ChangeDBInfo) error {
} }
func (u *MysqlService) UpdateConfByFile(req dto.MysqlConfUpdateByFile) error { func (u *MysqlService) UpdateConfByFile(req dto.MysqlConfUpdateByFile) error {
database, err := databaseRepo.Get(commonRepo.WithByID(req.DatabaseID)) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Database)
if err != nil { if err != nil {
return err return err
} }
path := fmt.Sprintf("%s/%s/%s/conf/my.cnf", constant.AppInstallDir, database.Type, database.Name) path := fmt.Sprintf("%s/%s/%s/conf/my.cnf", constant.AppInstallDir, req.Type, app.Name)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0640) file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0640)
if err != nil { if err != nil {
return err return err
@ -393,20 +383,20 @@ func (u *MysqlService) UpdateConfByFile(req dto.MysqlConfUpdateByFile) error {
write := bufio.NewWriter(file) write := bufio.NewWriter(file)
_, _ = write.WriteString(req.File) _, _ = write.WriteString(req.File)
write.Flush() write.Flush()
if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, database.Type, database.Name)); err != nil { if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, req.Type, app.Name)); err != nil {
return err return err
} }
return nil return nil
} }
func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error { func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error {
database, err := databaseRepo.Get(commonRepo.WithByID(req.DatabaseID)) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Database)
if err != nil { if err != nil {
return err return err
} }
var files []string var files []string
path := fmt.Sprintf("%s/%s/%s/conf/my.cnf", constant.AppInstallDir, database.Type, database.Name) path := fmt.Sprintf("%s/%s/%s/conf/my.cnf", constant.AppInstallDir, req.Type, app.Name)
lineBytes, err := os.ReadFile(path) lineBytes, err := os.ReadFile(path)
if err != nil { if err != nil {
return err return err
@ -415,7 +405,7 @@ func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error {
group := "[mysqld]" group := "[mysqld]"
for _, info := range req.Variables { for _, info := range req.Variables {
if !strings.HasPrefix(database.Version, "5.7") && !strings.HasPrefix(database.Version, "5.6") { if !strings.HasPrefix(app.Version, "5.7") && !strings.HasPrefix(app.Version, "5.6") {
if info.Param == "query_cache_size" { if info.Param == "query_cache_size" {
continue continue
} }
@ -437,20 +427,16 @@ func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error {
return err return err
} }
if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, database.Type, database.Name)); err != nil { if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, req.Type, app.Name)); err != nil {
return err return err
} }
return nil return nil
} }
func (u *MysqlService) LoadBaseInfo(req dto.OperateByID) (*dto.DBBaseInfo, error) { func (u *MysqlService) LoadBaseInfo(req dto.OperationWithNameAndType) (*dto.DBBaseInfo, error) {
database, err := databaseRepo.Get(commonRepo.WithByID(req.ID))
if err != nil {
return nil, err
}
var data dto.DBBaseInfo var data dto.DBBaseInfo
app, err := appInstallRepo.LoadBaseInfo(database.Type, database.Name) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -461,12 +447,8 @@ func (u *MysqlService) LoadBaseInfo(req dto.OperateByID) (*dto.DBBaseInfo, error
return &data, nil return &data, nil
} }
func (u *MysqlService) LoadRemoteAccess(req dto.OperateByID) (bool, error) { func (u *MysqlService) LoadRemoteAccess(req dto.OperationWithNameAndType) (bool, error) {
database, err := databaseRepo.Get(commonRepo.WithByID(req.ID)) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Name)
if err != nil {
return false, err
}
app, err := appInstallRepo.LoadBaseInfo(database.Type, database.Name)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -483,12 +465,8 @@ func (u *MysqlService) LoadRemoteAccess(req dto.OperateByID) (bool, error) {
return false, nil return false, nil
} }
func (u *MysqlService) LoadVariables(req dto.OperateByID) (*dto.MysqlVariables, error) { func (u *MysqlService) LoadVariables(req dto.OperationWithNameAndType) (*dto.MysqlVariables, error) {
database, err := databaseRepo.Get(commonRepo.WithByID(req.ID)) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Name)
if err != nil {
return nil, err
}
app, err := appInstallRepo.LoadBaseInfo(database.Type, database.Name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -505,12 +483,8 @@ func (u *MysqlService) LoadVariables(req dto.OperateByID) (*dto.MysqlVariables,
return &info, nil return &info, nil
} }
func (u *MysqlService) LoadStatus(req dto.OperateByID) (*dto.MysqlStatus, error) { func (u *MysqlService) LoadStatus(req dto.OperationWithNameAndType) (*dto.MysqlStatus, error) {
database, err := databaseRepo.Get(commonRepo.WithByID(req.ID)) app, err := appInstallRepo.LoadBaseInfo(req.Type, req.Name)
if err != nil {
return nil, err
}
app, err := appInstallRepo.LoadBaseInfo(database.Type, database.Name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -648,7 +622,7 @@ func updateMyCnf(oldFiles []string, group string, param string, value interface{
return newFiles return newFiles
} }
func LoadMysqlClientByFrom(databaseID uint) (mysql.MysqlClient, string, string, error) { func LoadMysqlClientByFrom(database string) (mysql.MysqlClient, string, error) {
var ( var (
dbInfo client.DBInfo dbInfo client.DBInfo
version string version string
@ -656,12 +630,12 @@ func LoadMysqlClientByFrom(databaseID uint) (mysql.MysqlClient, string, string,
) )
dbInfo.Timeout = 300 dbInfo.Timeout = 300
databaseItem, err := databaseRepo.Get(commonRepo.WithByID(databaseID)) databaseItem, err := databaseRepo.Get(commonRepo.WithByName(database))
if err != nil { if err != nil {
return nil, "", databaseItem.Name, err return nil, "", err
} }
dbInfo.From = databaseItem.From dbInfo.From = databaseItem.From
dbInfo.Database = databaseItem.Name dbInfo.Database = database
if dbInfo.From != "local" { if dbInfo.From != "local" {
dbInfo.Address = databaseItem.Address dbInfo.Address = databaseItem.Address
dbInfo.Port = databaseItem.Port dbInfo.Port = databaseItem.Port
@ -670,9 +644,9 @@ func LoadMysqlClientByFrom(databaseID uint) (mysql.MysqlClient, string, string,
version = databaseItem.Version version = databaseItem.Version
} else { } else {
app, err := appInstallRepo.LoadBaseInfo(databaseItem.Type, databaseItem.Name) app, err := appInstallRepo.LoadBaseInfo(databaseItem.Type, database)
if err != nil { if err != nil {
return nil, "", databaseItem.Name, err return nil, "", err
} }
dbInfo.Address = app.ContainerName dbInfo.Address = app.ContainerName
dbInfo.Username = "root" dbInfo.Username = "root"
@ -682,7 +656,7 @@ func LoadMysqlClientByFrom(databaseID uint) (mysql.MysqlClient, string, string,
cli, err := mysql.NewMysqlClient(dbInfo) cli, err := mysql.NewMysqlClient(dbInfo)
if err != nil { if err != nil {
return nil, "", databaseItem.Name, err return nil, "", err
} }
return cli, version, databaseItem.Name, nil return cli, version, nil
} }

View File

@ -96,6 +96,8 @@ var (
ErrUserIsExist = "ErrUserIsExist" ErrUserIsExist = "ErrUserIsExist"
ErrDatabaseIsExist = "ErrDatabaseIsExist" ErrDatabaseIsExist = "ErrDatabaseIsExist"
ErrExecTimeOut = "ErrExecTimeOut" ErrExecTimeOut = "ErrExecTimeOut"
ErrRemoteExist = "ErrRemoteExist"
ErrLocalExist = "ErrLocalExist"
) )
// redis // redis

View File

@ -82,6 +82,8 @@ ErrSSLCertificateFormat: 'Certificate file format error, please use pem format'
ErrUserIsExist: "The current user already exists. Please enter a new user" ErrUserIsExist: "The current user already exists. Please enter a new user"
ErrDatabaseIsExist: "The current database already exists. Please enter a new database" ErrDatabaseIsExist: "The current database already exists. Please enter a new database"
ErrExecTimeOut: "SQL execution timed out, please check the database" ErrExecTimeOut: "SQL execution timed out, please check the database"
ErrRemoteExist: "The remote database already exists with that name, please modify it and try again"
ErrLocalExist: "The local database already exists with that name, please modify it and try again"
#redis #redis
ErrTypeOfRedis: "The recovery file type does not match the current persistence mode. Modify the file type and try again" ErrTypeOfRedis: "The recovery file type does not match the current persistence mode. Modify the file type and try again"

View File

@ -82,6 +82,8 @@ ErrSSLCertificateFormat: '證書文件格式錯誤,請使用 pem 格式'
ErrUserIsExist: "當前用戶已存在,請重新輸入" ErrUserIsExist: "當前用戶已存在,請重新輸入"
ErrDatabaseIsExist: "當前資料庫已存在,請重新輸入" ErrDatabaseIsExist: "當前資料庫已存在,請重新輸入"
ErrExecTimeOut: "SQL 執行超時,請檢查數據庫" ErrExecTimeOut: "SQL 執行超時,請檢查數據庫"
ErrRemoteExist: "遠程數據庫已存在該名稱,請修改後重試"
ErrLocalExist: "本地數據庫已存在該名稱,請修改後重試"
#redis #redis
ErrTypeOfRedis: "恢復文件類型與當前持久化方式不符,請修改後重試" ErrTypeOfRedis: "恢復文件類型與當前持久化方式不符,請修改後重試"

View File

@ -82,6 +82,8 @@ ErrSSLCertificateFormat: '证书文件格式错误,请使用 pem 格式'
ErrUserIsExist: "当前用户已存在,请重新输入" ErrUserIsExist: "当前用户已存在,请重新输入"
ErrDatabaseIsExist: "当前数据库已存在,请重新输入" ErrDatabaseIsExist: "当前数据库已存在,请重新输入"
ErrExecTimeOut: "SQL 执行超时,请检查数据库" ErrExecTimeOut: "SQL 执行超时,请检查数据库"
ErrRemoteExist: "远程数据库已存在该名称,请修改后重试"
ErrLocalExist: "本地数据库已存在该名称,请修改后重试"
#redis #redis
ErrTypeOfRedis: "恢复文件类型与当前持久化方式不符,请修改后重试" ErrTypeOfRedis: "恢复文件类型与当前持久化方式不符,请修改后重试"

View File

@ -43,8 +43,6 @@ func Init() {
migrations.UpdateDatabase, migrations.UpdateDatabase,
migrations.UpdateAppInstallResource, migrations.UpdateAppInstallResource,
migrations.DropDatabaseLocal, migrations.DropDatabaseLocal,
migrations.AddDatabaseID,
migrations.UpdataBackupRecord,
}) })
if err := m.Migrate(); err != nil { if err := m.Migrate(); err != nil {
global.LOG.Error(err) global.LOG.Error(err)

View File

@ -2,7 +2,6 @@ package migrations
import ( import (
"fmt" "fmt"
"strconv"
"strings" "strings"
"time" "time"
@ -572,76 +571,45 @@ var AddTableFirewall = &gormigrate.Migration{
var AddDatabases = &gormigrate.Migration{ var AddDatabases = &gormigrate.Migration{
ID: "20230831-add-databases", ID: "20230831-add-databases",
Migrate: func(tx *gorm.DB) error { Migrate: func(tx *gorm.DB) error {
var (
backups []model.BackupRecord
databases []model.Database
)
_ = tx.Where("type = ? OR type = ?", "mysql", "mariadb").Find(&backups).Error
_ = tx.Where("from = ?", "remote").Find(&databases).Error
_ = tx.Where("name = ? AND address = ? AND type = ?", "local", "127.0.0.1", "mysql").Delete(&model.Database{}).Error
for _, backup := range backups {
for _, database := range databases {
if backup.Name == database.Name && backup.Type == database.Type {
_ = tx.Model(&model.BackupRecord{}).Where("id = ?", backup.ID).Updates(map[string]interface{}{
"name": fmt.Sprintf("%v", database.ID),
}).Error
break
}
}
}
installRepo := repo.NewIAppInstallRepo() installRepo := repo.NewIAppInstallRepo()
mysql := addDatabaseData("mysql", installRepo) _ = tx.Where("name = ? AND address = ?", "local", "127.0.0.1").Delete(&model.Database{}).Error
mysql := addDatabaseData(tx, installRepo, "mysql")
if mysql.AppInstallID != 0 { if mysql.AppInstallID != 0 {
if err := tx.Create(mysql).Error; err != nil { if err := tx.Create(mysql).Error; err != nil {
return err return err
} }
} }
mariadb := addDatabaseData("mariadb", installRepo) mariadb := addDatabaseData(tx, installRepo, "mariadb")
if mariadb.AppInstallID != 0 { if mariadb.AppInstallID != 0 {
if err := tx.Create(mariadb).Error; err != nil { if err := tx.Create(mariadb).Error; err != nil {
return err return err
} }
} }
redis := addDatabaseData("redis", installRepo) redis := addDatabaseData(tx, installRepo, "redis")
if redis.AppInstallID != 0 { if redis.AppInstallID != 0 {
if err := tx.Create(redis).Error; err != nil { if err := tx.Create(redis).Error; err != nil {
return err return err
} }
} }
postgresql := addDatabaseData("postgresql", installRepo) postgresql := addDatabaseData(tx, installRepo, "postgresql")
if postgresql.AppInstallID != 0 { if postgresql.AppInstallID != 0 {
if err := tx.Create(postgresql).Error; err != nil { if err := tx.Create(postgresql).Error; err != nil {
return err return err
} }
} }
mongodb := addDatabaseData("mongodb", installRepo) mongodb := addDatabaseData(tx, installRepo, "mongodb")
if mongodb.AppInstallID != 0 { if mongodb.AppInstallID != 0 {
if err := tx.Create(mongodb).Error; err != nil { if err := tx.Create(mongodb).Error; err != nil {
return err return err
} }
} }
memcached := addDatabaseData("memcached", installRepo) memcached := addDatabaseData(tx, installRepo, "memcached")
if memcached.AppInstallID != 0 { if memcached.AppInstallID != 0 {
if err := tx.Create(memcached).Error; err != nil { if err := tx.Create(memcached).Error; err != nil {
return err return err
} }
} }
_ = tx.Where("type = ? OR type = ?", "mysql", "mariadb").Find(&backups).Error
_ = tx.Where("from = ?", "local").Find(&databases).Error
for _, backup := range backups {
if _, err := strconv.Atoi(backup.Name); err == nil {
continue
}
for _, database := range databases {
if backup.Name == database.Name && backup.Type == database.Type {
_ = tx.Model(&model.BackupRecord{}).Where("id = ?", backup.ID).Updates(map[string]interface{}{
"name": fmt.Sprintf("%v", database.ID),
}).Error
break
}
}
}
return nil return nil
}, },
} }
@ -715,80 +683,61 @@ var DropDatabaseLocal = &gormigrate.Migration{
}, },
} }
var AddDatabaseID = &gormigrate.Migration{ func addDatabaseData(tx *gorm.DB, installRepo repo.IAppInstallRepo, appType string) *model.Database {
ID: "20230914-add-database-id",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&model.DatabaseMysql{}, &model.Database{}); err != nil {
return err
}
var (
mysqls []model.DatabaseMysql
databases []model.Database
)
_ = tx.Find(&mysqls).Error
if len(mysqls) == 0 {
return nil
}
_ = tx.Find(&databases).Error
for _, mysql := range mysqls {
for _, database := range databases {
if mysql.MysqlName == database.Name && mysql.From == database.From {
if err := tx.Model(&model.DatabaseMysql{}).Where("id = ?", mysql.ID).Updates(map[string]interface{}{
"database_id": database.ID,
}).Error; err != nil {
return err
}
break
}
}
}
return nil
},
}
var UpdataBackupRecord = &gormigrate.Migration{
ID: "20230915-update-backup-record",
Migrate: func(tx *gorm.DB) error {
var (
backups []model.BackupRecord
databases []model.Database
)
_ = tx.Where("type = ? OR type = ?", "mysql", "mariadb").Find(&backups).Error
_ = tx.Find(&databases).Error
for _, backup := range backups {
if _, err := strconv.Atoi(backup.Name); err == nil {
continue
}
for _, database := range databases {
if backup.Name == database.Name && backup.Type == database.Type {
_ = tx.Model(&model.BackupRecord{}).Where("id = ?", backup.ID).Updates(map[string]interface{}{
"name": fmt.Sprintf("%v", database.ID),
}).Error
break
}
}
}
return nil
},
}
func addDatabaseData(appType string, installRepo repo.IAppInstallRepo) *model.Database {
dbInfo, err := installRepo.LoadBaseInfo(appType, "") dbInfo, err := installRepo.LoadBaseInfo(appType, "")
if err == nil { if err != nil {
if appType == "mysql" || appType == "redis" || appType == "mariadb" || appType == "memcached" { return &model.Database{}
dbInfo.UserName = "root" }
if appType == "mysql" || appType == "redis" || appType == "mariadb" || appType == "memcached" {
dbInfo.UserName = "root"
}
database := &model.Database{
AppInstallID: dbInfo.ID,
Name: dbInfo.Name,
Type: appType,
Version: dbInfo.Version,
From: "local",
Address: dbInfo.ServiceName,
Port: service.DatabaseKeys[appType],
Username: dbInfo.UserName,
Password: dbInfo.Password,
}
var dbItem model.Database
_ = global.DB.Where("name = ?", dbInfo.Name).First(&dbItem).Error
if dbItem.ID != 0 {
if appType == "mysql" {
var (
backups []model.BackupRecord
mysqls []model.DatabaseMysql
)
_ = tx.Where("name = ? AND type = ?", dbItem.Name, "mysql").Find(&backups)
_ = tx.Where("`from` = ?", "local").Find(&mysqls)
for _, item := range backups {
isLocal := false
for _, mysql := range mysqls {
if item.Name == mysql.MysqlName && item.DetailName == mysql.Name {
isLocal = true
break
}
}
if !isLocal {
_ = tx.Model(&model.BackupRecord{}).Where("id = ?", item.ID).Updates(map[string]interface{}{
"name": "remote-" + dbItem.Name,
}).Error
}
}
} }
return &model.Database{ if err := tx.Debug().Model(&model.DatabaseMysql{}).Where("mysql_name = ? AND `from` != ?", dbItem.Name, "local").Updates(map[string]interface{}{
AppInstallID: dbInfo.ID, "mysql_name": "remote-" + dbItem.Name,
Name: dbInfo.Name, }).Error; err != nil {
Type: appType, fmt.Println(err)
Version: dbInfo.Version, }
From: "local", if err := tx.Debug().Model(&model.Database{}).Where("name = ?", dbItem.Name).Updates(map[string]interface{}{
Address: dbInfo.ServiceName, "name": "remote-" + dbItem.Name,
Port: service.DatabaseKeys[appType], }).Error; err != nil {
Username: dbInfo.UserName, fmt.Println(err)
Password: dbInfo.Password,
} }
} }
return &model.Database{} return database
} }

View File

@ -79,6 +79,7 @@ type RecoverInfo struct {
type SyncDBInfo struct { type SyncDBInfo struct {
Name string `json:"name"` Name string `json:"name"`
From string `json:"from"` From string `json:"from"`
MysqlName string `json:"mysqlName"`
Format string `json:"format"` Format string `json:"format"`
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`

View File

@ -273,9 +273,10 @@ func (r *Local) SyncDB(version string) ([]SyncDBInfo, error) {
continue continue
} }
dataItem := SyncDBInfo{ dataItem := SyncDBInfo{
Name: parts[0], Name: parts[0],
From: "local", From: "local",
Format: parts[1], MysqlName: r.Database,
Format: parts[1],
} }
userLines, err := r.ExecSQLForRows(fmt.Sprintf("select user,host from mysql.db where db = '%s'", parts[0]), 300) userLines, err := r.ExecSQLForRows(fmt.Sprintf("select user,host from mysql.db where db = '%s'", parts[0]), 300)
if err != nil { if err != nil {

View File

@ -283,9 +283,10 @@ func (r *Remote) SyncDB(version string) ([]SyncDBInfo, error) {
continue continue
} }
dataItem := SyncDBInfo{ dataItem := SyncDBInfo{
Name: dbName, Name: dbName,
From: "remote", From: "remote",
Format: charsetName, MysqlName: r.Database,
Format: charsetName,
} }
userRows, err := r.Client.Query("select user,host from mysql.db where db = ?", dbName) userRows, err := r.Client.Query("select user,host from mysql.db where db = ?", dbName)
if err != nil { if err != nil {

View File

@ -3740,7 +3740,7 @@ const docTemplate = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -4322,7 +4322,7 @@ const docTemplate = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.MysqlLoadDB"
} }
} }
], ],
@ -4685,7 +4685,7 @@ const docTemplate = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -4757,7 +4757,7 @@ const docTemplate = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -4793,7 +4793,7 @@ const docTemplate = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -11900,14 +11900,14 @@ const docTemplate = `{
"dto.ChangeDBInfo": { "dto.ChangeDBInfo": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"from", "from",
"type", "type",
"value" "value"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"from": { "from": {
"type": "string", "type": "string",
@ -13543,21 +13543,29 @@ const docTemplate = `{
"dto.MysqlConfUpdateByFile": { "dto.MysqlConfUpdateByFile": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID" "database",
"type"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"file": { "file": {
"type": "string" "type": "string"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
} }
} }
}, },
"dto.MysqlDBCreate": { "dto.MysqlDBCreate": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"format", "format",
"from", "from",
"name", "name",
@ -13566,8 +13574,8 @@ const docTemplate = `{
"username" "username"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"description": { "description": {
"type": "string" "type": "string"
@ -13605,9 +13613,14 @@ const docTemplate = `{
"dto.MysqlDBDelete": { "dto.MysqlDBDelete": {
"type": "object", "type": "object",
"required": [ "required": [
"id" "database",
"id",
"type"
], ],
"properties": { "properties": {
"database": {
"type": "string"
},
"deleteBackup": { "deleteBackup": {
"type": "boolean" "type": "boolean"
}, },
@ -13616,34 +13629,49 @@ const docTemplate = `{
}, },
"id": { "id": {
"type": "integer" "type": "integer"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
} }
} }
}, },
"dto.MysqlDBDeleteCheck": { "dto.MysqlDBDeleteCheck": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"id" "id",
"type"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"id": { "id": {
"type": "integer" "type": "integer"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
} }
} }
}, },
"dto.MysqlDBSearch": { "dto.MysqlDBSearch": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"page", "page",
"pageSize" "pageSize"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"info": { "info": {
"type": "string" "type": "string"
@ -13662,15 +13690,39 @@ const docTemplate = `{
} }
} }
}, },
"dto.MysqlLoadDB": {
"type": "object",
"required": [
"database",
"from",
"type"
],
"properties": {
"database": {
"type": "string"
},
"from": {
"type": "string",
"enum": [
"local",
"remote"
]
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
}
}
},
"dto.MysqlOption": { "dto.MysqlOption": {
"type": "object", "type": "object",
"properties": { "properties": {
"database": { "database": {
"type": "string" "type": "string"
}, },
"databaseID": {
"type": "integer"
},
"from": { "from": {
"type": "string" "type": "string"
}, },
@ -13857,11 +13909,19 @@ const docTemplate = `{
"dto.MysqlVariablesUpdate": { "dto.MysqlVariablesUpdate": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID" "database",
"type"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
}, },
"variables": { "variables": {
"type": "array", "type": "array",
@ -17628,6 +17688,9 @@ const docTemplate = `{
}, },
"end": { "end": {
"type": "boolean" "type": "boolean"
},
"path": {
"type": "string"
} }
} }
}, },

View File

@ -3733,7 +3733,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -4315,7 +4315,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.MysqlLoadDB"
} }
} }
], ],
@ -4678,7 +4678,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -4750,7 +4750,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -4786,7 +4786,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dto.OperateByID" "$ref": "#/definitions/dto.OperationWithNameAndType"
} }
} }
], ],
@ -11893,14 +11893,14 @@
"dto.ChangeDBInfo": { "dto.ChangeDBInfo": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"from", "from",
"type", "type",
"value" "value"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"from": { "from": {
"type": "string", "type": "string",
@ -13536,21 +13536,29 @@
"dto.MysqlConfUpdateByFile": { "dto.MysqlConfUpdateByFile": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID" "database",
"type"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"file": { "file": {
"type": "string" "type": "string"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
} }
} }
}, },
"dto.MysqlDBCreate": { "dto.MysqlDBCreate": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"format", "format",
"from", "from",
"name", "name",
@ -13559,8 +13567,8 @@
"username" "username"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"description": { "description": {
"type": "string" "type": "string"
@ -13598,9 +13606,14 @@
"dto.MysqlDBDelete": { "dto.MysqlDBDelete": {
"type": "object", "type": "object",
"required": [ "required": [
"id" "database",
"id",
"type"
], ],
"properties": { "properties": {
"database": {
"type": "string"
},
"deleteBackup": { "deleteBackup": {
"type": "boolean" "type": "boolean"
}, },
@ -13609,34 +13622,49 @@
}, },
"id": { "id": {
"type": "integer" "type": "integer"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
} }
} }
}, },
"dto.MysqlDBDeleteCheck": { "dto.MysqlDBDeleteCheck": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"id" "id",
"type"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"id": { "id": {
"type": "integer" "type": "integer"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
} }
} }
}, },
"dto.MysqlDBSearch": { "dto.MysqlDBSearch": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID", "database",
"page", "page",
"pageSize" "pageSize"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
}, },
"info": { "info": {
"type": "string" "type": "string"
@ -13655,15 +13683,39 @@
} }
} }
}, },
"dto.MysqlLoadDB": {
"type": "object",
"required": [
"database",
"from",
"type"
],
"properties": {
"database": {
"type": "string"
},
"from": {
"type": "string",
"enum": [
"local",
"remote"
]
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
}
}
},
"dto.MysqlOption": { "dto.MysqlOption": {
"type": "object", "type": "object",
"properties": { "properties": {
"database": { "database": {
"type": "string" "type": "string"
}, },
"databaseID": {
"type": "integer"
},
"from": { "from": {
"type": "string" "type": "string"
}, },
@ -13850,11 +13902,19 @@
"dto.MysqlVariablesUpdate": { "dto.MysqlVariablesUpdate": {
"type": "object", "type": "object",
"required": [ "required": [
"databaseID" "database",
"type"
], ],
"properties": { "properties": {
"databaseID": { "database": {
"type": "integer" "type": "string"
},
"type": {
"type": "string",
"enum": [
"mysql",
"mariadb"
]
}, },
"variables": { "variables": {
"type": "array", "type": "array",
@ -17621,6 +17681,9 @@
}, },
"end": { "end": {
"type": "boolean" "type": "boolean"
},
"path": {
"type": "string"
} }
} }
}, },

View File

@ -131,8 +131,8 @@ definitions:
type: object type: object
dto.ChangeDBInfo: dto.ChangeDBInfo:
properties: properties:
databaseID: database:
type: integer type: string
from: from:
enum: enum:
- local - local
@ -148,7 +148,7 @@ definitions:
value: value:
type: string type: string
required: required:
- databaseID - database
- from - from
- type - type
- value - value
@ -1241,17 +1241,23 @@ definitions:
type: object type: object
dto.MysqlConfUpdateByFile: dto.MysqlConfUpdateByFile:
properties: properties:
databaseID: database:
type: integer type: string
file: file:
type: string type: string
type:
enum:
- mysql
- mariadb
type: string
required: required:
- databaseID - database
- type
type: object type: object
dto.MysqlDBCreate: dto.MysqlDBCreate:
properties: properties:
databaseID: database:
type: integer type: string
description: description:
type: string type: string
format: format:
@ -1275,7 +1281,7 @@ definitions:
username: username:
type: string type: string
required: required:
- databaseID - database
- format - format
- from - from
- name - name
@ -1285,29 +1291,44 @@ definitions:
type: object type: object
dto.MysqlDBDelete: dto.MysqlDBDelete:
properties: properties:
database:
type: string
deleteBackup: deleteBackup:
type: boolean type: boolean
forceDelete: forceDelete:
type: boolean type: boolean
id: id:
type: integer type: integer
type:
enum:
- mysql
- mariadb
type: string
required: required:
- database
- id - id
- type
type: object type: object
dto.MysqlDBDeleteCheck: dto.MysqlDBDeleteCheck:
properties: properties:
databaseID: database:
type: integer type: string
id: id:
type: integer type: integer
type:
enum:
- mysql
- mariadb
type: string
required: required:
- databaseID - database
- id - id
- type
type: object type: object
dto.MysqlDBSearch: dto.MysqlDBSearch:
properties: properties:
databaseID: database:
type: integer type: string
info: info:
type: string type: string
order: order:
@ -1319,16 +1340,33 @@ definitions:
pageSize: pageSize:
type: integer type: integer
required: required:
- databaseID - database
- page - page
- pageSize - pageSize
type: object type: object
dto.MysqlLoadDB:
properties:
database:
type: string
from:
enum:
- local
- remote
type: string
type:
enum:
- mysql
- mariadb
type: string
required:
- database
- from
- type
type: object
dto.MysqlOption: dto.MysqlOption:
properties: properties:
database: database:
type: string type: string
databaseID:
type: integer
from: from:
type: string type: string
id: id:
@ -1452,14 +1490,20 @@ definitions:
type: object type: object
dto.MysqlVariablesUpdate: dto.MysqlVariablesUpdate:
properties: properties:
databaseID: database:
type: integer type: string
type:
enum:
- mysql
- mariadb
type: string
variables: variables:
items: items:
$ref: '#/definitions/dto.MysqlVariablesUpdateHelper' $ref: '#/definitions/dto.MysqlVariablesUpdateHelper'
type: array type: array
required: required:
- databaseID - database
- type
type: object type: object
dto.MysqlVariablesUpdateHelper: dto.MysqlVariablesUpdateHelper:
properties: properties:
@ -3972,6 +4016,8 @@ definitions:
type: boolean type: boolean
end: end:
type: boolean type: boolean
path:
type: string
type: object type: object
response.WebsiteNginxConfig: response.WebsiteNginxConfig:
properties: properties:
@ -6368,7 +6414,7 @@ paths:
name: request name: request
required: true required: true
schema: schema:
$ref: '#/definitions/dto.OperateByID' $ref: '#/definitions/dto.OperationWithNameAndType'
responses: responses:
"200": "200":
description: OK description: OK
@ -6739,7 +6785,7 @@ paths:
name: request name: request
required: true required: true
schema: schema:
$ref: '#/definitions/dto.OperateByID' $ref: '#/definitions/dto.MysqlLoadDB'
responses: {} responses: {}
security: security:
- ApiKeyAuth: [] - ApiKeyAuth: []
@ -6966,7 +7012,7 @@ paths:
name: request name: request
required: true required: true
schema: schema:
$ref: '#/definitions/dto.OperateByID' $ref: '#/definitions/dto.OperationWithNameAndType'
responses: responses:
"200": "200":
description: OK description: OK
@ -7010,7 +7056,7 @@ paths:
name: request name: request
required: true required: true
schema: schema:
$ref: '#/definitions/dto.OperateByID' $ref: '#/definitions/dto.OperationWithNameAndType'
responses: responses:
"200": "200":
description: OK description: OK
@ -7032,7 +7078,7 @@ paths:
name: request name: request
required: true required: true
schema: schema:
$ref: '#/definitions/dto.OperateByID' $ref: '#/definitions/dto.OperationWithNameAndType'
responses: responses:
"200": "200":
description: OK description: OK

View File

@ -1,17 +1,23 @@
import { ReqPage } from '.';
export namespace Database { export namespace Database {
export interface SearchDBWithPage { export interface SearchDBWithPage {
info: string; info: string;
databaseID: number; database: string;
page: number; page: number;
pageSize: number; pageSize: number;
orderBy?: string; orderBy?: string;
order?: string; order?: string;
} }
export interface SearchBackupRecord extends ReqPage {
mysqlName: string;
dbName: string;
}
export interface MysqlDBInfo { export interface MysqlDBInfo {
id: number; id: number;
createdAt: Date; createdAt: Date;
name: string; name: string;
databaseID: number; mysqlName: string;
from: string; from: string;
format: string; format: string;
username: string; username: string;
@ -28,25 +34,34 @@ export namespace Database {
containerName: string; containerName: string;
} }
export interface MysqlConfUpdateByFile { export interface MysqlConfUpdateByFile {
databaseID: number; type: string;
database: string;
file: string; file: string;
} }
export interface MysqlDBCreate { export interface MysqlDBCreate {
name: string; name: string;
from: string; from: string;
databaseID: number; database: string;
format: string; format: string;
username: string; username: string;
password: string; password: string;
permission: string; permission: string;
description: string; description: string;
} }
export interface MysqlLoadDB {
from: string;
type: string;
database: string;
}
export interface MysqlDBDeleteCheck { export interface MysqlDBDeleteCheck {
id: number; id: number;
databaseID: number; type: string;
database: string;
} }
export interface MysqlDBDelete { export interface MysqlDBDelete {
id: number; id: number;
type: string;
database: string;
forceDelete: boolean; forceDelete: boolean;
deleteBackup: boolean; deleteBackup: boolean;
} }
@ -71,7 +86,8 @@ export namespace Database {
long_query_time: number; long_query_time: number;
} }
export interface VariablesUpdate { export interface VariablesUpdate {
databaseID: number; type: string;
database: string;
variables: Array<VariablesUpdateHelper>; variables: Array<VariablesUpdateHelper>;
} }
export interface VariablesUpdateHelper { export interface VariablesUpdateHelper {
@ -119,7 +135,6 @@ export namespace Database {
id: number; id: number;
from: string; from: string;
type: string; type: string;
databaseID: number;
database: string; database: string;
name: string; name: string;
} }
@ -127,7 +142,7 @@ export namespace Database {
id: number; id: number;
from: string; from: string;
type: string; type: string;
databaseID: number; database: string;
value: string; value: string;
} }

View File

@ -19,6 +19,9 @@ export const addMysqlDB = (params: Database.MysqlDBCreate) => {
} }
return http.post(`/databases`, request); return http.post(`/databases`, request);
}; };
export const loadDBFromRemote = (params: Database.MysqlLoadDB) => {
return http.post(`/databases/load`, params);
};
export const updateMysqlAccess = (params: Database.ChangeInfo) => { export const updateMysqlAccess = (params: Database.ChangeInfo) => {
return http.post(`/databases/change/access`, params); return http.post(`/databases/change/access`, params);
}; };
@ -45,20 +48,17 @@ export const deleteMysqlDB = (params: Database.MysqlDBDelete) => {
return http.post(`/databases/del`, params); return http.post(`/databases/del`, params);
}; };
export const loadDBFromRemote = (id: number) => { export const loadMysqlBaseInfo = (type: string, database: string) => {
return http.post(`/databases/load`, { id: id }); return http.post<Database.BaseInfo>(`/databases/baseinfo`, { type: type, name: database });
}; };
export const loadMysqlBaseInfo = (id: number) => { export const loadMysqlVariables = (type: string, database: string) => {
return http.post<Database.BaseInfo>(`/databases/baseinfo`, { id: id }); return http.post<Database.MysqlVariables>(`/databases/variables`, { type: type, name: database });
}; };
export const loadMysqlVariables = (id: number) => { export const loadMysqlStatus = (type: string, database: string) => {
return http.post<Database.MysqlVariables>(`/databases/variables`, { id: id }); return http.post<Database.MysqlStatus>(`/databases/status`, { type: type, name: database });
}; };
export const loadMysqlStatus = (id: number) => { export const loadRemoteAccess = (type: string, database: string) => {
return http.post<Database.MysqlStatus>(`/databases/status`, { id: id }); return http.post<boolean>(`/databases/remote`, { type: type, name: database });
};
export const loadRemoteAccess = (id: number) => {
return http.post<boolean>(`/databases/remote`, { id: id });
}; };
export const loadDBOptions = () => { export const loadDBOptions = () => {
return http.get<Array<Database.MysqlOption>>(`/databases/options`); return http.get<Array<Database.MysqlOption>>(`/databases/options`);

View File

@ -50,7 +50,7 @@
</div> </div>
</el-card> </el-card>
</div> </div>
<div v-else> <div v-if="!data.isExist && !isDB">
<LayoutContent :title="getTitle(key)" :divider="true"> <LayoutContent :title="getTitle(key)" :divider="true">
<template #main> <template #main>
<div class="app-warn"> <div class="app-warn">
@ -134,6 +134,10 @@ const goRouter = async (key: string) => {
router.push({ name: 'AppAll', query: { install: key } }); router.push({ name: 'AppAll', query: { install: key } });
}; };
const isDB = () => {
return key.value === 'mysql' || key.value === 'mysql';
};
const onCheck = async () => { const onCheck = async () => {
await CheckAppInstalled(key.value, name.value) await CheckAppInstalled(key.value, name.value)
.then((res) => { .then((res) => {

View File

@ -3,13 +3,7 @@
<el-drawer v-model="backupVisiable" :destroy-on-close="true" :close-on-click-modal="false" size="50%"> <el-drawer v-model="backupVisiable" :destroy-on-close="true" :close-on-click-modal="false" size="50%">
<template #header> <template #header>
<DrawerHeader <DrawerHeader
v-if="type === 'mysql' || type == 'mariadb'" v-if="detailName"
:header="$t('commons.button.backup')"
:resource="detailName"
:back="handleClose"
/>
<DrawerHeader
v-else-if="detailName"
:header="$t('commons.button.backup')" :header="$t('commons.button.backup')"
:resource="name + '(' + detailName + ')'" :resource="name + '(' + detailName + ')'"
:back="handleClose" :back="handleClose"

View File

@ -18,7 +18,7 @@
:stroke-width="12" :stroke-width="12"
:percentage="uploadPrecent" :percentage="uploadPrecent"
></el-progress> ></el-progress>
<div v-if="type === 'mysql' || type === 'mariadb'" style="width: 80%" class="el-upload__tip"> <div v-if="type === 'mysql'" style="width: 80%" class="el-upload__tip">
<span class="input-help">{{ $t('database.supportUpType') }}</span> <span class="input-help">{{ $t('database.supportUpType') }}</span>
<span class="input-help"> <span class="input-help">
{{ $t('database.zipFormat') }} {{ $t('database.zipFormat') }}
@ -109,21 +109,18 @@ const upVisiable = ref(false);
const type = ref(); const type = ref();
const name = ref(); const name = ref();
const detailName = ref(); const detailName = ref();
const databaseID = ref();
interface DialogProps { interface DialogProps {
type: string; type: string;
name: string; name: string;
databaseID: string;
detailName: string; detailName: string;
} }
const acceptParams = async (params: DialogProps): Promise<void> => { const acceptParams = async (params: DialogProps): Promise<void> => {
type.value = params.type; type.value = params.type;
name.value = params.name; name.value = params.name;
databaseID.value = params.databaseID;
detailName.value = params.detailName; detailName.value = params.detailName;
const pathRes = await loadBaseDir(); const pathRes = await loadBaseDir();
if (type.value === 'mysql' || type.value === 'mariadb') { if (type.value === 'mysql') {
title.value = name.value + ' [ ' + detailName.value + ' ]'; title.value = name.value + ' [ ' + detailName.value + ' ]';
} }
if (type.value === 'website' || type.value === 'app') { if (type.value === 'website' || type.value === 'app') {
@ -151,11 +148,10 @@ const search = async () => {
}; };
const onRecover = async (row: File.File) => { const onRecover = async (row: File.File) => {
let nameItem = type.value === 'mysql' || type.value === 'mariadb' ? databaseID.value : name.value;
let params = { let params = {
source: 'LOCAL', source: 'LOCAL',
type: type.value, type: type.value,
name: nameItem, name: name.value,
detailName: detailName.value, detailName: detailName.value,
file: baseDir.value + row.name, file: baseDir.value + row.name,
}; };

View File

@ -120,7 +120,6 @@ const form = reactive({
from: '', from: '',
type: '', type: '',
database: '', database: '',
databaseID: 0,
username: '', username: '',
remoteIP: '', remoteIP: '',
}); });
@ -135,7 +134,6 @@ interface DialogProps {
from: string; from: string;
type: string; type: string;
database: string; database: string;
databaseID: number;
} }
const acceptParams = (param: DialogProps): void => { const acceptParams = (param: DialogProps): void => {
@ -143,7 +141,6 @@ const acceptParams = (param: DialogProps): void => {
form.from = param.from; form.from = param.from;
form.type = param.type; form.type = param.type;
form.database = param.database; form.database = param.database;
form.databaseID = param.databaseID;
loadAccess(); loadAccess();
loadPassword(); loadPassword();
dialogVisiable.value = true; dialogVisiable.value = true;
@ -174,7 +171,7 @@ const handleClose = () => {
const loadAccess = async () => { const loadAccess = async () => {
if (form.from === 'local') { if (form.from === 'local') {
const res = await loadRemoteAccess(form.databaseID); const res = await loadRemoteAccess(form.type, form.database);
form.privilege = res.data; form.privilege = res.data;
} }
}; };
@ -206,7 +203,7 @@ const onSubmit = async () => {
id: 0, id: 0,
from: form.from, from: form.from,
type: form.type, type: form.type,
databaseID: form.databaseID, database: form.database,
value: form.password, value: form.password,
}; };
loading.value = true; loading.value = true;
@ -239,7 +236,7 @@ const onSubmitAccess = async () => {
id: 0, id: 0,
from: form.from, from: form.from,
type: form.type, type: form.type,
databaseID: form.databaseID, database: form.database,
value: form.privilege ? '%' : 'localhost', value: form.privilege ? '%' : 'localhost',
}; };
loading.value = true; loading.value = true;

View File

@ -93,7 +93,6 @@ const form = reactive({
from: 'local', from: 'local',
type: '', type: '',
database: '', database: '',
databaseID: 0,
format: '', format: '',
username: '', username: '',
password: '', password: '',
@ -125,14 +124,12 @@ interface DialogProps {
from: string; from: string;
type: string; type: string;
database: string; database: string;
databaseID: number;
} }
const acceptParams = (params: DialogProps): void => { const acceptParams = (params: DialogProps): void => {
form.name = ''; form.name = '';
form.from = params.from; form.from = params.from;
form.type = params.type; form.type = params.type;
form.database = params.database; form.database = params.database;
form.databaseID = params.databaseID;
form.format = 'utf8mb4'; form.format = 'utf8mb4';
form.username = ''; form.username = '';
form.permission = '%'; form.permission = '%';

View File

@ -48,6 +48,8 @@ import { MsgSuccess } from '@/utils/message';
let deleteReq = ref({ let deleteReq = ref({
id: 0, id: 0,
type: '',
database: '',
deleteBackup: false, deleteBackup: false,
forceDelete: false, forceDelete: false,
}); });
@ -60,13 +62,17 @@ const deleteForm = ref<FormInstance>();
interface DialogProps { interface DialogProps {
id: number; id: number;
type: string;
name: string; name: string;
database: string;
} }
const emit = defineEmits<{ (e: 'search'): void }>(); const emit = defineEmits<{ (e: 'search'): void }>();
const acceptParams = async (prop: DialogProps) => { const acceptParams = async (prop: DialogProps) => {
deleteReq.value = { deleteReq.value = {
id: prop.id, id: prop.id,
type: prop.type,
database: prop.database,
deleteBackup: false, deleteBackup: false,
forceDelete: false, forceDelete: false,
}; };

View File

@ -164,7 +164,7 @@
</template> </template>
</LayoutContent> </LayoutContent>
<div v-if="!currentDB?.id"> <div v-if="dbOptionsLocal.length === 0 && dbOptionsRemote.length === 0">
<LayoutContent :title="'MySQL ' + $t('menu.database')" :divider="true"> <LayoutContent :title="'MySQL ' + $t('menu.database')" :divider="true">
<template #main> <template #main>
<div class="app-warn"> <div class="app-warn">
@ -285,7 +285,6 @@ const onOpenDialog = async () => {
from: currentDB.value.from, from: currentDB.value.from,
type: currentDB.value.type, type: currentDB.value.type,
database: currentDBName.value, database: currentDBName.value,
databaseID: currentDB.value.id,
}; };
dialogRef.value!.acceptParams(params); dialogRef.value!.acceptParams(params);
}; };
@ -299,8 +298,7 @@ const onChangeConn = async () => {
connRef.value!.acceptParams({ connRef.value!.acceptParams({
from: currentDB.value.from, from: currentDB.value.from,
type: currentDB.value.type, type: currentDB.value.type,
databaseID: currentDB.value.id, database: currentDBName.value,
database: currentDB.value.database,
}); });
}; };
@ -317,10 +315,7 @@ const onSetting = async () => {
if (currentDB.value) { if (currentDB.value) {
globalStore.setCurrentDB(currentDB.value.database); globalStore.setCurrentDB(currentDB.value.database);
} }
router.push({ router.push({ name: 'MySQL-Setting', params: { type: currentDB.value.type, database: currentDB.value.database } });
name: 'MySQL-Setting',
params: { type: currentDB.value.type, database: currentDB.value.database, databaseID: currentDB.value.id },
});
}; };
const changeDatabase = async () => { const changeDatabase = async () => {
@ -349,7 +344,7 @@ const search = async (column?: any) => {
page: paginationConfig.currentPage, page: paginationConfig.currentPage,
pageSize: paginationConfig.pageSize, pageSize: paginationConfig.pageSize,
info: searchName.value, info: searchName.value,
databaseID: currentDB.value.id, database: currentDB.value.database,
orderBy: paginationConfig.orderBy, orderBy: paginationConfig.orderBy,
order: paginationConfig.order, order: paginationConfig.order,
}; };
@ -365,7 +360,12 @@ const loadDB = async () => {
type: 'info', type: 'info',
}).then(async () => { }).then(async () => {
loading.value = true; loading.value = true;
await loadDBFromRemote(currentDB.value.id) let params = {
from: currentDB.value.from,
type: currentDB.value.type,
database: currentDBName.value,
};
await loadDBFromRemote(params)
.then(() => { .then(() => {
loading.value = false; loading.value = false;
search(); search();
@ -464,7 +464,8 @@ const onCopy = async (row: any) => {
const onDelete = async (row: Database.MysqlDBInfo) => { const onDelete = async (row: Database.MysqlDBInfo) => {
let param = { let param = {
id: row.id, id: row.id,
databaseID: currentDB.value.id, type: currentDB.value.type,
database: currentDBName.value,
}; };
const res = await deleteCheckMysqlDB(param); const res = await deleteCheckMysqlDB(param);
if (res.data && res.data.length > 0) { if (res.data && res.data.length > 0) {
@ -473,8 +474,8 @@ const onDelete = async (row: Database.MysqlDBInfo) => {
deleteRef.value.acceptParams({ deleteRef.value.acceptParams({
id: row.id, id: row.id,
type: currentDB.value.type, type: currentDB.value.type,
database: currentDBName.value,
name: row.name, name: row.name,
databaseID: currentDB.value.id,
}); });
} }
}; };
@ -484,7 +485,8 @@ const onChangePassword = async (row: Database.MysqlDBInfo) => {
id: row.id, id: row.id,
from: row.from, from: row.from,
type: currentDB.value.type, type: currentDB.value.type,
databaseID: currentDB.value.id, database: currentDBName.value,
mysqlName: row.name,
operation: 'password', operation: 'password',
username: row.username, username: row.username,
password: row.password, password: row.password,
@ -509,7 +511,8 @@ const buttons = [
id: row.id, id: row.id,
from: row.from, from: row.from,
type: currentDB.value.type, type: currentDB.value.type,
databaseID: currentDB.value.id, database: currentDBName.value,
mysqlName: row.name,
operation: 'privilege', operation: 'privilege',
privilege: '', privilege: '',
privilegeIPs: '', privilegeIPs: '',
@ -529,7 +532,7 @@ const buttons = [
click: (row: Database.MysqlDBInfo) => { click: (row: Database.MysqlDBInfo) => {
let params = { let params = {
type: currentDB.value.type, type: currentDB.value.type,
name: currentDB.value.id + '', name: currentDBName.value,
detailName: row.name, detailName: row.name,
}; };
dialogBackupRef.value!.acceptParams(params); dialogBackupRef.value!.acceptParams(params);
@ -540,8 +543,7 @@ const buttons = [
click: (row: Database.MysqlDBInfo) => { click: (row: Database.MysqlDBInfo) => {
let params = { let params = {
type: currentDB.value.type, type: currentDB.value.type,
name: currentDB.value.from + '-' + currentDB.value.database, name: currentDBName.value,
databaseID: currentDB.value.id + '',
detailName: row.name, detailName: row.name,
}; };
uploadRef.value!.acceptParams(params); uploadRef.value!.acceptParams(params);

View File

@ -79,7 +79,7 @@ const changeForm = reactive({
id: 0, id: 0,
from: '', from: '',
type: '', type: '',
databaseID: 0, database: '',
mysqlName: '', mysqlName: '',
userName: '', userName: '',
password: '', password: '',
@ -109,7 +109,7 @@ interface DialogProps {
id: number; id: number;
from: string; from: string;
type: string; type: string;
databaseID: number; database: string;
mysqlName: string; mysqlName: string;
username: string; username: string;
password: string; password: string;
@ -126,7 +126,7 @@ const acceptParams = (params: DialogProps): void => {
changeForm.id = params.id; changeForm.id = params.id;
changeForm.from = params.from; changeForm.from = params.from;
changeForm.type = params.type; changeForm.type = params.type;
changeForm.databaseID = params.databaseID; changeForm.database = params.database;
changeForm.mysqlName = params.mysqlName; changeForm.mysqlName = params.mysqlName;
changeForm.userName = params.username; changeForm.userName = params.username;
changeForm.password = params.password; changeForm.password = params.password;
@ -150,7 +150,7 @@ const submitChangeInfo = async (formEl: FormInstance | undefined) => {
id: changeForm.id, id: changeForm.id,
from: changeForm.from, from: changeForm.from,
type: changeForm.type, type: changeForm.type,
databaseID: changeForm.databaseID, database: changeForm.database,
value: '', value: '',
}; };
if (changeForm.operation === 'password') { if (changeForm.operation === 'password') {
@ -202,7 +202,7 @@ const onSubmit = async () => {
id: changeForm.id, id: changeForm.id,
from: changeForm.from, from: changeForm.from,
type: changeForm.type, type: changeForm.type,
databaseID: changeForm.databaseID, database: changeForm.database,
value: changeForm.password, value: changeForm.password,
}; };
loading.value = true; loading.value = true;

View File

@ -188,12 +188,10 @@ const variables = ref();
interface DBProps { interface DBProps {
type: string; type: string;
database: string; database: string;
databaseID: string;
} }
const props = withDefaults(defineProps<DBProps>(), { const props = withDefaults(defineProps<DBProps>(), {
type: '', type: '',
database: '', database: '',
databaseID: '',
}); });
const dialogContainerLogRef = ref(); const dialogContainerLogRef = ref();
@ -261,7 +259,8 @@ const getDefaultConfig = async () => {
const onSubmitChangeConf = async () => { const onSubmitChangeConf = async () => {
let param = { let param = {
databaseID: Number(props.databaseID), type: props.type,
database: props.database,
file: mysqlConf.value, file: mysqlConf.value,
}; };
loading.value = true; loading.value = true;
@ -291,7 +290,7 @@ const loadContainerLog = async (containerID: string) => {
}; };
const loadBaseInfo = async () => { const loadBaseInfo = async () => {
const res = await loadMysqlBaseInfo(Number(props.databaseID)); const res = await loadMysqlBaseInfo(props.type, props.database);
mysqlName.value = res.data?.name; mysqlName.value = res.data?.name;
baseInfo.port = res.data?.port; baseInfo.port = res.data?.port;
baseInfo.containerID = res.data?.containerName; baseInfo.containerID = res.data?.containerName;
@ -304,22 +303,23 @@ const changeLoading = (status: boolean) => {
}; };
const loadVariables = async () => { const loadVariables = async () => {
const res = await loadMysqlVariables(Number(props.databaseID)); const res = await loadMysqlVariables(props.type, props.database);
variables.value = res.data; variables.value = res.data;
variablesRef.value!.acceptParams({ variablesRef.value!.acceptParams({
databaseID: Number(props.databaseID), type: props.type,
database: props.database,
mysqlVersion: mysqlVersion.value, mysqlVersion: mysqlVersion.value,
variables: res.data, variables: res.data,
}); });
}; };
const loadSlowLogs = async () => { const loadSlowLogs = async () => {
const res = await loadMysqlVariables(Number(props.databaseID)); const res = await loadMysqlVariables(props.type, props.database);
variables.value = res.data; variables.value = res.data;
let param = { let param = {
type: props.type, type: props.type,
database: props.database, database: props.database,
databaseID: Number(props.databaseID),
variables: variables.value, variables: variables.value,
}; };
slowLogRef.value!.acceptParams(param); slowLogRef.value!.acceptParams(param);
@ -351,7 +351,7 @@ const onLoadInfo = async () => {
if (mysqlStatus.value === 'Running') { if (mysqlStatus.value === 'Running') {
loadVariables(); loadVariables();
loadSlowLogs(); loadSlowLogs();
statusRef.value!.acceptParams({ databaseID: Number(props.databaseID) }); statusRef.value!.acceptParams({ type: props.type, database: props.database });
} }
}); });
}; };

View File

@ -79,18 +79,15 @@ const variables = reactive({
const currentDB = reactive({ const currentDB = reactive({
type: '', type: '',
database: '', database: '',
databaseID: 0,
}); });
interface DialogProps { interface DialogProps {
type: string; type: string;
database: string; database: string;
databaseID: number;
variables: Database.MysqlVariables; variables: Database.MysqlVariables;
} }
const acceptParams = async (params: DialogProps): Promise<void> => { const acceptParams = async (params: DialogProps): Promise<void> => {
currentDB.type = params.type; currentDB.type = params.type;
currentDB.database = params.database; currentDB.database = params.database;
currentDB.databaseID = params.databaseID;
variables.slow_query_log = params.variables.slow_query_log; variables.slow_query_log = params.variables.slow_query_log;
variables.long_query_time = Number(params.variables.long_query_time); variables.long_query_time = Number(params.variables.long_query_time);
@ -152,7 +149,8 @@ const onSave = async () => {
param.push({ param: 'slow_query_log_file', value: '/var/lib/mysql/1Panel-slow.log' }); param.push({ param: 'slow_query_log_file', value: '/var/lib/mysql/1Panel-slow.log' });
} }
let params = { let params = {
databaseID: currentDB.databaseID, type: currentDB.type,
database: currentDB.database,
variables: param, variables: param,
}; };
emit('loading', true); emit('loading', true);

View File

@ -209,20 +209,23 @@ let mysqlStatus = reactive({
}); });
const currentDB = reactive({ const currentDB = reactive({
databaseID: 0, type: '',
database: '',
}); });
interface DialogProps { interface DialogProps {
databaseID: number; type: string;
database: string;
} }
const acceptParams = (params: DialogProps): void => { const acceptParams = (params: DialogProps): void => {
currentDB.databaseID = params.databaseID; currentDB.type = params.type;
currentDB.database = params.database;
loadStatus(); loadStatus();
}; };
const loadStatus = async () => { const loadStatus = async () => {
const res = await loadMysqlStatus(currentDB.databaseID); const res = await loadMysqlStatus(currentDB.type, currentDB.database);
let queryPerSecond = res.data.Questions / res.data.Uptime; let queryPerSecond = res.data.Questions / res.data.Uptime;
let txPerSecond = (res.data!.Com_commit + res.data.Com_rollback) / res.data.Uptime; let txPerSecond = (res.data!.Com_commit + res.data.Com_rollback) / res.data.Uptime;

View File

@ -170,16 +170,19 @@ const variablesRules = reactive({
}); });
const currentDB = reactive({ const currentDB = reactive({
databaseID: 0, type: '',
database: '',
version: '', version: '',
}); });
interface DialogProps { interface DialogProps {
databaseID: number; type: string;
database: string;
version: string; version: string;
variables: Database.MysqlVariables; variables: Database.MysqlVariables;
} }
const acceptParams = (params: DialogProps): void => { const acceptParams = (params: DialogProps): void => {
currentDB.databaseID = params.databaseID; currentDB.type = params.type;
currentDB.database = params.database;
currentDB.version = params.version; currentDB.version = params.version;
mysqlVariables.key_buffer_size = Number(params.variables.key_buffer_size) / 1024 / 1024; mysqlVariables.key_buffer_size = Number(params.variables.key_buffer_size) / 1024 / 1024;
mysqlVariables.query_cache_size = Number(params.variables.query_cache_size) / 1024 / 1024; mysqlVariables.query_cache_size = Number(params.variables.query_cache_size) / 1024 / 1024;
@ -285,7 +288,8 @@ const onSaveVariables = async () => {
} }
emit('loading', true); emit('loading', true);
let params = { let params = {
databaseID: currentDB.databaseID, type: currentDB.type,
database: currentDB.database,
variables: param, variables: param,
}; };
await updateMysqlVariables(params) await updateMysqlVariables(params)