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.7 KiB

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