sys_initdb.go 4.6 KB
Newer Older
1
package system
2 3

import (
4
	"database/sql"
5
	"fmt"
S
songzhibin97 已提交
6 7
	"path/filepath"

8 9 10 11 12 13 14
	"github.com/flipped-aurora/gin-vue-admin/server/config"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/example"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
	"github.com/flipped-aurora/gin-vue-admin/server/source"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
S
songzhibin97 已提交
15

16
	"github.com/spf13/viper"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
17 18
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
19 20
)

21 22 23
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: writeConfig
//@description: 回写配置
何秀钢 已提交
24
//@param: viper *viper.Viper, mysql config.Mysql
25 26
//@return: error

27 28 29 30
type InitDBService struct {
}

func (initDBService *InitDBService) writeConfig(viper *viper.Viper, mysql config.Mysql) error {
31 32 33
	global.GVA_CONFIG.Mysql = mysql
	cs := utils.StructToMap(global.GVA_CONFIG)
	for k, v := range cs {
34 35 36 37 38 39 40 41 42 43 44
		viper.Set(k, v)
	}
	return viper.WriteConfig()
}

//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: createTable
//@description: 创建数据库(mysql)
//@param: dsn string, driver string, createSql
//@return: error

45
func (initDBService *InitDBService) createTable(dsn string, driver string, createSql string) error {
46 47 48 49
	db, err := sql.Open(driver, dsn)
	if err != nil {
		return err
	}
50 51 52 53 54 55
	defer func(db *sql.DB) {
		err := db.Close()
		if err != nil {

		}
	}(db)
56 57 58 59 60 61 62
	if err = db.Ping(); err != nil {
		return err
	}
	_, err = db.Exec(createSql)
	return err
}

63
func (initDBService *InitDBService) initDB(InitDBFunctions ...system.InitDBFunc) (err error) {
64 65 66 67 68 69 70 71 72
	for _, v := range InitDBFunctions {
		err = v.Init()
		if err != nil {
			return err
		}
	}
	return nil
}

73 74 75
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: InitDB
//@description: 创建数据库并初始化
何秀钢 已提交
76 77
//@param: conf request.InitDB
//@return: error
78

79
func (initDBService *InitDBService) InitDB(conf request.InitDB) error {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
80

81 82 83
	if conf.Host == "" {
		conf.Host = "127.0.0.1"
	}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
84

85 86 87 88
	if conf.Port == "" {
		conf.Port = "3306"
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", conf.UserName, conf.Password, conf.Host, conf.Port)
89
	createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", conf.DBName)
90
	if err := initDBService.createTable(dsn, "mysql", createSql); err != nil {
91 92
		return err
	}
93 94 95 96 97 98 99

	MysqlConfig := config.Mysql{
		Path:     fmt.Sprintf("%s:%s", conf.Host, conf.Port),
		Dbname:   conf.DBName,
		Username: conf.UserName,
		Password: conf.Password,
		Config:   "charset=utf8mb4&parseTime=True&loc=Local",
100
	}
101

S
songzhibin97 已提交
102
	if MysqlConfig.Dbname == "" {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
103 104 105
		return nil
	}

S
songzhibin97 已提交
106
	linkDns := MysqlConfig.Username + ":" + MysqlConfig.Password + "@tcp(" + MysqlConfig.Path + ")/" + MysqlConfig.Dbname + "?" + MysqlConfig.Config
Mr.奇淼('s avatar
Mr.奇淼( 已提交
107 108 109 110 111 112 113 114 115 116 117 118
	mysqlConfig := mysql.Config{
		DSN:                       linkDns, // DSN data source name
		DefaultStringSize:         191,     // string 类型字段的默认长度
		DisableDatetimePrecision:  true,    // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,    // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,    // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false,   // 根据版本自动配置
	}
	if db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}); err != nil {
		return nil
	} else {
		sqlDB, _ := db.DB()
S
songzhibin97 已提交
119 120
		sqlDB.SetMaxIdleConns(MysqlConfig.MaxIdleConns)
		sqlDB.SetMaxOpenConns(MysqlConfig.MaxOpenConns)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
121 122 123 124
		global.GVA_DB = db
	}

	err := global.GVA_DB.AutoMigrate(
Mr.奇淼('s avatar
Mr.奇淼( 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138
		system.SysUser{},
		system.SysAuthority{},
		system.SysApi{},
		system.SysBaseMenu{},
		system.SysBaseMenuParameter{},
		system.JwtBlacklist{},
		system.SysDictionary{},
		system.SysDictionaryDetail{},
		example.ExaFileUploadAndDownload{},
		example.ExaFile{},
		example.ExaFileChunk{},
		example.ExaCustomer{},
		system.SysOperationRecord{},
		system.SysAutoCodeHistory{},
Mr.奇淼('s avatar
Mr.奇淼( 已提交
139 140
	)
	if err != nil {
S
songzhibin97 已提交
141
		global.GVA_DB = nil
Mr.奇淼('s avatar
Mr.奇淼( 已提交
142 143
		return err
	}
144
	err = initDBService.initDB(
Mr.奇淼('s avatar
Mr.奇淼( 已提交
145
		source.Admin,
146 147 148 149 150 151 152 153 154
		source.Api,
		source.AuthorityMenu,
		source.Authority,
		source.AuthoritiesMenus,
		source.Casbin,
		source.DataAuthorities,
		source.Dictionary,
		source.DictionaryDetail,
		source.File,
155 156 157
		source.BaseMenu,
		source.UserAuthority,
	)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
158
	if err != nil {
S
songzhibin97 已提交
159 160 161
		global.GVA_DB = nil
		return err
	}
162
	if err = initDBService.writeConfig(global.GVA_VP, MysqlConfig); err != nil {
163 164
		return err
	}
165
	global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
166 167
	return nil
}