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.

161 lines
4.1 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. "path/filepath"
  12. "github.com/spf13/viper"
  13. "gorm.io/driver/mysql"
  14. "gorm.io/gorm"
  15. )
  16. //@author: [songzhibin97](https://github.com/songzhibin97)
  17. //@function: writeConfig
  18. //@description: 回写配置
  19. //@param: viper *viper.Viper, mysql config.Mysql
  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: conf request.InitDB
  63. //@return: error
  64. func InitDB(conf request.InitDB) error {
  65. if conf.Host == "" {
  66. conf.Host = "127.0.0.1"
  67. }
  68. if conf.Port == "" {
  69. conf.Port = "3306"
  70. }
  71. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", conf.UserName, conf.Password, conf.Host, conf.Port)
  72. createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", conf.DBName)
  73. if err := createTable(dsn, "mysql", createSql); err != nil {
  74. return err
  75. }
  76. MysqlConfig := config.Mysql{
  77. Path: fmt.Sprintf("%s:%s", conf.Host, conf.Port),
  78. Dbname: conf.DBName,
  79. Username: conf.UserName,
  80. Password: conf.Password,
  81. Config: "charset=utf8mb4&parseTime=True&loc=Local",
  82. }
  83. if MysqlConfig.Dbname == "" {
  84. return nil
  85. }
  86. linkDns := MysqlConfig.Username + ":" + MysqlConfig.Password + "@tcp(" + MysqlConfig.Path + ")/" + MysqlConfig.Dbname + "?" + MysqlConfig.Config
  87. mysqlConfig := mysql.Config{
  88. DSN: linkDns, // DSN data source name
  89. DefaultStringSize: 191, // string 类型字段的默认长度
  90. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  91. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  92. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  93. SkipInitializeWithVersion: false, // 根据版本自动配置
  94. }
  95. if db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}); err != nil {
  96. return nil
  97. } else {
  98. sqlDB, _ := db.DB()
  99. sqlDB.SetMaxIdleConns(MysqlConfig.MaxIdleConns)
  100. sqlDB.SetMaxOpenConns(MysqlConfig.MaxOpenConns)
  101. global.GVA_DB = db
  102. }
  103. err := global.GVA_DB.AutoMigrate(
  104. model.SysUser{},
  105. model.SysAuthority{},
  106. model.SysApi{},
  107. model.SysBaseMenu{},
  108. model.SysBaseMenuParameter{},
  109. model.JwtBlacklist{},
  110. model.SysDictionary{},
  111. model.SysDictionaryDetail{},
  112. model.ExaFileUploadAndDownload{},
  113. model.ExaFile{},
  114. model.ExaFileChunk{},
  115. model.ExaSimpleUploader{},
  116. model.ExaCustomer{},
  117. model.SysOperationRecord{},
  118. model.SysAutoCodeHistory{},
  119. )
  120. if err != nil {
  121. global.GVA_DB = nil
  122. return err
  123. }
  124. err = initDB(
  125. source.Admin,
  126. source.Api,
  127. source.AuthorityMenu,
  128. source.Authority,
  129. source.AuthoritiesMenus,
  130. source.Casbin,
  131. source.DataAuthorities,
  132. source.Dictionary,
  133. source.DictionaryDetail,
  134. source.File,
  135. source.BaseMenu)
  136. if err != nil {
  137. global.GVA_DB = nil
  138. return err
  139. }
  140. if err = writeConfig(global.GVA_VP, MysqlConfig); err != nil {
  141. return err
  142. }
  143. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  144. return nil
  145. }