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.

171 lines
4.4 KiB

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