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.

165 lines
4.3 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 db.Close()
  40. if err = db.Ping(); err != nil {
  41. return err
  42. }
  43. _, err = db.Exec(createSql)
  44. return err
  45. }
  46. func initDB(InitDBFunctions ...model.InitDBFunc) (err error) {
  47. for _, v := range InitDBFunctions {
  48. err = v.Init()
  49. if err != nil {
  50. return err
  51. }
  52. }
  53. return nil
  54. }
  55. //@author: [songzhibin97](https://github.com/songzhibin97)
  56. //@function: InitDB
  57. //@description: 创建数据库并初始化
  58. //@param: authorityId string
  59. //@return: err error, treeMap map[string][]model.SysMenu
  60. func InitDB(conf request.InitDB) error {
  61. BaseMysql := config.Mysql{
  62. Path: "",
  63. Dbname: "",
  64. Username: "",
  65. Password: "",
  66. Config: "charset=utf8mb4&parseTime=True&loc=Local",
  67. }
  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. fmt.Println(dsn)
  76. createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", conf.DBName)
  77. if err := createTable(dsn, "mysql", createSql); err != nil {
  78. return err
  79. }
  80. MysqlConfig := config.Mysql{
  81. Path: fmt.Sprintf("%s:%s", conf.Host, conf.Port),
  82. Dbname: conf.DBName,
  83. Username: conf.UserName,
  84. Password: conf.Password,
  85. Config: "charset=utf8mb4&parseTime=True&loc=Local",
  86. }
  87. if err := writeConfig(global.GVA_VP, MysqlConfig); err != nil {
  88. return err
  89. }
  90. m := global.GVA_CONFIG.Mysql
  91. if m.Dbname == "" {
  92. return nil
  93. }
  94. linkDns := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
  95. mysqlConfig := mysql.Config{
  96. DSN: linkDns, // DSN data source name
  97. DefaultStringSize: 191, // string 类型字段的默认长度
  98. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  99. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  100. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  101. SkipInitializeWithVersion: false, // 根据版本自动配置
  102. }
  103. if db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}); err != nil {
  104. //global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
  105. //os.Exit(0)
  106. //return nil
  107. return nil
  108. } else {
  109. sqlDB, _ := db.DB()
  110. sqlDB.SetMaxIdleConns(m.MaxIdleConns)
  111. sqlDB.SetMaxOpenConns(m.MaxOpenConns)
  112. global.GVA_DB = db
  113. }
  114. err := global.GVA_DB.AutoMigrate(
  115. model.SysUser{},
  116. model.SysAuthority{},
  117. model.SysApi{},
  118. model.SysBaseMenu{},
  119. model.SysBaseMenuParameter{},
  120. model.JwtBlacklist{},
  121. model.SysDictionary{},
  122. model.SysDictionaryDetail{},
  123. model.ExaFileUploadAndDownload{},
  124. model.ExaFile{},
  125. model.ExaFileChunk{},
  126. model.ExaSimpleUploader{},
  127. model.ExaCustomer{},
  128. model.SysOperationRecord{},
  129. )
  130. if err != nil {
  131. return err
  132. }
  133. err = initDB(
  134. source.Admin,
  135. source.Api,
  136. source.AuthorityMenu,
  137. source.Authority,
  138. source.AuthoritiesMenus,
  139. source.Casbin,
  140. source.DataAuthorities,
  141. source.Dictionary,
  142. source.DictionaryDetail,
  143. source.File,
  144. source.BaseMenu)
  145. if err != nil {
  146. _ = writeConfig(global.GVA_VP, BaseMysql)
  147. return err
  148. }
  149. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  150. return nil
  151. }