Files
mayfly-go/server/devops/api/db.go

269 lines
7.1 KiB
Go
Raw Normal View History

2021-09-11 14:04:09 +08:00
package api
2021-01-08 15:37:32 +08:00
import (
"fmt"
"io/ioutil"
2021-03-24 17:18:39 +08:00
"mayfly-go/base/biz"
2021-01-08 15:37:32 +08:00
"mayfly-go/base/ctx"
2021-04-16 15:10:07 +08:00
"mayfly-go/base/ginx"
2021-01-08 15:37:32 +08:00
"mayfly-go/base/model"
"mayfly-go/base/utils"
"mayfly-go/base/ws"
2021-09-11 14:04:09 +08:00
"mayfly-go/server/devops/api/form"
"mayfly-go/server/devops/api/vo"
"mayfly-go/server/devops/application"
"mayfly-go/server/devops/domain/entity"
sysApplication "mayfly-go/server/sys/application"
2021-01-08 15:37:32 +08:00
"strconv"
2021-04-21 10:22:09 +08:00
"strings"
2021-01-08 15:37:32 +08:00
2021-04-16 15:10:07 +08:00
"github.com/gin-gonic/gin"
)
2021-01-08 15:37:32 +08:00
type Db struct {
DbApp application.Db
MsgApp sysApplication.Msg
}
2021-01-08 15:37:32 +08:00
// @router /api/dbs [get]
func (d *Db) Dbs(rc *ctx.ReqCtx) {
g := rc.GinCtx
m := &entity.Db{EnvId: uint64(ginx.QueryInt(g, "envId", 0)),
ProjectId: uint64(ginx.QueryInt(g, "projectId", 0)),
Database: g.Query("database"),
}
m.CreatorId = rc.LoginAccount.Id
rc.ResData = d.DbApp.GetPageList(m, ginx.GetPageParam(rc.GinCtx), new([]vo.SelectDataDbVO))
2021-01-08 15:37:32 +08:00
}
func (d *Db) Save(rc *ctx.ReqCtx) {
form := &form.DbForm{}
ginx.BindJsonAndValid(rc.GinCtx, form)
rc.ReqParam = form
db := new(entity.Db)
utils.Copy(db, form)
db.SetBaseInfo(rc.LoginAccount)
d.DbApp.Save(db)
}
func (d *Db) DeleteDb(rc *ctx.ReqCtx) {
d.DbApp.Delete(GetDbId(rc.GinCtx))
}
func (d *Db) TableInfos(rc *ctx.ReqCtx) {
rc.ResData = d.DbApp.GetDbInstance(GetDbId(rc.GinCtx)).GetTableInfos()
}
func (d *Db) TableIndex(rc *ctx.ReqCtx) {
tn := rc.GinCtx.Query("tableName")
biz.NotEmpty(tn, "tableName不能为空")
rc.ResData = d.DbApp.GetDbInstance(GetDbId(rc.GinCtx)).GetTableIndex(tn)
}
func (d *Db) GetCreateTableDdl(rc *ctx.ReqCtx) {
tn := rc.GinCtx.Query("tableName")
biz.NotEmpty(tn, "tableName不能为空")
rc.ResData = d.DbApp.GetDbInstance(GetDbId(rc.GinCtx)).GetCreateTableDdl(tn)
}
// @router /api/db/:dbId/exec-sql [get]
func (d *Db) ExecSql(rc *ctx.ReqCtx) {
2021-04-16 15:10:07 +08:00
g := rc.GinCtx
2021-04-21 10:22:09 +08:00
// 去除前后空格及换行符
sql := strings.TrimFunc(g.Query("sql"), func(r rune) bool {
2021-04-21 10:22:09 +08:00
s := string(r)
return s == " " || s == "\n"
})
rc.ReqParam = sql
2021-04-21 10:22:09 +08:00
biz.NotEmpty(sql, "sql不能为空")
if strings.HasPrefix(sql, "SELECT") || strings.HasPrefix(sql, "select") {
colNames, res, err := d.DbApp.GetDbInstance(GetDbId(g)).SelectData(sql)
biz.ErrIsNilAppendErr(err, "查询失败: %s")
colAndRes := make(map[string]interface{})
colAndRes["colNames"] = colNames
colAndRes["res"] = res
rc.ResData = colAndRes
} else {
rowsAffected, err := d.DbApp.GetDbInstance(GetDbId(g)).Exec(sql)
biz.ErrIsNilAppendErr(err, "执行失败: %s")
res := make([]map[string]string, 0)
resData := make(map[string]string)
resData["影响条数"] = fmt.Sprintf("%d", rowsAffected)
res = append(res, resData)
colAndRes := make(map[string]interface{})
colAndRes["colNames"] = []string{"影响条数"}
colAndRes["res"] = res
rc.ResData = colAndRes
}
2021-01-08 15:37:32 +08:00
}
// 执行sql文件
func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
g := rc.GinCtx
fileheader, err := g.FormFile("file")
biz.ErrIsNilAppendErr(err, "读取sql文件失败: %s")
// 读取sql文件并根据;切割sql语句
file, _ := fileheader.Open()
filename := fileheader.Filename
bytes, _ := ioutil.ReadAll(file)
sqlContent := string(bytes)
sqls := strings.Split(sqlContent, ";")
dbId := GetDbId(g)
go func() {
db := d.DbApp.GetDbInstance(dbId)
dbEntity := d.DbApp.GetById(dbId)
dbInfo := fmt.Sprintf("于%s的%s环境", dbEntity.Name, dbEntity.Env)
defer func() {
if err := recover(); err != nil {
switch t := err.(type) {
case *biz.BizError:
d.MsgApp.CreateAndSend(rc.LoginAccount, ws.ErrMsg("sql脚本执行失败", fmt.Sprintf("[%s]%s执行失败: [%s]", filename, dbInfo, t.Error())))
}
}
}()
for _, sql := range sqls {
sql = strings.Trim(sql, " ")
if sql == "" || sql == "\n" {
continue
}
_, err := db.Exec(sql)
if err != nil {
d.MsgApp.CreateAndSend(rc.LoginAccount, ws.ErrMsg("sql脚本执行失败", fmt.Sprintf("[%s]%s执行失败: [%s]", filename, dbInfo, err.Error())))
return
}
}
d.MsgApp.CreateAndSend(rc.LoginAccount, ws.SuccessMsg("sql脚本执行成功", fmt.Sprintf("[%s]%s执行完成", filename, dbInfo)))
}()
}
2021-01-08 15:37:32 +08:00
// @router /api/db/:dbId/t-metadata [get]
func (d *Db) TableMA(rc *ctx.ReqCtx) {
rc.ResData = d.DbApp.GetDbInstance(GetDbId(rc.GinCtx)).GetTableMetedatas()
2021-01-08 15:37:32 +08:00
}
// @router /api/db/:dbId/c-metadata [get]
func (d *Db) ColumnMA(rc *ctx.ReqCtx) {
2021-04-16 15:10:07 +08:00
g := rc.GinCtx
tn := g.Query("tableName")
biz.NotEmpty(tn, "tableName不能为空")
rc.ResData = d.DbApp.GetDbInstance(GetDbId(rc.GinCtx)).GetColumnMetadatas(tn)
2021-01-08 15:37:32 +08:00
}
// @router /api/db/:dbId/hint-tables [get]
func (d *Db) HintTables(rc *ctx.ReqCtx) {
dbi := d.DbApp.GetDbInstance(GetDbId(rc.GinCtx))
// 获取所有表
2021-04-16 15:10:07 +08:00
tables := dbi.GetTableMetedatas()
tableNames := make([]string, 0)
2021-04-16 15:10:07 +08:00
for _, v := range tables {
tableNames = append(tableNames, v["tableName"])
}
// key = 表名value = 列名数组
res := make(map[string][]string)
// 表为空,则直接返回
if len(tableNames) == 0 {
rc.ResData = res
return
}
// 获取所有表下的所有列信息
columnMds := dbi.GetColumnMetadatas(tableNames...)
for _, v := range columnMds {
tName := v["tableName"]
if res[tName] == nil {
res[tName] = make([]string, 0)
2021-01-08 15:37:32 +08:00
}
columnName := fmt.Sprintf("%s [%s]", v["columnName"], v["columnType"])
comment := v["columnComment"]
// 如果字段备注不为空,则加上备注信息
if comment != "" {
columnName = fmt.Sprintf("%s[%s]", columnName, comment)
}
res[tName] = append(res[tName], columnName)
2021-04-16 15:10:07 +08:00
}
rc.ResData = res
2021-01-08 15:37:32 +08:00
}
// @router /api/db/:dbId/sql [post]
func (d *Db) SaveSql(rc *ctx.ReqCtx) {
2021-04-16 15:10:07 +08:00
g := rc.GinCtx
account := rc.LoginAccount
dbSqlForm := &form.DbSqlSaveForm{}
ginx.BindJsonAndValid(g, dbSqlForm)
rc.ReqParam = dbSqlForm
2021-01-08 15:37:32 +08:00
2021-04-16 15:10:07 +08:00
dbId := GetDbId(g)
// 判断dbId是否存在
2021-05-08 20:50:34 +08:00
err := model.GetById(new(entity.Db), dbId)
biz.ErrIsNil(err, "该数据库信息不存在")
2021-01-08 15:37:32 +08:00
2021-04-16 15:10:07 +08:00
// 获取用于是否有该dbsql的保存记录有则更改否则新增
dbSql := &entity.DbSql{Type: dbSqlForm.Type, DbId: dbId, Name: dbSqlForm.Name}
2021-04-16 15:10:07 +08:00
dbSql.CreatorId = account.Id
e := model.GetBy(dbSql)
2021-01-08 15:37:32 +08:00
2021-04-16 15:10:07 +08:00
dbSql.SetBaseInfo(account)
// 更新sql信息
dbSql.Sql = dbSqlForm.Sql
if e == nil {
model.UpdateById(dbSql)
} else {
model.Insert(dbSql)
}
2021-01-08 15:37:32 +08:00
}
// 获取所有保存的sql names
func (d *Db) GetSqlNames(rc *ctx.ReqCtx) {
// 获取用于是否有该dbsql的保存记录有则更改否则新增
dbSql := &entity.DbSql{Type: 1, DbId: GetDbId(rc.GinCtx)}
dbSql.CreatorId = rc.LoginAccount.Id
var sqls []entity.DbSql
model.ListBy(dbSql, &sqls, "id", "name")
rc.ResData = sqls
}
// 删除保存的sql
func (d *Db) DeleteSql(rc *ctx.ReqCtx) {
dbSql := &entity.DbSql{Type: 1, DbId: GetDbId(rc.GinCtx)}
dbSql.CreatorId = rc.LoginAccount.Id
dbSql.Name = rc.GinCtx.Query("name")
model.DeleteByCondition(dbSql)
}
2021-01-08 15:37:32 +08:00
// @router /api/db/:dbId/sql [get]
func (d *Db) GetSql(rc *ctx.ReqCtx) {
// 根据创建者id 数据库id以及sql模板名称查询保存的sql信息
2021-05-08 20:50:34 +08:00
dbSql := &entity.DbSql{Type: 1, DbId: GetDbId(rc.GinCtx)}
2021-04-16 15:10:07 +08:00
dbSql.CreatorId = rc.LoginAccount.Id
dbSql.Name = rc.GinCtx.Query("name")
2021-04-16 15:10:07 +08:00
e := model.GetBy(dbSql)
if e != nil {
return
}
rc.ResData = dbSql
2021-01-08 15:37:32 +08:00
}
2021-04-16 15:10:07 +08:00
func GetDbId(g *gin.Context) uint64 {
dbId, _ := strconv.Atoi(g.Param("dbId"))
2021-03-24 17:18:39 +08:00
biz.IsTrue(dbId > 0, "dbId错误")
2021-01-08 15:37:32 +08:00
return uint64(dbId)
}