浏览代码

数据库初始化

wilgx0 4 年之前
父节点
当前提交
a047dea4ce
共有 2 个文件被更改,包括 33 次插入1 次删除
  1. 7 1
      internal/app/system/controller/sys_init.go
  2. 26 0
      internal/app/system/service/sys_init.go

+ 7 - 1
internal/app/system/controller/sys_init.go

@@ -43,6 +43,12 @@ func (c *sysDbInitController) GetEnvInfo(ctx context.Context, req *system.DbInit
 
 // 创建配置文件及数据库等
 func (c *sysDbInitController) CreateDb(ctx context.Context, req *system.DbInitCreateDbReq) (res *system.DbInitCreateDbRes, err error) {
+	// 生成数据库
+	err = service.SysInit().CreateDataBaseByName(ctx, req)
+	if err != nil {
+		return
+	}
+
 	// 生成配置文件
 	err = service.SysInit().CreateConfigFile(ctx, req)
 	if err != nil {
@@ -55,7 +61,7 @@ func (c *sysDbInitController) CreateDb(ctx context.Context, req *system.DbInitCr
 		return
 	}
 
-	// 生成数据库
+	// 生成数据库表机构及数据
 	err = service.SysInit().CreateDataBase(ctx, req.DbName)
 	if err != nil {
 		return

+ 26 - 0
internal/app/system/service/sys_init.go

@@ -4,6 +4,7 @@ import (
 	"bufio"
 	"bytes"
 	"context"
+	"fmt"
 	"github.com/gogf/gf/v2/container/gvar"
 	"github.com/gogf/gf/v2/database/gdb"
 	"github.com/gogf/gf/v2/database/gredis"
@@ -27,6 +28,9 @@ type ISysInit interface {
 
 	// 是否已生成配置文件
 	IsCreateConfigFile() bool
+
+	//创建数据库
+	CreateDataBaseByName(ctx context.Context, req *system.DbInitCreateDbReq) (err error)
 }
 
 func SysInit() ISysInit {
@@ -47,6 +51,28 @@ func init() {
 	SysInitConfig = c.MapStrVar()
 }
 
+// 创建数据库
+func (s *sysInit) CreateDataBaseByName(ctx context.Context, req *system.DbInitCreateDbReq) (err error) {
+	db, err := gdb.New(gdb.ConfigNode{
+		Type: "mysql",
+		Host: req.DbHost,
+		Port: fmt.Sprintf("%d", req.DbPort),
+		User: req.DbUser,
+		Pass: req.DbPass,
+	})
+	if err != nil {
+		return
+	}
+	defer db.Close(ctx)
+
+	_, err = db.Exec(ctx, fmt.Sprintf("CREATE DATABASE IF NOT EXISTS  `%s` DEFAULT CHARSET utf8mb4  COLLATE utf8mb4_general_ci", req.DbName))
+	if err != nil {
+		return
+	}
+
+	return
+}
+
 // 是否已经生成配置文件
 func (s *sysInit) IsCreateConfigFile() bool {
 	return libUtils.FileIsExisted(SysInitConfig["configPath"].String())