1
This commit is contained in:
204
app/other/apis/file.go
Normal file
204
app/other/apis/file.go
Normal file
@ -0,0 +1,204 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/utils"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"go-admin/common/file_store"
|
||||
)
|
||||
|
||||
type FileResponse struct {
|
||||
Size int64 `json:"size"`
|
||||
Path string `json:"path"`
|
||||
FullPath string `json:"full_path"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
const path = "static/uploadfile/"
|
||||
|
||||
type File struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// UploadFile 上传图片
|
||||
// @Summary 上传图片
|
||||
// @Description 获取JSON
|
||||
// @Tags 公共接口
|
||||
// @Accept multipart/form-data
|
||||
// @Param type query string true "type" (1:单图,2:多图, 3:base64图片)
|
||||
// @Param file formData file true "file"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/public/uploadFile [post]
|
||||
// @Security Bearer
|
||||
func (e File) UploadFile(c *gin.Context) {
|
||||
e.MakeContext(c)
|
||||
tag, _ := c.GetPostForm("type")
|
||||
urlPrefix := fmt.Sprintf("%s://%s/", "http", c.Request.Host)
|
||||
var fileResponse FileResponse
|
||||
|
||||
switch tag {
|
||||
case "1": // 单图
|
||||
var done bool
|
||||
fileResponse, done = e.singleFile(c, fileResponse, urlPrefix)
|
||||
if done {
|
||||
return
|
||||
}
|
||||
e.OK(fileResponse, "上传成功")
|
||||
return
|
||||
case "2": // 多图
|
||||
multipartFile := e.multipleFile(c, urlPrefix)
|
||||
e.OK(multipartFile, "上传成功")
|
||||
return
|
||||
case "3": // base64
|
||||
fileResponse = e.baseImg(c, fileResponse, urlPrefix)
|
||||
e.OK(fileResponse, "上传成功")
|
||||
default:
|
||||
var done bool
|
||||
fileResponse, done = e.singleFile(c, fileResponse, urlPrefix)
|
||||
if done {
|
||||
return
|
||||
}
|
||||
e.OK(fileResponse, "上传成功")
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (e File) baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileResponse {
|
||||
files, _ := c.GetPostForm("file")
|
||||
file2list := strings.Split(files, ",")
|
||||
ddd, _ := base64.StdEncoding.DecodeString(file2list[1])
|
||||
guid := uuid.New().String()
|
||||
fileName := guid + ".jpg"
|
||||
err := utils.IsNotExistMkDir(path)
|
||||
if err != nil {
|
||||
e.Error(500, errors.New(""), "初始化文件路径失败")
|
||||
}
|
||||
base64File := path + fileName
|
||||
_ = ioutil.WriteFile(base64File, ddd, 0666)
|
||||
typeStr := strings.Replace(strings.Replace(file2list[0], "data:", "", -1), ";base64", "", -1)
|
||||
fileResponse = FileResponse{
|
||||
Size: pkg.GetFileSize(base64File),
|
||||
Path: base64File,
|
||||
FullPath: urlPerfix + base64File,
|
||||
Name: "",
|
||||
Type: typeStr,
|
||||
}
|
||||
source, _ := c.GetPostForm("source")
|
||||
err = thirdUpload(source, fileName, base64File)
|
||||
if err != nil {
|
||||
e.Error(200, errors.New(""), "上传第三方失败")
|
||||
return fileResponse
|
||||
}
|
||||
if source != "1" {
|
||||
fileResponse.Path = "/static/uploadfile/" + fileName
|
||||
fileResponse.FullPath = "/static/uploadfile/" + fileName
|
||||
}
|
||||
return fileResponse
|
||||
}
|
||||
|
||||
func (e File) multipleFile(c *gin.Context, urlPerfix string) []FileResponse {
|
||||
files := c.Request.MultipartForm.File["file"]
|
||||
source, _ := c.GetPostForm("source")
|
||||
var multipartFile []FileResponse
|
||||
for _, f := range files {
|
||||
guid := uuid.New().String()
|
||||
fileName := guid + utils.GetExt(f.Filename)
|
||||
|
||||
err := utils.IsNotExistMkDir(path)
|
||||
if err != nil {
|
||||
e.Error(500, errors.New(""), "初始化文件路径失败")
|
||||
}
|
||||
multipartFileName := path + fileName
|
||||
err1 := c.SaveUploadedFile(f, multipartFileName)
|
||||
fileType, _ := utils.GetType(multipartFileName)
|
||||
if err1 == nil {
|
||||
err := thirdUpload(source, fileName, multipartFileName)
|
||||
if err != nil {
|
||||
e.Error(500, errors.New(""), "上传第三方失败")
|
||||
} else {
|
||||
fileResponse := FileResponse{
|
||||
Size: pkg.GetFileSize(multipartFileName),
|
||||
Path: multipartFileName,
|
||||
FullPath: urlPerfix + multipartFileName,
|
||||
Name: f.Filename,
|
||||
Type: fileType,
|
||||
}
|
||||
if source != "1" {
|
||||
fileResponse.Path = "/static/uploadfile/" + fileName
|
||||
fileResponse.FullPath = "/static/uploadfile/" + fileName
|
||||
}
|
||||
multipartFile = append(multipartFile, fileResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
return multipartFile
|
||||
}
|
||||
|
||||
func (e File) singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (FileResponse, bool) {
|
||||
files, err := c.FormFile("file")
|
||||
|
||||
if err != nil {
|
||||
e.Error(200, errors.New(""), "图片不能为空")
|
||||
return FileResponse{}, true
|
||||
}
|
||||
// 上传文件至指定目录
|
||||
guid := uuid.New().String()
|
||||
|
||||
fileName := guid + utils.GetExt(files.Filename)
|
||||
|
||||
err = utils.IsNotExistMkDir(path)
|
||||
if err != nil {
|
||||
e.Error(500, errors.New(""), "初始化文件路径失败")
|
||||
}
|
||||
singleFile := path + fileName
|
||||
_ = c.SaveUploadedFile(files, singleFile)
|
||||
fileType, _ := utils.GetType(singleFile)
|
||||
fileResponse = FileResponse{
|
||||
Size: pkg.GetFileSize(singleFile),
|
||||
Path: singleFile,
|
||||
FullPath: urlPerfix + singleFile,
|
||||
Name: files.Filename,
|
||||
Type: fileType,
|
||||
}
|
||||
//source, _ := c.GetPostForm("source")
|
||||
//err = thirdUpload(source, fileName, singleFile)
|
||||
//if err != nil {
|
||||
// e.Error(200, errors.New(""), "上传第三方失败")
|
||||
// return FileResponse{}, true
|
||||
//}
|
||||
fileResponse.Path = "/static/uploadfile/" + fileName
|
||||
fileResponse.FullPath = "/static/uploadfile/" + fileName
|
||||
return fileResponse, false
|
||||
}
|
||||
|
||||
func thirdUpload(source string, name string, path string) error {
|
||||
switch source {
|
||||
case "2":
|
||||
return ossUpload("img/"+name, path)
|
||||
case "3":
|
||||
return qiniuUpload("img/"+name, path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ossUpload(name string, path string) error {
|
||||
oss := file_store.ALiYunOSS{}
|
||||
return oss.UpLoad(name, path)
|
||||
}
|
||||
|
||||
func qiniuUpload(name string, path string) error {
|
||||
oss := file_store.ALiYunOSS{}
|
||||
return oss.UpLoad(name, path)
|
||||
}
|
||||
186
app/other/apis/sys_server_monitor.go
Normal file
186
app/other/apis/sys_server_monitor.go
Normal file
@ -0,0 +1,186 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/shirou/gopsutil/v3/net"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
)
|
||||
|
||||
const (
|
||||
B = 1
|
||||
KB = 1024 * B
|
||||
MB = 1024 * KB
|
||||
GB = 1024 * MB
|
||||
)
|
||||
|
||||
var (
|
||||
//Version string
|
||||
//expectDiskFsTypes = []string{
|
||||
// "apfs", "ext4", "ext3", "ext2", "f2fs", "reiserfs", "jfs", "btrfs",
|
||||
// "fuseblk", "zfs", "simfs", "ntfs", "fat32", "exfat", "xfs", "fuse.rclone",
|
||||
//}
|
||||
excludeNetInterfaces = []string{
|
||||
"lo", "tun", "docker", "veth", "br-", "vmbr", "vnet", "kube",
|
||||
}
|
||||
//getMacDiskNo = regexp.MustCompile(`\/dev\/disk(\d)s.*`)
|
||||
)
|
||||
|
||||
var (
|
||||
netInSpeed, netOutSpeed, netInTransfer, netOutTransfer, lastUpdateNetStats uint64
|
||||
cachedBootTime time.Time
|
||||
)
|
||||
|
||||
type ServerMonitor struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetHourDiffer 获取相差时间
|
||||
func GetHourDiffer(startTime, endTime string) int64 {
|
||||
var hour int64
|
||||
t1, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
|
||||
t2, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
|
||||
if err == nil && t1.Before(t2) {
|
||||
diff := t2.Unix() - t1.Unix() //
|
||||
hour = diff / 3600
|
||||
return hour
|
||||
} else {
|
||||
return hour
|
||||
}
|
||||
}
|
||||
|
||||
// ServerInfo 获取系统信息
|
||||
// @Summary 系统信息
|
||||
// @Description 获取JSON
|
||||
// @Tags 系统信息
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/server-monitor [get]
|
||||
// @Security Bearer
|
||||
func (e ServerMonitor) ServerInfo(c *gin.Context) {
|
||||
e.Context = c
|
||||
|
||||
sysInfo, err := host.Info()
|
||||
osDic := make(map[string]interface{}, 0)
|
||||
osDic["goOs"] = runtime.GOOS
|
||||
osDic["arch"] = runtime.GOARCH
|
||||
osDic["mem"] = runtime.MemProfileRate
|
||||
osDic["compiler"] = runtime.Compiler
|
||||
osDic["version"] = runtime.Version()
|
||||
osDic["numGoroutine"] = runtime.NumGoroutine()
|
||||
osDic["ip"] = pkg.GetLocaHonst()
|
||||
osDic["projectDir"] = pkg.GetCurrentPath()
|
||||
osDic["hostName"] = sysInfo.Hostname
|
||||
osDic["time"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
|
||||
memory, _ := mem.VirtualMemory()
|
||||
memDic := make(map[string]interface{}, 0)
|
||||
memDic["used"] = memory.Used / MB
|
||||
memDic["total"] = memory.Total / MB
|
||||
|
||||
fmt.Println("mem", int(memory.Total/memory.Used*100))
|
||||
memDic["percent"] = pkg.Round(memory.UsedPercent, 2)
|
||||
|
||||
swapDic := make(map[string]interface{}, 0)
|
||||
swapDic["used"] = memory.SwapTotal - memory.SwapFree
|
||||
swapDic["total"] = memory.SwapTotal
|
||||
|
||||
cpuDic := make(map[string]interface{}, 0)
|
||||
cpuDic["cpuInfo"], _ = cpu.Info()
|
||||
percent, _ := cpu.Percent(0, false)
|
||||
cpuDic["percent"] = pkg.Round(percent[0], 2)
|
||||
cpuDic["cpuNum"], _ = cpu.Counts(false)
|
||||
|
||||
//服务器磁盘信息
|
||||
disklist := make([]disk.UsageStat, 0)
|
||||
//所有分区
|
||||
var diskTotal, diskUsed, diskUsedPercent float64
|
||||
diskInfo, err := disk.Partitions(true)
|
||||
if err == nil {
|
||||
for _, p := range diskInfo {
|
||||
diskDetail, err := disk.Usage(p.Mountpoint)
|
||||
if err == nil {
|
||||
diskDetail.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", diskDetail.UsedPercent), 64)
|
||||
diskDetail.Total = diskDetail.Total / 1024 / 1024
|
||||
diskDetail.Used = diskDetail.Used / 1024 / 1024
|
||||
diskDetail.Free = diskDetail.Free / 1024 / 1024
|
||||
disklist = append(disklist, *diskDetail)
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
d, _ := disk.Usage("/")
|
||||
|
||||
diskTotal = float64(d.Total / GB)
|
||||
diskUsed = float64(d.Used / GB)
|
||||
diskUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", d.UsedPercent), 64)
|
||||
|
||||
diskDic := make(map[string]interface{}, 0)
|
||||
diskDic["total"] = diskTotal
|
||||
diskDic["used"] = diskUsed
|
||||
diskDic["percent"] = diskUsedPercent
|
||||
|
||||
bootTime, _ := host.BootTime()
|
||||
cachedBootTime = time.Unix(int64(bootTime), 0)
|
||||
|
||||
TrackNetworkSpeed()
|
||||
netDic := make(map[string]interface{}, 0)
|
||||
netDic["in"] = pkg.Round(float64(netInSpeed/KB), 2)
|
||||
netDic["out"] = pkg.Round(float64(netOutSpeed/KB), 2)
|
||||
e.Custom(gin.H{
|
||||
"code": 200,
|
||||
"os": osDic,
|
||||
"mem": memDic,
|
||||
"cpu": cpuDic,
|
||||
"disk": diskDic,
|
||||
"net": netDic,
|
||||
"swap": swapDic,
|
||||
"location": "Aliyun",
|
||||
"bootTime": GetHourDiffer(cachedBootTime.Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05")),
|
||||
})
|
||||
}
|
||||
|
||||
func TrackNetworkSpeed() {
|
||||
var innerNetInTransfer, innerNetOutTransfer uint64
|
||||
nc, err := net.IOCounters(true)
|
||||
if err == nil {
|
||||
for _, v := range nc {
|
||||
if isListContainsStr(excludeNetInterfaces, v.Name) {
|
||||
continue
|
||||
}
|
||||
innerNetInTransfer += v.BytesRecv
|
||||
innerNetOutTransfer += v.BytesSent
|
||||
}
|
||||
now := uint64(time.Now().Unix())
|
||||
diff := now - lastUpdateNetStats
|
||||
if diff > 0 {
|
||||
netInSpeed = (innerNetInTransfer - netInTransfer) / diff
|
||||
fmt.Println("netInSpeed", netInSpeed)
|
||||
netOutSpeed = (innerNetOutTransfer - netOutTransfer) / diff
|
||||
fmt.Println("netOutSpeed", netOutSpeed)
|
||||
}
|
||||
netInTransfer = innerNetInTransfer
|
||||
netOutTransfer = innerNetOutTransfer
|
||||
lastUpdateNetStats = now
|
||||
}
|
||||
}
|
||||
|
||||
func isListContainsStr(list []string, str string) bool {
|
||||
for i := 0; i < len(list); i++ {
|
||||
if strings.Contains(str, list[i]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
52
app/other/apis/tools/db_columns.go
Normal file
52
app/other/apis/tools/db_columns.go
Normal file
@ -0,0 +1,52 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
|
||||
"go-admin/app/other/models/tools"
|
||||
)
|
||||
|
||||
// GetDBColumnList 分页列表数据
|
||||
// @Summary 分页列表数据 / page list data
|
||||
// @Description 数据库表列分页列表 / database table column page list
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Param tableName query string false "tableName / 数据表名称"
|
||||
// @Param pageSize query int false "pageSize / 页条数"
|
||||
// @Param pageIndex query int false "pageIndex / 页码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/db/columns/page [get]
|
||||
func (e Gen) GetDBColumnList(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
var data tools.DBColumns
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize, err = pkg.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex, err = pkg.StringToInt(index)
|
||||
}
|
||||
|
||||
db, err := pkg.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
data.TableName = c.Request.FormValue("tableName")
|
||||
pkg.Assert(data.TableName == "", "table name cannot be empty!", 500)
|
||||
result, count, err := data.GetPage(db, pageSize, pageIndex)
|
||||
if err != nil {
|
||||
log.Errorf("GetPage error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
e.PageOK(result, count, pageIndex, pageSize, "查询成功")
|
||||
}
|
||||
60
app/other/apis/tools/db_tables.go
Normal file
60
app/other/apis/tools/db_tables.go
Normal file
@ -0,0 +1,60 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
|
||||
"go-admin/app/other/models/tools"
|
||||
)
|
||||
|
||||
// GetDBTableList 分页列表数据
|
||||
// @Summary 分页列表数据 / page list data
|
||||
// @Description 数据库表分页列表 / database table page list
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Param tableName query string false "tableName / 数据表名称"
|
||||
// @Param pageSize query int false "pageSize / 页条数"
|
||||
// @Param pageIndex query int false "pageIndex / 页码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/db/tables/page [get]
|
||||
func (e Gen) GetDBTableList(c *gin.Context) {
|
||||
//var res response.Response
|
||||
var data tools.DBTables
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
if config.DatabaseConfig.Driver == "sqlite3" || config.DatabaseConfig.Driver == "postgres" {
|
||||
err = errors.New("对不起,sqlite3 或 postgres 不支持代码生成!")
|
||||
log.Warn(err)
|
||||
e.Error(403, err, "")
|
||||
return
|
||||
}
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize, err = pkg.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex, err = pkg.StringToInt(index)
|
||||
}
|
||||
|
||||
db, err := pkg.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
data.TableName = c.Request.FormValue("tableName")
|
||||
result, count, err := data.GetPage(db, pageSize, pageIndex)
|
||||
if err != nil {
|
||||
log.Errorf("GetPage error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
e.PageOK(result, count, pageIndex, pageSize, "查询成功")
|
||||
}
|
||||
410
app/other/apis/tools/gen.go
Normal file
410
app/other/apis/tools/gen.go
Normal file
@ -0,0 +1,410 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
|
||||
"go-admin/app/other/models/tools"
|
||||
)
|
||||
|
||||
type Gen struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
func (e Gen) Preview(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
table := tools.SysTables{}
|
||||
id, err := pkg.StringToInt(c.Param("tableId"))
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("tableId接收失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
table.TableId = id
|
||||
t1, err := template.ParseFiles("template/v4/model.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("model模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t2, err := template.ParseFiles("template/v4/no_actions/apis.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("api模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t3, err := template.ParseFiles("template/v4/js.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("js模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t4, err := template.ParseFiles("template/v4/vue.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("vue模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t5, err := template.ParseFiles("template/v4/no_actions/router_check_role.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("路由模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t6, err := template.ParseFiles("template/v4/dto.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("dto模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t7, err := template.ParseFiles("template/v4/no_actions/service.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("service模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
db, err := pkg.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, fmt.Sprintf("数据库链接获取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
tab, _ := table.Get(db,false)
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
var b2 bytes.Buffer
|
||||
err = t2.Execute(&b2, tab)
|
||||
var b3 bytes.Buffer
|
||||
err = t3.Execute(&b3, tab)
|
||||
var b4 bytes.Buffer
|
||||
err = t4.Execute(&b4, tab)
|
||||
var b5 bytes.Buffer
|
||||
err = t5.Execute(&b5, tab)
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
var b7 bytes.Buffer
|
||||
err = t7.Execute(&b7, tab)
|
||||
|
||||
mp := make(map[string]interface{})
|
||||
mp["template/model.go.template"] = b1.String()
|
||||
mp["template/api.go.template"] = b2.String()
|
||||
mp["template/js.go.template"] = b3.String()
|
||||
mp["template/vue.go.template"] = b4.String()
|
||||
mp["template/router.go.template"] = b5.String()
|
||||
mp["template/dto.go.template"] = b6.String()
|
||||
mp["template/service.go.template"] = b7.String()
|
||||
e.OK(mp, "")
|
||||
}
|
||||
|
||||
func (e Gen) GenCode(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
table := tools.SysTables{}
|
||||
id, err := pkg.StringToInt(c.Param("tableId"))
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("tableId参数接收失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
db, err := pkg.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, fmt.Sprintf("数据库链接获取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
table.TableId = id
|
||||
tab, _ := table.Get(db,false)
|
||||
|
||||
e.NOActionsGen(c, tab)
|
||||
|
||||
e.OK("", "Code generated successfully!")
|
||||
}
|
||||
|
||||
func (e Gen) GenApiToFile(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
table := tools.SysTables{}
|
||||
id, err := pkg.StringToInt(c.Param("tableId"))
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("tableId参数获取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
db, err := pkg.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, fmt.Sprintf("数据库链接获取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
table.TableId = id
|
||||
tab, _ := table.Get(db,false)
|
||||
e.genApiToFile(c, tab)
|
||||
|
||||
e.OK("", "Code generated successfully!")
|
||||
}
|
||||
|
||||
func (e Gen) NOActionsGen(c *gin.Context, tab tools.SysTables) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
tab.MLTBName = strings.Replace(tab.TBName, "_", "-", -1)
|
||||
|
||||
basePath := "template/v4/"
|
||||
routerFile := basePath + "no_actions/router_check_role.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerFile = basePath + "no_actions/router_no_check_role.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles(basePath + "model.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("model模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("api模版读取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t3, err := template.ParseFiles(routerFile)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("路由模版失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t4, err := template.ParseFiles(basePath + "js.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("js模版解析失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t5, err := template.ParseFiles(basePath + "vue.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("vue模版解析失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t6, err := template.ParseFiles(basePath + "dto.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("dto模版解析失败失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
t7, err := template.ParseFiles(basePath + "no_actions/service.go.template")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("service模版失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
_ = pkg.PathCreate("./app/" + tab.PackageName + "/apis/")
|
||||
_ = pkg.PathCreate("./app/" + tab.PackageName + "/models/")
|
||||
_ = pkg.PathCreate("./app/" + tab.PackageName + "/router/")
|
||||
_ = pkg.PathCreate("./app/" + tab.PackageName + "/service/dto/")
|
||||
_ = pkg.PathCreate(config.GenConfig.FrontPath + "/api/" + tab.PackageName + "/")
|
||||
err = pkg.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.PackageName + "/" + tab.MLTBName + "/")
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("views目录创建失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
var b2 bytes.Buffer
|
||||
err = t2.Execute(&b2, tab)
|
||||
var b3 bytes.Buffer
|
||||
err = t3.Execute(&b3, tab)
|
||||
var b4 bytes.Buffer
|
||||
err = t4.Execute(&b4, tab)
|
||||
var b5 bytes.Buffer
|
||||
err = t5.Execute(&b5, tab)
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
var b7 bytes.Buffer
|
||||
err = t7.Execute(&b7, tab)
|
||||
pkg.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.TBName+".go")
|
||||
pkg.FileCreate(b2, "./app/"+tab.PackageName+"/apis/"+tab.TBName+".go")
|
||||
pkg.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.TBName+".go")
|
||||
pkg.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.PackageName+"/"+tab.MLTBName+".js")
|
||||
pkg.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.PackageName+"/"+tab.MLTBName+"/index.vue")
|
||||
pkg.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.TBName+".go")
|
||||
pkg.FileCreate(b7, "./app/"+tab.PackageName+"/service/"+tab.TBName+".go")
|
||||
|
||||
}
|
||||
|
||||
func (e Gen) genApiToFile(c *gin.Context, tab tools.SysTables) {
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
basePath := "template/"
|
||||
|
||||
t1, err := template.ParseFiles(basePath + "api_migrate.template")
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("数据迁移模版解析失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
i := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, struct {
|
||||
tools.SysTables
|
||||
GenerateTime string
|
||||
}{tab, i})
|
||||
|
||||
pkg.FileCreate(b1, "./cmd/migrate/migration/version-local/"+i+"_migrate.go")
|
||||
|
||||
}
|
||||
|
||||
func (e Gen) GenMenuAndApi(c *gin.Context) {
|
||||
s := service.SysMenu{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
table := tools.SysTables{}
|
||||
id, err := pkg.StringToInt(c.Param("tableId"))
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("tableId参数解析失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
table.TableId = id
|
||||
tab, _ := table.Get(e.Orm,true)
|
||||
tab.MLTBName = strings.Replace(tab.TBName, "_", "-", -1)
|
||||
|
||||
Mmenu := dto.SysMenuInsertReq{}
|
||||
Mmenu.Title = tab.TableComment
|
||||
Mmenu.Icon = "pass"
|
||||
Mmenu.Path = "/" + tab.MLTBName
|
||||
Mmenu.MenuType = "M"
|
||||
Mmenu.Action = "无"
|
||||
Mmenu.ParentId = 0
|
||||
Mmenu.NoCache = false
|
||||
Mmenu.Component = "Layout"
|
||||
Mmenu.Sort = 0
|
||||
Mmenu.Visible = "0"
|
||||
Mmenu.IsFrame = "0"
|
||||
Mmenu.CreateBy = 1
|
||||
s.Insert(&Mmenu)
|
||||
|
||||
Cmenu := dto.SysMenuInsertReq{}
|
||||
Cmenu.MenuName = tab.ClassName + "Manage"
|
||||
Cmenu.Title = tab.TableComment
|
||||
Cmenu.Icon = "pass"
|
||||
Cmenu.Path = "/" + tab.PackageName + "/" + tab.MLTBName
|
||||
Cmenu.MenuType = "C"
|
||||
Cmenu.Action = "无"
|
||||
Cmenu.Permission = tab.PackageName + ":" + tab.BusinessName + ":list"
|
||||
Cmenu.ParentId = Mmenu.MenuId
|
||||
Cmenu.NoCache = false
|
||||
Cmenu.Component = "/" + tab.PackageName + "/" + tab.MLTBName + "/index"
|
||||
Cmenu.Sort = 0
|
||||
Cmenu.Visible = "0"
|
||||
Cmenu.IsFrame = "0"
|
||||
Cmenu.CreateBy = 1
|
||||
Cmenu.UpdateBy = 1
|
||||
s.Insert(&Cmenu)
|
||||
|
||||
MList := dto.SysMenuInsertReq{}
|
||||
MList.MenuName = ""
|
||||
MList.Title = "分页获取" + tab.TableComment
|
||||
MList.Icon = ""
|
||||
MList.Path = tab.TBName
|
||||
MList.MenuType = "F"
|
||||
MList.Action = "无"
|
||||
MList.Permission = tab.PackageName + ":" + tab.BusinessName + ":query"
|
||||
MList.ParentId = Cmenu.MenuId
|
||||
MList.NoCache = false
|
||||
MList.Sort = 0
|
||||
MList.Visible = "0"
|
||||
MList.IsFrame = "0"
|
||||
MList.CreateBy = 1
|
||||
MList.UpdateBy = 1
|
||||
s.Insert(&MList)
|
||||
|
||||
MCreate := dto.SysMenuInsertReq{}
|
||||
MCreate.MenuName = ""
|
||||
MCreate.Title = "创建" + tab.TableComment
|
||||
MCreate.Icon = ""
|
||||
MCreate.Path = tab.TBName
|
||||
MCreate.MenuType = "F"
|
||||
MCreate.Action = "无"
|
||||
MCreate.Permission = tab.PackageName + ":" + tab.BusinessName + ":add"
|
||||
MCreate.ParentId = Cmenu.MenuId
|
||||
MCreate.NoCache = false
|
||||
MCreate.Sort = 0
|
||||
MCreate.Visible = "0"
|
||||
MCreate.IsFrame = "0"
|
||||
MCreate.CreateBy = 1
|
||||
MCreate.UpdateBy = 1
|
||||
s.Insert(&MCreate)
|
||||
|
||||
MUpdate := dto.SysMenuInsertReq{}
|
||||
MUpdate.MenuName = ""
|
||||
MUpdate.Title = "修改" + tab.TableComment
|
||||
MUpdate.Icon = ""
|
||||
MUpdate.Path = tab.TBName
|
||||
MUpdate.MenuType = "F"
|
||||
MUpdate.Action = "无"
|
||||
MUpdate.Permission = tab.PackageName + ":" + tab.BusinessName + ":edit"
|
||||
MUpdate.ParentId = Cmenu.MenuId
|
||||
MUpdate.NoCache = false
|
||||
MUpdate.Sort = 0
|
||||
MUpdate.Visible = "0"
|
||||
MUpdate.IsFrame = "0"
|
||||
MUpdate.CreateBy = 1
|
||||
MUpdate.UpdateBy = 1
|
||||
s.Insert(&MUpdate)
|
||||
|
||||
MDelete := dto.SysMenuInsertReq{}
|
||||
MDelete.MenuName = ""
|
||||
MDelete.Title = "删除" + tab.TableComment
|
||||
MDelete.Icon = ""
|
||||
MDelete.Path = tab.TBName
|
||||
MDelete.MenuType = "F"
|
||||
MDelete.Action = "无"
|
||||
MDelete.Permission = tab.PackageName + ":" + tab.BusinessName + ":remove"
|
||||
MDelete.ParentId = Cmenu.MenuId
|
||||
MDelete.NoCache = false
|
||||
MDelete.Sort = 0
|
||||
MDelete.Visible = "0"
|
||||
MDelete.IsFrame = "0"
|
||||
MDelete.CreateBy = 1
|
||||
MDelete.UpdateBy = 1
|
||||
s.Insert(&MDelete)
|
||||
|
||||
e.OK("", "数据生成成功!")
|
||||
}
|
||||
361
app/other/apis/tools/sys_tables.go
Normal file
361
app/other/apis/tools/sys_tables.go
Normal file
@ -0,0 +1,361 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/other/models/tools"
|
||||
)
|
||||
|
||||
type SysTable struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage 分页列表数据
|
||||
// @Summary 分页列表数据
|
||||
// @Description 生成表分页列表
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Param tableName query string false "tableName / 数据表名称"
|
||||
// @Param pageSize query int false "pageSize / 页条数"
|
||||
// @Param pageIndex query int false "pageIndex / 页码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys/tables/page [get]
|
||||
func (e SysTable) GetPage(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
var data tools.SysTables
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize, err = pkg.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex, err = pkg.StringToInt(index)
|
||||
}
|
||||
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
data.TBName = c.Request.FormValue("tableName")
|
||||
data.TableComment = c.Request.FormValue("tableComment")
|
||||
result, count, err := data.GetPage(db, pageSize, pageIndex)
|
||||
if err != nil {
|
||||
log.Errorf("GetPage error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
e.PageOK(result, count, pageIndex, pageSize, "查询成功")
|
||||
}
|
||||
|
||||
// Get
|
||||
// @Summary 获取配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Param configKey path int true "configKey"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys/tables/info/{tableId} [get]
|
||||
// @Security Bearer
|
||||
func (e SysTable) Get(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
var data tools.SysTables
|
||||
data.TableId, _ = pkg.StringToInt(c.Param("tableId"))
|
||||
result, err := data.Get(db,true)
|
||||
if err != nil {
|
||||
log.Errorf("Get error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
|
||||
mp := make(map[string]interface{})
|
||||
mp["list"] = result.Columns
|
||||
mp["info"] = result
|
||||
e.OK(mp, "")
|
||||
}
|
||||
|
||||
func (e SysTable) GetSysTablesInfo(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
var data tools.SysTables
|
||||
if c.Request.FormValue("tableName") != "" {
|
||||
data.TBName = c.Request.FormValue("tableName")
|
||||
}
|
||||
result, err := data.Get(db,true)
|
||||
if err != nil {
|
||||
log.Errorf("Get error, %s", err.Error())
|
||||
e.Error(500, err, "抱歉未找到相关信息")
|
||||
return
|
||||
}
|
||||
|
||||
mp := make(map[string]interface{})
|
||||
mp["list"] = result.Columns
|
||||
mp["info"] = result
|
||||
e.OK(mp, "")
|
||||
//res.Data = mp
|
||||
//c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
func (e SysTable) GetSysTablesTree(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
var data tools.SysTables
|
||||
result, err := data.GetTree(db)
|
||||
if err != nil {
|
||||
log.Errorf("GetTree error, %s", err.Error())
|
||||
e.Error(500, err, "抱歉未找到相关信息")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(result, "")
|
||||
}
|
||||
|
||||
// Insert
|
||||
// @Summary 添加表结构
|
||||
// @Description 添加表结构
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param tables query string false "tableName / 数据表名称"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/sys/tables/info [post]
|
||||
// @Security Bearer
|
||||
func (e SysTable) Insert(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
tablesList := strings.Split(c.Request.FormValue("tables"), ",")
|
||||
for i := 0; i < len(tablesList); i++ {
|
||||
|
||||
data, err := genTableInit(db, tablesList, i, c)
|
||||
if err != nil {
|
||||
log.Errorf("genTableInit error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
|
||||
_, err = data.Create(db)
|
||||
if err != nil {
|
||||
log.Errorf("Create error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
}
|
||||
e.OK(nil, "添加成功")
|
||||
|
||||
}
|
||||
|
||||
func genTableInit(tx *gorm.DB, tablesList []string, i int, c *gin.Context) (tools.SysTables, error) {
|
||||
var data tools.SysTables
|
||||
var dbTable tools.DBTables
|
||||
var dbColumn tools.DBColumns
|
||||
data.TBName = tablesList[i]
|
||||
data.CreateBy = 0
|
||||
|
||||
dbTable.TableName = data.TBName
|
||||
dbtable, err := dbTable.Get(tx)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
|
||||
dbColumn.TableName = data.TBName
|
||||
tablenamelist := strings.Split(dbColumn.TableName, "_")
|
||||
for i := 0; i < len(tablenamelist); i++ {
|
||||
strStart := string([]byte(tablenamelist[i])[:1])
|
||||
strend := string([]byte(tablenamelist[i])[1:])
|
||||
// 大驼峰表名 结构体使用
|
||||
data.ClassName += strings.ToUpper(strStart) + strend
|
||||
// 小驼峰表名 js函数名和权限标识使用
|
||||
if i == 0 {
|
||||
data.BusinessName += strings.ToLower(strStart) + strend
|
||||
} else {
|
||||
data.BusinessName += strings.ToUpper(strStart) + strend
|
||||
}
|
||||
//data.PackageName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
//data.ModuleName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
}
|
||||
//data.ModuleFrontName = strings.ReplaceAll(data.ModuleName, "_", "-")
|
||||
data.PackageName = "admin"
|
||||
data.TplCategory = "crud"
|
||||
data.Crud = true
|
||||
// 中横线表名称,接口路径、前端文件夹名称和js名称使用
|
||||
data.ModuleName = strings.Replace(data.TBName, "_", "-", -1)
|
||||
dbcolumn, err := dbColumn.GetList(tx)
|
||||
data.CreateBy = 0
|
||||
data.TableComment = dbtable.TableComment
|
||||
if dbtable.TableComment == "" {
|
||||
data.TableComment = data.ClassName
|
||||
}
|
||||
|
||||
data.FunctionName = data.TableComment
|
||||
//data.BusinessName = data.ModuleName
|
||||
data.IsLogicalDelete = "1"
|
||||
data.LogicalDelete = true
|
||||
data.LogicalDeleteColumn = "is_del"
|
||||
data.IsActions = 2
|
||||
data.IsDataScope = 1
|
||||
data.IsAuth = 1
|
||||
|
||||
data.FunctionAuthor = "wenjianzhang"
|
||||
for i := 0; i < len(dbcolumn); i++ {
|
||||
var column tools.SysColumns
|
||||
column.ColumnComment = dbcolumn[i].ColumnComment
|
||||
column.ColumnName = dbcolumn[i].ColumnName
|
||||
column.ColumnType = dbcolumn[i].ColumnType
|
||||
column.Sort = i + 1
|
||||
column.Insert = true
|
||||
column.IsInsert = "1"
|
||||
column.QueryType = "EQ"
|
||||
column.IsPk = "0"
|
||||
|
||||
namelist := strings.Split(dbcolumn[i].ColumnName, "_")
|
||||
for i := 0; i < len(namelist); i++ {
|
||||
strStart := string([]byte(namelist[i])[:1])
|
||||
strend := string([]byte(namelist[i])[1:])
|
||||
column.GoField += strings.ToUpper(strStart) + strend
|
||||
if i == 0 {
|
||||
column.JsonField = strings.ToLower(strStart) + strend
|
||||
} else {
|
||||
column.JsonField += strings.ToUpper(strStart) + strend
|
||||
}
|
||||
}
|
||||
if strings.Contains(dbcolumn[i].ColumnKey, "PR") {
|
||||
column.IsPk = "1"
|
||||
column.Pk = true
|
||||
data.PkColumn = dbcolumn[i].ColumnName
|
||||
//column.GoField = strings.ToUpper(column.GoField)
|
||||
//column.JsonField = strings.ToUpper(column.JsonField)
|
||||
data.PkGoField = column.GoField
|
||||
data.PkJsonField = column.JsonField
|
||||
}
|
||||
column.IsRequired = "0"
|
||||
if strings.Contains(dbcolumn[i].IsNullable, "NO") {
|
||||
column.IsRequired = "1"
|
||||
column.Required = true
|
||||
}
|
||||
|
||||
if strings.Contains(dbcolumn[i].ColumnType, "int") {
|
||||
if strings.Contains(dbcolumn[i].ColumnKey, "PR") {
|
||||
column.GoType = "int"
|
||||
} else {
|
||||
column.GoType = "string"
|
||||
}
|
||||
column.HtmlType = "input"
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "timestamp") {
|
||||
column.GoType = "time.Time"
|
||||
column.HtmlType = "datetime"
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "datetime") {
|
||||
column.GoType = "time.Time"
|
||||
column.HtmlType = "datetime"
|
||||
} else {
|
||||
column.GoType = "string"
|
||||
column.HtmlType = "input"
|
||||
}
|
||||
|
||||
data.Columns = append(data.Columns, column)
|
||||
}
|
||||
return data, err
|
||||
}
|
||||
|
||||
// Update
|
||||
// @Summary 修改表结构
|
||||
// @Description 修改表结构
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body tools.SysTables true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/sys/tables/info [put]
|
||||
// @Security Bearer
|
||||
func (e SysTable) Update(c *gin.Context) {
|
||||
var data tools.SysTables
|
||||
err := c.Bind(&data)
|
||||
pkg.HasError(err, "数据解析失败", 500)
|
||||
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
data.UpdateBy = 0
|
||||
result, err := data.Update(db)
|
||||
if err != nil {
|
||||
log.Errorf("Update error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
e.OK(result, "修改成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除表结构
|
||||
// @Description 删除表结构
|
||||
// @Tags 工具 / 生成工具
|
||||
// @Param tableId path int true "tableId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/sys/tables/info/{tableId} [delete]
|
||||
func (e SysTable) Delete(c *gin.Context) {
|
||||
e.Context = c
|
||||
log := e.GetLogger()
|
||||
db, err := e.GetOrm()
|
||||
if err != nil {
|
||||
log.Errorf("get db connection error, %s", err.Error())
|
||||
e.Error(500, err, "数据库连接获取失败")
|
||||
return
|
||||
}
|
||||
|
||||
var data tools.SysTables
|
||||
IDS := pkg.IdsStrToIdsIntGroup("tableId", c)
|
||||
_, err = data.BatchDelete(db, IDS)
|
||||
if err != nil {
|
||||
log.Errorf("BatchDelete error, %s", err.Error())
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(nil, "删除成功")
|
||||
}
|
||||
70
app/other/models/tools/db_columns.go
Normal file
70
app/other/models/tools/db_columns.go
Normal file
@ -0,0 +1,70 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DBColumns struct {
|
||||
TableSchema string `gorm:"column:TABLE_SCHEMA" json:"tableSchema"`
|
||||
TableName string `gorm:"column:TABLE_NAME" json:"tableName"`
|
||||
ColumnName string `gorm:"column:COLUMN_NAME" json:"columnName"`
|
||||
ColumnDefault string `gorm:"column:COLUMN_DEFAULT" json:"columnDefault"`
|
||||
IsNullable string `gorm:"column:IS_NULLABLE" json:"isNullable"`
|
||||
DataType string `gorm:"column:DATA_TYPE" json:"dataType"`
|
||||
CharacterMaximumLength string `gorm:"column:CHARACTER_MAXIMUM_LENGTH" json:"characterMaximumLength"`
|
||||
CharacterSetName string `gorm:"column:CHARACTER_SET_NAME" json:"characterSetName"`
|
||||
ColumnType string `gorm:"column:COLUMN_TYPE" json:"columnType"`
|
||||
ColumnKey string `gorm:"column:COLUMN_KEY" json:"columnKey"`
|
||||
Extra string `gorm:"column:EXTRA" json:"extra"`
|
||||
ColumnComment string `gorm:"column:COLUMN_COMMENT" json:"columnComment"`
|
||||
}
|
||||
|
||||
func (e *DBColumns) GetPage(tx *gorm.DB, pageSize int, pageIndex int) ([]DBColumns, int, error) {
|
||||
var doc []DBColumns
|
||||
var count int64
|
||||
table := new(gorm.DB)
|
||||
|
||||
if config.DatabaseConfig.Driver == "mysql" {
|
||||
table = tx.Table("information_schema.`COLUMNS`")
|
||||
table = table.Where("table_schema= ? ", config.GenConfig.DBName)
|
||||
|
||||
if e.TableName != "" {
|
||||
return nil, 0, errors.New("table name cannot be empty!")
|
||||
}
|
||||
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName)
|
||||
}
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Count(&count)
|
||||
return doc, int(count), nil
|
||||
|
||||
}
|
||||
|
||||
func (e *DBColumns) GetList(tx *gorm.DB) ([]DBColumns, error) {
|
||||
var doc []DBColumns
|
||||
table := new(gorm.DB)
|
||||
|
||||
if e.TableName == "" {
|
||||
return nil, errors.New("table name cannot be empty!")
|
||||
}
|
||||
|
||||
if config.DatabaseConfig.Driver == "mysql" {
|
||||
table = tx.Table("information_schema.columns")
|
||||
table = table.Where("table_schema= ? ", config.GenConfig.DBName)
|
||||
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName).Order("ORDINAL_POSITION asc")
|
||||
} else {
|
||||
pkg.Assert(true, "目前只支持mysql数据库", 500)
|
||||
}
|
||||
if err := table.Find(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
62
app/other/models/tools/db_tables.go
Normal file
62
app/other/models/tools/db_tables.go
Normal file
@ -0,0 +1,62 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
config2 "github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
)
|
||||
|
||||
type DBTables struct {
|
||||
TableName string `gorm:"column:TABLE_NAME" json:"tableName"`
|
||||
Engine string `gorm:"column:ENGINE" json:"engine"`
|
||||
TableRows string `gorm:"column:TABLE_ROWS" json:"tableRows"`
|
||||
TableCollation string `gorm:"column:TABLE_COLLATION" json:"tableCollation"`
|
||||
CreateTime string `gorm:"column:CREATE_TIME" json:"createTime"`
|
||||
UpdateTime string `gorm:"column:UPDATE_TIME" json:"updateTime"`
|
||||
TableComment string `gorm:"column:TABLE_COMMENT" json:"tableComment"`
|
||||
}
|
||||
|
||||
func (e *DBTables) GetPage(tx *gorm.DB, pageSize int, pageIndex int) ([]DBTables, int, error) {
|
||||
var doc []DBTables
|
||||
table := new(gorm.DB)
|
||||
var count int64
|
||||
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table = tx.Table("information_schema.tables")
|
||||
table = table.Where("TABLE_NAME not in (select table_name from `" + config2.GenConfig.DBName + "`.sys_tables) ")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
|
||||
if e.TableName != "" {
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName)
|
||||
}
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
} else {
|
||||
pkg.Assert(true, "目前只支持mysql数据库", 500)
|
||||
}
|
||||
|
||||
//table.Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *DBTables) Get(tx *gorm.DB) (DBTables, error) {
|
||||
var doc DBTables
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table := tx.Table("information_schema.tables")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
if e.TableName == "" {
|
||||
return doc, errors.New("table name cannot be empty!")
|
||||
}
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName)
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
} else {
|
||||
pkg.Assert(true, "目前只支持mysql数据库", 500)
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
101
app/other/models/tools/sys_columns.go
Normal file
101
app/other/models/tools/sys_columns.go
Normal file
@ -0,0 +1,101 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
common "go-admin/common/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysColumns struct {
|
||||
ColumnId int `gorm:"primaryKey;autoIncrement" json:"columnId"`
|
||||
TableId int `gorm:"" json:"tableId"`
|
||||
ColumnName string `gorm:"size:128;" json:"columnName"`
|
||||
ColumnComment string `gorm:"column:column_comment;size:128;" json:"columnComment"`
|
||||
ColumnType string `gorm:"column:column_type;size:128;" json:"columnType"`
|
||||
GoType string `gorm:"column:go_type;size:128;" json:"goType"`
|
||||
GoField string `gorm:"column:go_field;size:128;" json:"goField"`
|
||||
JsonField string `gorm:"column:json_field;size:128;" json:"jsonField"`
|
||||
IsPk string `gorm:"column:is_pk;size:4;" json:"isPk"`
|
||||
IsIncrement string `gorm:"column:is_increment;size:4;" json:"isIncrement"`
|
||||
IsRequired string `gorm:"column:is_required;size:4;" json:"isRequired"`
|
||||
IsInsert string `gorm:"column:is_insert;size:4;" json:"isInsert"`
|
||||
IsEdit string `gorm:"column:is_edit;size:4;" json:"isEdit"`
|
||||
IsList string `gorm:"column:is_list;size:4;" json:"isList"`
|
||||
IsQuery string `gorm:"column:is_query;size:4;" json:"isQuery"`
|
||||
QueryType string `gorm:"column:query_type;size:128;" json:"queryType"`
|
||||
HtmlType string `gorm:"column:html_type;size:128;" json:"htmlType"`
|
||||
DictType string `gorm:"column:dict_type;size:128;" json:"dictType"`
|
||||
Sort int `gorm:"column:sort;" json:"sort"`
|
||||
List string `gorm:"column:list;size:1;" json:"list"`
|
||||
Pk bool `gorm:"column:pk;size:1;" json:"pk"`
|
||||
Required bool `gorm:"column:required;size:1;" json:"required"`
|
||||
SuperColumn bool `gorm:"column:super_column;size:1;" json:"superColumn"`
|
||||
UsableColumn bool `gorm:"column:usable_column;size:1;" json:"usableColumn"`
|
||||
Increment bool `gorm:"column:increment;size:1;" json:"increment"`
|
||||
Insert bool `gorm:"column:insert;size:1;" json:"insert"`
|
||||
Edit bool `gorm:"column:edit;size:1;" json:"edit"`
|
||||
Query bool `gorm:"column:query;size:1;" json:"query"`
|
||||
Remark string `gorm:"column:remark;size:255;" json:"remark"`
|
||||
FkTableName string `gorm:"" json:"fkTableName"`
|
||||
FkTableNameClass string `gorm:"" json:"fkTableNameClass"`
|
||||
FkTableNamePackage string `gorm:"" json:"fkTableNamePackage"`
|
||||
FkCol []SysColumns `gorm:"-" json:"fkCol"`
|
||||
FkLabelId string `gorm:"" json:"fkLabelId"`
|
||||
FkLabelName string `gorm:"size:255;" json:"fkLabelName"`
|
||||
CreateBy int `gorm:"column:create_by;size:20;" json:"createBy"`
|
||||
UpdateBy int `gorm:"column:update_By;size:20;" json:"updateBy"`
|
||||
|
||||
common.ModelTime
|
||||
}
|
||||
|
||||
func (*SysColumns) TableName() string {
|
||||
return "sys_columns"
|
||||
}
|
||||
|
||||
func (e *SysColumns) GetList(tx *gorm.DB, exclude bool) ([]SysColumns, error) {
|
||||
var doc []SysColumns
|
||||
table := tx.Table("sys_columns")
|
||||
table = table.Where("table_id = ? ", e.TableId)
|
||||
if exclude {
|
||||
notIn := make([]string, 0, 6)
|
||||
notIn = append(notIn, "id")
|
||||
notIn = append(notIn, "create_by")
|
||||
notIn = append(notIn, "update_by")
|
||||
notIn = append(notIn, "created_at")
|
||||
notIn = append(notIn, "updated_at")
|
||||
notIn = append(notIn, "deleted_at")
|
||||
table = table.Where(" column_name not in(?)", notIn)
|
||||
}
|
||||
|
||||
if err := table.Find(&doc).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysColumns) Create(tx *gorm.DB) (SysColumns, error) {
|
||||
var doc SysColumns
|
||||
e.CreateBy = 0
|
||||
result := tx.Table("sys_columns").Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysColumns) Update(tx *gorm.DB) (update SysColumns, err error) {
|
||||
if err = tx.Table("sys_columns").First(&update, e.ColumnId).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
e.UpdateBy = 0
|
||||
if err = tx.Table("sys_columns").Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
234
app/other/models/tools/sys_tables.go
Normal file
234
app/other/models/tools/sys_tables.go
Normal file
@ -0,0 +1,234 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
common "go-admin/common/models"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysTables struct {
|
||||
TableId int `gorm:"primaryKey;autoIncrement" json:"tableId"` //表编码
|
||||
TBName string `gorm:"column:table_name;size:255;" json:"tableName"` //表名称
|
||||
MLTBName string `gorm:"-" json:"-"` //表名称
|
||||
TableComment string `gorm:"size:255;" json:"tableComment"` //表备注
|
||||
ClassName string `gorm:"size:255;" json:"className"` //类名
|
||||
TplCategory string `gorm:"size:255;" json:"tplCategory"` //
|
||||
PackageName string `gorm:"size:255;" json:"packageName"` //包名
|
||||
ModuleName string `gorm:"size:255;" json:"moduleName"` //go文件名
|
||||
ModuleFrontName string `gorm:"size:255;comment:前端文件名;" json:"moduleFrontName"` //前端文件名
|
||||
BusinessName string `gorm:"size:255;" json:"businessName"` //
|
||||
FunctionName string `gorm:"size:255;" json:"functionName"` //功能名称
|
||||
FunctionAuthor string `gorm:"size:255;" json:"functionAuthor"` //功能作者
|
||||
PkColumn string `gorm:"size:255;" json:"pkColumn"`
|
||||
PkGoField string `gorm:"size:255;" json:"pkGoField"`
|
||||
PkJsonField string `gorm:"size:255;" json:"pkJsonField"`
|
||||
Options string `gorm:"size:255;" json:"options"`
|
||||
TreeCode string `gorm:"size:255;" json:"treeCode"`
|
||||
TreeParentCode string `gorm:"size:255;" json:"treeParentCode"`
|
||||
TreeName string `gorm:"size:255;" json:"treeName"`
|
||||
Tree bool `gorm:"size:1;default:0;" json:"tree"`
|
||||
Crud bool `gorm:"size:1;default:1;" json:"crud"`
|
||||
Remark string `gorm:"size:255;" json:"remark"`
|
||||
IsDataScope int `gorm:"size:1;" json:"isDataScope"`
|
||||
IsActions int `gorm:"size:1;" json:"isActions"`
|
||||
IsAuth int `gorm:"size:1;" json:"isAuth"`
|
||||
IsLogicalDelete string `gorm:"size:1;" json:"isLogicalDelete"`
|
||||
LogicalDelete bool `gorm:"size:1;" json:"logicalDelete"`
|
||||
LogicalDeleteColumn string `gorm:"size:128;" json:"logicalDeleteColumn"`
|
||||
common.ModelTime
|
||||
common.ControlBy
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
Params Params `gorm:"-" json:"params"`
|
||||
Columns []SysColumns `gorm:"-" json:"columns"`
|
||||
}
|
||||
|
||||
func (*SysTables) TableName() string {
|
||||
return "sys_tables"
|
||||
}
|
||||
|
||||
type Params struct {
|
||||
TreeCode string `gorm:"-" json:"treeCode"`
|
||||
TreeParentCode string `gorm:"-" json:"treeParentCode"`
|
||||
TreeName string `gorm:"-" json:"treeName"`
|
||||
}
|
||||
|
||||
func (e *SysTables) GetPage(tx *gorm.DB, pageSize int, pageIndex int) ([]SysTables, int, error) {
|
||||
var doc []SysTables
|
||||
|
||||
table := tx.Table("sys_tables")
|
||||
|
||||
if e.TBName != "" {
|
||||
table = table.Where("table_name = ?", e.TBName)
|
||||
}
|
||||
if e.TableComment != "" {
|
||||
table = table.Where("table_comment = ?", e.TableComment)
|
||||
}
|
||||
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysTables) Get(tx *gorm.DB, exclude bool) (SysTables, error) {
|
||||
var doc SysTables
|
||||
var err error
|
||||
table := tx.Table("sys_tables")
|
||||
|
||||
if e.TBName != "" {
|
||||
table = table.Where("table_name = ?", e.TBName)
|
||||
}
|
||||
if e.TableId != 0 {
|
||||
table = table.Where("table_id = ?", e.TableId)
|
||||
}
|
||||
if e.TableComment != "" {
|
||||
table = table.Where("table_comment = ?", e.TableComment)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
var col SysColumns
|
||||
col.TableId = doc.TableId
|
||||
if doc.Columns, err = col.GetList(tx, exclude); err != nil {
|
||||
return doc, err
|
||||
}
|
||||
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysTables) GetTree(tx *gorm.DB) ([]SysTables, error) {
|
||||
var doc []SysTables
|
||||
var err error
|
||||
table := tx.Table("sys_tables")
|
||||
|
||||
if e.TBName != "" {
|
||||
table = table.Where("table_name = ?", e.TBName)
|
||||
}
|
||||
if e.TableId != 0 {
|
||||
table = table.Where("table_id = ?", e.TableId)
|
||||
}
|
||||
if e.TableComment != "" {
|
||||
table = table.Where("table_comment = ?", e.TableComment)
|
||||
}
|
||||
|
||||
if err := table.Find(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
for i := 0; i < len(doc); i++ {
|
||||
var col SysColumns
|
||||
//col.FkCol = append(col.FkCol, SysColumns{ColumnId: 0, ColumnName: "请选择"})
|
||||
col.TableId = doc[i].TableId
|
||||
if doc[i].Columns, err = col.GetList(tx, false); err != nil {
|
||||
return doc, err
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysTables) Create(tx *gorm.DB) (SysTables, error) {
|
||||
var doc SysTables
|
||||
e.CreateBy = 0
|
||||
result := tx.Table("sys_tables").Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
for i := 0; i < len(e.Columns); i++ {
|
||||
e.Columns[i].TableId = doc.TableId
|
||||
|
||||
_, _ = e.Columns[i].Create(tx)
|
||||
}
|
||||
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysTables) Update(tx *gorm.DB) (update SysTables, err error) {
|
||||
//if err = orm.Eloquent.Table("sys_tables").First(&update, e.TableId).Error; err != nil {
|
||||
// return
|
||||
//}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
e.UpdateBy = 0
|
||||
if err = tx.Table("sys_tables").Where("table_id = ?", e.TableId).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tableNames := make([]string, 0)
|
||||
for i := range e.Columns {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
tableNames = append(tableNames, e.Columns[i].FkTableName)
|
||||
}
|
||||
}
|
||||
|
||||
tables := make([]SysTables, 0)
|
||||
tableMap := make(map[string]*SysTables)
|
||||
if len(tableNames) > 0 {
|
||||
if err = tx.Table("sys_tables").Where("table_name in (?)", tableNames).Find(&tables).Error; err != nil {
|
||||
return
|
||||
}
|
||||
for i := range tables {
|
||||
tableMap[tables[i].TBName] = &tables[i]
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < len(e.Columns); i++ {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
t, ok := tableMap[e.Columns[i].FkTableName]
|
||||
if ok {
|
||||
e.Columns[i].FkTableNameClass = t.ClassName
|
||||
t.MLTBName = strings.Replace(t.TBName, "_", "-", -1)
|
||||
e.Columns[i].FkTableNamePackage = t.MLTBName
|
||||
} else {
|
||||
tableNameList := strings.Split(e.Columns[i].FkTableName, "_")
|
||||
e.Columns[i].FkTableNameClass = ""
|
||||
//e.Columns[i].FkTableNamePackage = ""
|
||||
for a := 0; a < len(tableNameList); a++ {
|
||||
strStart := string([]byte(tableNameList[a])[:1])
|
||||
strEnd := string([]byte(tableNameList[a])[1:])
|
||||
e.Columns[i].FkTableNameClass += strings.ToUpper(strStart) + strEnd
|
||||
//e.Columns[i].FkTableNamePackage += strings.ToLower(strStart) + strings.ToLower(strEnd)
|
||||
}
|
||||
}
|
||||
}
|
||||
_, _ = e.Columns[i].Update(tx)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysTables) Delete(db *gorm.DB) (success bool, err error) {
|
||||
tx := db.Begin()
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
} else {
|
||||
tx.Commit()
|
||||
}
|
||||
}()
|
||||
if err = tx.Table("sys_tables").Delete(SysTables{}, "table_id = ?", e.TableId).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
if err = tx.Table("sys_columns").Delete(SysColumns{}, "table_id = ?", e.TableId).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysTables) BatchDelete(tx *gorm.DB, id []int) (Result bool, err error) {
|
||||
if err = tx.Unscoped().Table(e.TableName()).Where(" table_id in (?)", id).Delete(&SysColumns{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
20
app/other/router/file.go
Normal file
20
app/other/router/file.go
Normal file
@ -0,0 +1,20 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/other/apis"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerFileRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerFileRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
var api = apis.File{}
|
||||
r := v1.Group("").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
r.POST("/public/uploadFile", api.UploadFile)
|
||||
}
|
||||
}
|
||||
56
app/other/router/gen_router.go
Normal file
56
app/other/router/gen_router.go
Normal file
@ -0,0 +1,56 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/app/other/apis/tools"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, sysNoCheckRoleRouter, registerDBRouter, registerSysTableRouter)
|
||||
}
|
||||
|
||||
func sysNoCheckRoleRouter(v1 *gin.RouterGroup ,authMiddleware *jwt.GinJWTMiddleware) {
|
||||
r1 := v1.Group("")
|
||||
{
|
||||
sys := apis.System{}
|
||||
r1.GET("/captcha", sys.GenerateCaptchaHandler)
|
||||
}
|
||||
|
||||
r := v1.Group("").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
gen := tools.Gen{}
|
||||
r.GET("/gen/preview/:tableId", gen.Preview)
|
||||
r.GET("/gen/toproject/:tableId", gen.GenCode)
|
||||
r.GET("/gen/apitofile/:tableId", gen.GenApiToFile)
|
||||
r.GET("/gen/todb/:tableId", gen.GenMenuAndApi)
|
||||
sysTable := tools.SysTable{}
|
||||
r.GET("/gen/tabletree", sysTable.GetSysTablesTree)
|
||||
}
|
||||
}
|
||||
|
||||
func registerDBRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
db := v1.Group("/db").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
gen := tools.Gen{}
|
||||
db.GET("/tables/page", gen.GetDBTableList)
|
||||
db.GET("/columns/page", gen.GetDBColumnList)
|
||||
}
|
||||
}
|
||||
|
||||
func registerSysTableRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
tables := v1.Group("/sys/tables")
|
||||
{
|
||||
sysTable := tools.SysTable{}
|
||||
tables.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/page", sysTable.GetPage)
|
||||
tablesInfo := tables.Group("/info").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
tablesInfo.POST("", sysTable.Insert)
|
||||
tablesInfo.PUT("", sysTable.Update)
|
||||
tablesInfo.DELETE("/:tableId", sysTable.Delete)
|
||||
tablesInfo.GET("/:tableId", sysTable.Get)
|
||||
tablesInfo.GET("", sysTable.GetSysTablesInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
36
app/other/router/init_router.go
Normal file
36
app/other/router/init_router.go
Normal file
@ -0,0 +1,36 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
common "go-admin/common/middleware"
|
||||
)
|
||||
|
||||
// InitRouter 路由初始化,不要怀疑,这里用到了
|
||||
func InitRouter() {
|
||||
var r *gin.Engine
|
||||
h := sdk.Runtime.GetEngine()
|
||||
if h == nil {
|
||||
log.Fatal("not found engine...")
|
||||
os.Exit(-1)
|
||||
}
|
||||
switch h.(type) {
|
||||
case *gin.Engine:
|
||||
r = h.(*gin.Engine)
|
||||
default:
|
||||
log.Fatal("not support other engine")
|
||||
os.Exit(-1)
|
||||
}
|
||||
// the jwt middleware
|
||||
authMiddleware, err := common.AuthInit()
|
||||
if err != nil {
|
||||
log.Fatalf("JWT Init Error, %s", err.Error())
|
||||
}
|
||||
|
||||
// 注册业务路由
|
||||
// TODO: 这里可存放业务路由,里边并无实际路由只有演示代码
|
||||
initRouter(r, authMiddleware)
|
||||
}
|
||||
23
app/other/router/monitor.go
Normal file
23
app/other/router/monitor.go
Normal file
@ -0,0 +1,23 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/tools/transfer"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerNoCheckRole = append(routerNoCheckRole, registerMonitorRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerMonitorRouter(v1 *gin.RouterGroup) {
|
||||
v1.GET("/metrics", transfer.Handler(promhttp.Handler()))
|
||||
//健康检查
|
||||
v1.GET("/health", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
|
||||
}
|
||||
42
app/other/router/router.go
Normal file
42
app/other/router/router.go
Normal file
@ -0,0 +1,42 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
)
|
||||
|
||||
var (
|
||||
routerNoCheckRole = make([]func(*gin.RouterGroup), 0)
|
||||
routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
|
||||
)
|
||||
|
||||
// initRouter 路由示例
|
||||
func initRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
|
||||
|
||||
// 无需认证的路由
|
||||
noCheckRoleRouter(r)
|
||||
// 需要认证的路由
|
||||
checkRoleRouter(r, authMiddleware)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// noCheckRoleRouter 无需认证的路由示例
|
||||
func noCheckRoleRouter(r *gin.Engine) {
|
||||
// 可根据业务需求来设置接口版本
|
||||
v1 := r.Group("/api/v1")
|
||||
|
||||
for _, f := range routerNoCheckRole {
|
||||
f(v1)
|
||||
}
|
||||
}
|
||||
|
||||
// checkRoleRouter 需要认证的路由示例
|
||||
func checkRoleRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
// 可根据业务需求来设置接口版本
|
||||
v1 := r.Group("/api/v1")
|
||||
|
||||
for _, f := range routerCheckRole {
|
||||
f(v1, authMiddleware)
|
||||
}
|
||||
}
|
||||
21
app/other/router/sys_server_monitor.go
Normal file
21
app/other/router/sys_server_monitor.go
Normal file
@ -0,0 +1,21 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/other/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysServerMonitorRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysServerMonitorRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.ServerMonitor{}
|
||||
r := v1.Group("/server-monitor").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.ServerInfo)
|
||||
}
|
||||
}
|
||||
6
app/other/service/dto/sys_tables.go
Normal file
6
app/other/service/dto/sys_tables.go
Normal file
@ -0,0 +1,6 @@
|
||||
package dto
|
||||
|
||||
type SysTableSearch struct {
|
||||
TBName string `form:"tableName" search:"type:exact;column:table_name;table:table_name"`
|
||||
TableComment string `form:"tableComment" search:"type:icontains;column:table_comment;table:table_comment"`
|
||||
}
|
||||
Reference in New Issue
Block a user