sys_initdb.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package system
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "path/filepath"
  6. "github.com/flipped-aurora/gin-vue-admin/server/config"
  7. "github.com/flipped-aurora/gin-vue-admin/server/global"
  8. "github.com/flipped-aurora/gin-vue-admin/server/model/example"
  9. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  10. "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
  11. "github.com/flipped-aurora/gin-vue-admin/server/source"
  12. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  13. "github.com/spf13/viper"
  14. "gorm.io/driver/mysql"
  15. "gorm.io/gorm"
  16. )
  17. //@author: [songzhibin97](https://github.com/songzhibin97)
  18. //@function: writeConfig
  19. //@description: 回写配置
  20. //@param: viper *viper.Viper, mysql config.Mysql
  21. //@return: error
  22. type InitDBService struct {
  23. }
  24. func (initDBService *InitDBService) writeConfig(viper *viper.Viper, mysql config.Mysql) error {
  25. global.GVA_CONFIG.Mysql = mysql
  26. cs := utils.StructToMap(global.GVA_CONFIG)
  27. for k, v := range cs {
  28. viper.Set(k, v)
  29. }
  30. return viper.WriteConfig()
  31. }
  32. //@author: [songzhibin97](https://github.com/songzhibin97)
  33. //@function: createTable
  34. //@description: 创建数据库(mysql)
  35. //@param: dsn string, driver string, createSql
  36. //@return: error
  37. func (initDBService *InitDBService) createTable(dsn string, driver string, createSql string) error {
  38. db, err := sql.Open(driver, dsn)
  39. if err != nil {
  40. return err
  41. }
  42. defer func(db *sql.DB) {
  43. err := db.Close()
  44. if err != nil {
  45. }
  46. }(db)
  47. if err = db.Ping(); err != nil {
  48. return err
  49. }
  50. _, err = db.Exec(createSql)
  51. return err
  52. }
  53. func (initDBService *InitDBService) initDB(InitDBFunctions ...system.InitDBFunc) (err error) {
  54. for _, v := range InitDBFunctions {
  55. err = v.Init()
  56. if err != nil {
  57. return err
  58. }
  59. }
  60. return nil
  61. }
  62. //@author: [songzhibin97](https://github.com/songzhibin97)
  63. //@function: InitDB
  64. //@description: 创建数据库并初始化
  65. //@param: conf request.InitDB
  66. //@return: error
  67. func (initDBService *InitDBService) InitDB(conf request.InitDB) error {
  68. if conf.Host == "" {
  69. conf.Host = "127.0.0.1"
  70. }
  71. if conf.Port == "" {
  72. conf.Port = "3306"
  73. }
  74. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", conf.UserName, conf.Password, conf.Host, conf.Port)
  75. createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", conf.DBName)
  76. if err := initDBService.createTable(dsn, "mysql", createSql); err != nil {
  77. return err
  78. }
  79. MysqlConfig := config.Mysql{
  80. Path: fmt.Sprintf("%s:%s", conf.Host, conf.Port),
  81. Dbname: conf.DBName,
  82. Username: conf.UserName,
  83. Password: conf.Password,
  84. Config: "charset=utf8mb4&parseTime=True&loc=Local",
  85. }
  86. if MysqlConfig.Dbname == "" {
  87. return nil
  88. }
  89. linkDns := MysqlConfig.Username + ":" + MysqlConfig.Password + "@tcp(" + MysqlConfig.Path + ")/" + MysqlConfig.Dbname + "?" + MysqlConfig.Config
  90. mysqlConfig := mysql.Config{
  91. DSN: linkDns, // DSN data source name
  92. DefaultStringSize: 191, // string 类型字段的默认长度
  93. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  94. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  95. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  96. SkipInitializeWithVersion: false, // 根据版本自动配置
  97. }
  98. if db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}); err != nil {
  99. return nil
  100. } else {
  101. sqlDB, _ := db.DB()
  102. sqlDB.SetMaxIdleConns(MysqlConfig.MaxIdleConns)
  103. sqlDB.SetMaxOpenConns(MysqlConfig.MaxOpenConns)
  104. global.GVA_DB = db
  105. }
  106. err := global.GVA_DB.AutoMigrate(
  107. system.SysUser{},
  108. system.SysAuthority{},
  109. system.SysApi{},
  110. system.SysBaseMenu{},
  111. system.SysBaseMenuParameter{},
  112. system.JwtBlacklist{},
  113. system.SysDictionary{},
  114. system.SysDictionaryDetail{},
  115. example.ExaFileUploadAndDownload{},
  116. example.ExaFile{},
  117. example.ExaFileChunk{},
  118. example.ExaCustomer{},
  119. system.SysOperationRecord{},
  120. system.SysAutoCodeHistory{},
  121. )
  122. if err != nil {
  123. global.GVA_DB = nil
  124. return err
  125. }
  126. err = initDBService.initDB(
  127. source.Admin,
  128. source.Api,
  129. source.AuthorityMenu,
  130. source.Authority,
  131. source.AuthoritiesMenus,
  132. source.Casbin,
  133. source.DataAuthorities,
  134. source.Dictionary,
  135. source.DictionaryDetail,
  136. source.File,
  137. source.BaseMenu,
  138. source.UserAuthority,
  139. )
  140. if err != nil {
  141. global.GVA_DB = nil
  142. return err
  143. }
  144. if err = initDBService.writeConfig(global.GVA_VP, MysqlConfig); err != nil {
  145. return err
  146. }
  147. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  148. return nil
  149. }