Browse Source

新增功能-api生成数据库并初始化回写配置

修改gva initdb 判断是否已经创建的一些小问题
新增api生成数据库并初始化回写配置
修改文件:
server/cmd/gva/initdb.go
server/cmd/information/data_authorities.go
server/cmd/information/workflow.go
server/initialize/gorm
server/main.go

新增文件:
server/api/v1/sys.initdb.go
server/middleware/init.go
server/model/sys_init.go
server/service/sys_initdb.go
servcer/utils/init_db.go

迁移文件
server/cmd/gva/mysql.go->server/utils/mysql.go
main
songzhibin97 4 years ago
parent
commit
ae42da9c72
  1. 39
      server/api/v1/sys_initdb.go
  2. 14
      server/cmd/gva/initdb.go
  3. 3
      server/cmd/information/system/data_authorities.go
  4. 27
      server/cmd/information/system/workflow.go
  5. 11
      server/initialize/gorm.go
  6. 5
      server/initialize/router.go
  7. 3
      server/main.go
  8. 20
      server/middleware/init.go
  9. 9
      server/model/sys_init.go
  10. 40
      server/service/sys_initdb.go
  11. 54
      server/utils/init_db.go
  12. 7
      server/utils/mysql.go

39
server/api/v1/sys_initdb.go

@ -0,0 +1,39 @@
package v1
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/response"
"gin-vue-admin/service"
"go.uber.org/zap"
"github.com/gin-gonic/gin"
)
// @Tags InitDB
// @Summary 初始化用户数据库
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /init/db [post]
func InitDB(c *gin.Context) {
if global.GVA_DB != nil {
global.GVA_LOG.Error("非法访问")
response.FailWithMessage("非法访问", c)
return
}
var dbInfo model.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)
}

14
server/cmd/gva/initdb.go

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

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

@ -2,6 +2,7 @@ package information
import ( import (
"gin-vue-admin/global" "gin-vue-admin/global"
"github.com/gookit/color" "github.com/gookit/color"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -27,7 +28,7 @@ var infos = []DataAuthority{
//@description: sys_data_authority_id 表数据初始化 //@description: sys_data_authority_id 表数据初始化
func (d *dataAuthorities) Init() error { func (d *dataAuthorities) Init() error {
return global.GVA_DB.Table("sys_data_authority_id").Transaction(func(tx *gorm.DB) 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 表初始数据已存在!") color.Danger.Println("\n[Mysql] --> sys_data_authority_id 表初始数据已存在!")
return nil return nil
} }

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

@ -3,9 +3,10 @@ package information
import ( import (
"gin-vue-admin/global" "gin-vue-admin/global"
"gin-vue-admin/model" "gin-vue-admin/model"
"time"
"github.com/gookit/color" "github.com/gookit/color"
"gorm.io/gorm" "gorm.io/gorm"
"time"
) )
var Workflow = new(workflow) var Workflow = new(workflow)
@ -43,19 +44,33 @@ var WorkflowEndPoint = []model.WorkflowEndPoint{
//@description: 工作流相关 表数据初始化 //@description: 工作流相关 表数据初始化
func (w *workflow) Init() error { func (w *workflow) Init() error {
return global.GVA_DB.Transaction(func(tx *gorm.DB) 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 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 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 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 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 return err
} }
color.Info.Println("\n[Mysql] --> 工作流相关 表初始数据成功!") color.Info.Println("\n[Mysql] --> 工作流相关 表初始数据成功!")

11
server/initialize/gorm.go

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

5
server/initialize/router.go

@ -1,20 +1,23 @@
package initialize package initialize
import ( import (
v1 "gin-vue-admin/api/v1"
_ "gin-vue-admin/docs" _ "gin-vue-admin/docs"
"gin-vue-admin/global" "gin-vue-admin/global"
"gin-vue-admin/middleware" "gin-vue-admin/middleware"
"gin-vue-admin/router" "gin-vue-admin/router"
"net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles" "github.com/swaggo/gin-swagger/swaggerFiles"
"net/http"
) )
// 初始化总路由 // 初始化总路由
func Routers() *gin.Engine { func Routers() *gin.Engine {
var Router = gin.Default() var Router = gin.Default()
Router.POST("initdb", v1.InitDB)
Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.Path)) // 为用户头像和文件提供静态地址 Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.Path)) // 为用户头像和文件提供静态地址
// Router.Use(middleware.LoadTls()) // 打开就能玩https了 // Router.Use(middleware.LoadTls()) // 打开就能玩https了
global.GVA_LOG.Info("use middleware logger") 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_VP = core.Viper() // 初始化Viper
global.GVA_LOG = core.Zap() // 初始化zap日志库 global.GVA_LOG = core.Zap() // 初始化zap日志库
global.GVA_DB = initialize.Gorm() // gorm连接数据库 global.GVA_DB = initialize.Gorm() // gorm连接数据库
if global.GVA_DB != nil {
initialize.MysqlTables(global.GVA_DB) // 初始化表 initialize.MysqlTables(global.GVA_DB) // 初始化表
// 程序结束前关闭数据库链接 // 程序结束前关闭数据库链接
db, _ := global.GVA_DB.DB() db, _ := global.GVA_DB.DB()
defer db.Close() defer db.Close()
}
core.RunWindowsServer() 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/sys_init.go

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