Browse Source

Merge pull request #387 from songzhibin97/gva_gormv2_dev

新增功能-api生成数据库并初始化回写配置
main
奇淼(piexlmax 4 years ago
committed by GitHub
parent
commit
ded39b986a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 38
      server/api/v1/sys_initdb.go
  2. 5
      server/api/v1/sys_system.go
  3. 14
      server/cmd/gva/initdb.go
  4. 3
      server/cmd/information/system/data_authorities.go
  5. 27
      server/cmd/information/system/workflow.go
  6. 11
      server/initialize/gorm.go
  7. 5
      server/initialize/router.go
  8. 3
      server/main.go
  9. 20
      server/middleware/init.go
  10. 9
      server/model/request/sys_init.go
  11. 40
      server/service/sys_initdb.go
  12. 54
      server/utils/init_db.go
  13. 7
      server/utils/mysql.go

38
server/api/v1/sys_initdb.go

@ -0,0 +1,38 @@
package v1
import (
"gin-vue-admin/global"
"gin-vue-admin/model/request"
"gin-vue-admin/model/response"
"gin-vue-admin/service"
"go.uber.org/zap"
"github.com/gin-gonic/gin"
)
// @Tags InitDB
// @Summary 初始化用户数据库
// @Produce application/json
// @Param data body request.InitDB true "初始化数据库参数"
// @Success 200 {string} string "{"code":0,"data":{},"msg":"自动创建数据库成功"}"
// @Router /initdb [post]
func InitDB(c *gin.Context) {
if global.GVA_DB != nil {
global.GVA_LOG.Error("非法访问")
response.FailWithMessage("非法访问", c)
return
}
var dbInfo request.InitDB
if err := c.ShouldBindJSON(&dbInfo); err != nil {
global.GVA_LOG.Error("参数校验不通过", zap.Any("err", err))
response.FailWithMessage("参数校验不通过", c)
return
}
if err := service.InitDB(dbInfo); err != nil {
global.GVA_LOG.Error("自动创建数据库失败", zap.Any("err", err))
response.FailWithMessage("自动创建数据库失败", c)
return
}
response.OkWithData("自动创建数据库成功", c)
}

5
server/api/v1/sys_system.go

@ -51,9 +51,8 @@ func SetSystemConfig(c *gin.Context) {
// @Summary 重启系统
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body model.System true "重启系统"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"重启系统成功"}"
// @Router /system/ReloadSystem [post]
// @Success 200 {string} string "{"code":0,"data":{},"msg":"重启系统成功"}"
// @Router /system/reloadSystem [post]
func ReloadSystem(c *gin.Context) {
if runtime.GOOS == "windows" {
response.FailWithMessage("系统不支持", c)

14
server/cmd/gva/initdb.go

@ -17,6 +17,8 @@ package gva
import (
"gin-vue-admin/core"
"gin-vue-admin/utils"
"github.com/gookit/color"
_ "gin-vue-admin/core"
@ -39,15 +41,15 @@ var initdbCmd = &cobra.Command{
path, _ := cmd.Flags().GetString("path")
global.GVA_VP = core.Viper(path)
global.GVA_LOG = core.Zap() // 初始化zap日志库
Mysql.CheckDatabase()
Mysql.CheckUtf8mb4()
Mysql.Info()
Mysql.Init()
utils.Mysql.CheckDatabase()
utils.Mysql.CheckUtf8mb4()
utils.Mysql.Info()
utils.Mysql.Init()
switch frame {
case "gin":
if global.GVA_CONFIG.System.DbType == "mysql" {
Mysql.AutoMigrateTables()
Mysql.InitData()
utils.Mysql.AutoMigrateTables()
utils.Mysql.InitData()
}
case "gf":
color.Info.Println("gf功能开发中")

3
server/cmd/information/system/data_authorities.go

@ -2,6 +2,7 @@ package information
import (
"gin-vue-admin/global"
"github.com/gookit/color"
"gorm.io/gorm"
)
@ -27,7 +28,7 @@ var infos = []DataAuthority{
//@description: sys_data_authority_id 表数据初始化
func (d *dataAuthorities) Init() error {
return global.GVA_DB.Table("sys_data_authority_id").Transaction(func(tx *gorm.DB) error {
if tx.Where("authority_id IN ('888', '9528') ").Find(&[]DataAuthority{}).RowsAffected == 5 {
if tx.Where("sys_authority_authority_id IN ('888', '9528') ").Find(&[]DataAuthority{}).RowsAffected == 5 {
color.Danger.Println("\n[Mysql] --> sys_data_authority_id 表初始数据已存在!")
return nil
}

27
server/cmd/information/system/workflow.go

@ -3,9 +3,10 @@ package information
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
"time"
"github.com/gookit/color"
"gorm.io/gorm"
"time"
)
var Workflow = new(workflow)
@ -43,19 +44,33 @@ var WorkflowEndPoint = []model.WorkflowEndPoint{
//@description: 工作流相关 表数据初始化
func (w *workflow) Init() error {
return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&WorkflowProcess).Error; err != nil { // 遇到错误时回滚事务
if tx.Where("id IN ?", []string{"leaveFlow"}).Find(&[]model.WorkflowProcess{}).RowsAffected == 1 {
// continue
} else if err := tx.Create(&WorkflowProcess).Error; err != nil { // 遇到错误时回滚事务
return err
}
if err := tx.Create(&WorkflowNodes).Error; err != nil { // 遇到错误时回滚事务
if tx.Where("id IN ?", []string{"end1603681358043", "end1603681360882", "start1603681292875", "userTask1603681299962"}).Find(&[]model.WorkflowNode{}).RowsAffected == 4 {
// continue
} else if err := tx.Create(&WorkflowNodes).Error; err != nil { // 遇到错误时回滚事务
return err
}
if err := tx.Create(&WorkflowEdge).Error; err != nil { // 遇到错误时回滚事务
if tx.Where("id IN ?", []string{"flow1604985849039", "flow1604985879574", "flow1604985881207"}).Find(&[]model.WorkflowEdge{}).RowsAffected == 3 {
} else if err := tx.Create(&WorkflowEdge).Error; err != nil { // 遇到错误时回滚事务
return err
}
if err := tx.Create(&WorkflowStartPoint).Error; err != nil { // 遇到错误时回滚事务
if tx.Where("workflow_edge_id IN ?", []string{"flow1604985849039", "flow1604985879574", "flow1604985881207"}).Find(&[]model.WorkflowStartPoint{}).RowsAffected == 3 {
} else if err := tx.Create(&WorkflowStartPoint).Error; err != nil { // 遇到错误时回滚事务
return err
}
if err := tx.Create(&WorkflowEndPoint).Error; err != nil { // 遇到错误时回滚事务
if tx.Where("workflow_edge_id IN ?", []string{"flow1604985849039", "flow1604985879574", "flow1604985881207"}).Find(&[]model.WorkflowEndPoint{}).RowsAffected == 3 {
} else if err := tx.Create(&WorkflowEndPoint).Error; err != nil { // 遇到错误时回滚事务
return err
}
color.Info.Println("\n[Mysql] --> 工作流相关 表初始数据成功!")

11
server/initialize/gorm.go

@ -4,11 +4,12 @@ import (
"gin-vue-admin/global"
"gin-vue-admin/initialize/internal"
"gin-vue-admin/model"
"os"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"os"
)
//@author: SliverHorn
@ -70,6 +71,9 @@ func MysqlTables(db *gorm.DB) {
func GormMysql() *gorm.DB {
m := global.GVA_CONFIG.Mysql
if m.Dbname == "" {
return nil
}
dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
@ -80,8 +84,9 @@ func GormMysql() *gorm.DB {
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig(m.LogMode)); err != nil {
global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
os.Exit(0)
//global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
//os.Exit(0)
//return nil
return nil
} else {
sqlDB, _ := db.DB()

5
server/initialize/router.go

@ -1,20 +1,23 @@
package initialize
import (
v1 "gin-vue-admin/api/v1"
_ "gin-vue-admin/docs"
"gin-vue-admin/global"
"gin-vue-admin/middleware"
"gin-vue-admin/router"
"net/http"
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"net/http"
)
// 初始化总路由
func Routers() *gin.Engine {
var Router = gin.Default()
Router.POST("initdb", v1.InitDB)
Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.Path)) // 为用户头像和文件提供静态地址
// Router.Use(middleware.LoadTls()) // 打开就能玩https了
global.GVA_LOG.Info("use middleware logger")

3
server/main.go

@ -17,10 +17,11 @@ func main() {
global.GVA_VP = core.Viper() // 初始化Viper
global.GVA_LOG = core.Zap() // 初始化zap日志库
global.GVA_DB = initialize.Gorm() // gorm连接数据库
if global.GVA_DB != nil {
initialize.MysqlTables(global.GVA_DB) // 初始化表
// 程序结束前关闭数据库链接
db, _ := global.GVA_DB.DB()
defer db.Close()
}
core.RunWindowsServer()
}

20
server/middleware/init.go

@ -0,0 +1,20 @@
package middleware
import (
"gin-vue-admin/global"
"gin-vue-admin/model/response"
"github.com/gin-gonic/gin"
)
func InitCheck() gin.HandlerFunc {
return func(c *gin.Context) {
if global.GVA_DB == nil {
// 未初始化
response.FailWithDetailed(gin.H{"database": true}, "数据库未初始化", c)
c.Abort()
return
}
c.Next()
}
}

9
server/model/request/sys_init.go

@ -0,0 +1,9 @@
package request
type InitDB struct {
Host string `json:"host"`
Port string `json:"port"`
UserName string `json:"user_name" binding:"required"`
Password string `json:"password"`
DBName string `json:"db_name" binding:"required"`
}

40
server/service/sys_initdb.go

@ -0,0 +1,40 @@
package service
import (
"fmt"
"gin-vue-admin/global"
"gin-vue-admin/model/request"
"gin-vue-admin/utils"
)
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: InitDB
//@description: 创建数据库并初始化
//@param: authorityId string
//@return: err error, treeMap map[string][]model.SysMenu
func InitDB(conf request.InitDB) error {
if conf.Host == "" {
conf.Host = "127.0.0.1"
}
if conf.Port == "" {
conf.Port = "3306"
}
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", conf.UserName, conf.Password, conf.Host, conf.Port)
fmt.Println(dsn)
createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", conf.DBName)
if err := utils.CreateTable(dsn, "mysql", createSql); err != nil {
return err
}
setting := map[string]interface{}{
"mysql.path": fmt.Sprintf("%s:%s", conf.Host, conf.Port),
"mysql.db-name": conf.DBName,
"mysql.username": conf.UserName,
"mysql.password": conf.Password,
}
if err := utils.WriteConfig(global.GVA_VP, setting); err != nil {
return err
}
utils.InitDB()
return nil
}

54
server/utils/init_db.go

@ -0,0 +1,54 @@
package utils
import (
"database/sql"
"github.com/spf13/viper"
)
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: CreateTable
//@description: 创建数据库(mysql)
//@param: dsn string, driver string, createSql
//@return: error
func CreateTable(dsn string, driver string, createSql string) error {
db, err := sql.Open(driver, dsn)
if err != nil {
return err
}
defer db.Close()
if err = db.Ping(); err != nil {
return err
}
_, err = db.Exec(createSql)
return err
}
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: WriteConfig
//@description: 回写配置
//@param:
//@return: error
func WriteConfig(viper *viper.Viper, conf map[string]interface{}) error {
for k, v := range conf {
viper.Set(k, v)
}
return viper.WriteConfig()
}
//@author: [Songzhibin97](https://github.com/Songzhibin97)
//@function: InitDB
//@description: 初始化db
//@param:
//@return: error
func InitDB() {
Mysql.CheckDatabase()
Mysql.CheckUtf8mb4()
Mysql.Info()
Mysql.Init()
Mysql.AutoMigrateTables()
Mysql.InitData()
}

7
server/cmd/gva/mysql.go → server/utils/mysql.go

@ -1,4 +1,4 @@
package gva
package utils
import (
"fmt"
@ -6,13 +6,14 @@ import (
data "gin-vue-admin/cmd/information/system"
"gin-vue-admin/global"
"gin-vue-admin/model"
"os"
"strings"
gormadapter "github.com/casbin/gorm-adapter/v3"
"github.com/gookit/color"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"os"
"strings"
)
type DatabaseInfo struct {
Loading…
Cancel
Save