89 lines
2.4 KiB
Go
89 lines
2.4 KiB
Go
package db_service
|
|
|
|
import (
|
|
"context"
|
|
"cron_admin/app/constants/common"
|
|
"cron_admin/app/constants/errorcode"
|
|
"cron_admin/app/http/entities/backend"
|
|
"cron_admin/app/models/crondbmodel"
|
|
"cron_admin/app/utils/mapstructure"
|
|
"database/sql"
|
|
"fmt"
|
|
"time"
|
|
"xorm.io/builder"
|
|
)
|
|
|
|
func DbList(request *backend.DbListRequest, page int, limit int) (count int64, DbListInfo []crondbmodel.CronDb, err error) {
|
|
conn := builder.NewCond()
|
|
if request.DbName != "" {
|
|
conn = conn.And(builder.Like{"db_name", request.DbName})
|
|
}
|
|
if request.DbType != "" {
|
|
conn = conn.And(builder.Like{"db_type", request.DbType})
|
|
}
|
|
if request.DbPermission != 0 {
|
|
conn = conn.And(builder.Eq{"db_permission": request.DbPermission})
|
|
}
|
|
if request.Status != 0 {
|
|
conn = conn.And(builder.Eq{"status": request.Status})
|
|
}
|
|
session := crondbmodel.GetInstance().GetDb().Where(conn)
|
|
if page != 0 && limit != 0 {
|
|
session = session.Limit(limit, (page-1)*limit)
|
|
}
|
|
if request.DbPermission != 0 {
|
|
session = session.And(builder.Eq{"DbPermission": request.DbPermission})
|
|
}
|
|
count, err = session.OrderBy("db_id desc").Omit("source", "UpdateTime").FindAndCount(&DbListInfo)
|
|
if err != nil {
|
|
return
|
|
}
|
|
return
|
|
}
|
|
|
|
func DbAdd(request *backend.DbAddRequest) (err error) {
|
|
var db crondbmodel.CronDb
|
|
_ = mapstructure.Decode(request, &db)
|
|
db.Status = common.STATUS_DISABLE
|
|
_, err = crondbmodel.GetInstance().GetDb().InsertOne(db)
|
|
return
|
|
}
|
|
|
|
func DbEdit(request *backend.DbEditRequest) (err error) {
|
|
var info crondbmodel.CronDb
|
|
flag, _ := crondbmodel.GetInstance().GetDb().ID(request.DbId).Get(&info)
|
|
if !flag {
|
|
return
|
|
}
|
|
var db crondbmodel.CronDb
|
|
_ = mapstructure.Decode(request, &db)
|
|
if request.Source == "" {
|
|
request.Source = info.Source
|
|
}
|
|
_, err = crondbmodel.GetInstance().GetDb().ID(request.DbId).Update(&db)
|
|
return
|
|
}
|
|
|
|
func DbDel(request *backend.DbDeleteRequest) (err error) {
|
|
_, err = crondbmodel.GetInstance().GetDb().ID(request.DbId).Delete(&crondbmodel.CronDb{})
|
|
return
|
|
}
|
|
|
|
func DbTest(request *backend.DbTestRequest) (err error) {
|
|
// 打开数据库连接
|
|
db, err := sql.Open("mysql", request.Source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer db.Close()
|
|
// 使用 context 来设置 Ping 的超时时间
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
// 测试连接
|
|
err = db.PingContext(ctx)
|
|
if err != nil {
|
|
return errorcode.NewBusinessErr(301, fmt.Sprintf("数据库连接失败: %v", err))
|
|
}
|
|
return
|
|
}
|