You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

167 lines
4.4 KiB

3 years ago
3 years ago
  1. package system
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "gin-vue-admin/config"
  6. "gin-vue-admin/global"
  7. "gin-vue-admin/model/example"
  8. "gin-vue-admin/model/system"
  9. "gin-vue-admin/model/system/request"
  10. "gin-vue-admin/source"
  11. "gin-vue-admin/utils"
  12. "path/filepath"
  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.ExaSimpleUploader{},
  119. example.ExaCustomer{},
  120. system.SysOperationRecord{},
  121. system.SysAutoCodeHistory{},
  122. )
  123. if err != nil {
  124. global.GVA_DB = nil
  125. return err
  126. }
  127. err = initDBService.initDB(
  128. source.Admin,
  129. source.Api,
  130. source.AuthorityMenu,
  131. source.Authority,
  132. source.AuthoritiesMenus,
  133. source.Casbin,
  134. source.DataAuthorities,
  135. source.Dictionary,
  136. source.DictionaryDetail,
  137. source.File,
  138. source.BaseMenu,
  139. source.UserAuthority,
  140. )
  141. if err != nil {
  142. global.GVA_DB = nil
  143. return err
  144. }
  145. if err = initDBService.writeConfig(global.GVA_VP, MysqlConfig); err != nil {
  146. return err
  147. }
  148. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  149. return nil
  150. }