sys_initdb.go 4.2 KB

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