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.

89 lines
2.6 KiB

  1. package initialize
  2. import (
  3. "gin-vue-admin/global"
  4. "gin-vue-admin/model"
  5. "go.uber.org/zap"
  6. "gorm.io/driver/mysql"
  7. "gorm.io/gorm"
  8. "gorm.io/gorm/logger"
  9. "os"
  10. )
  11. // Gorm 初始化数据库并产生数据库全局变量
  12. func Gorm() *gorm.DB {
  13. switch global.GVA_CONFIG.System.DbType {
  14. case "mysql":
  15. return GormMysql()
  16. default:
  17. return GormMysql()
  18. }
  19. }
  20. // MysqlTables 注册数据库表专用
  21. func MysqlTables(db *gorm.DB) {
  22. err := db.AutoMigrate(
  23. model.SysUser{},
  24. model.SysAuthority{},
  25. model.SysApi{},
  26. model.SysBaseMenu{},
  27. model.SysBaseMenuParameter{},
  28. model.JwtBlacklist{},
  29. model.SysDictionary{},
  30. model.SysDictionaryDetail{},
  31. model.ExaFileUploadAndDownload{},
  32. model.ExaFile{},
  33. model.ExaFileChunk{},
  34. model.ExaSimpleUploader{},
  35. model.ExaCustomer{},
  36. model.SysOperationRecord{},
  37. model.WorkflowProcess{},
  38. model.WorkflowNode{},
  39. model.WorkflowEdge{},
  40. model.WorkflowPoint{},
  41. )
  42. if err != nil {
  43. global.GVA_LOG.Error("register table failed", zap.Any("err", err))
  44. os.Exit(0)
  45. }
  46. global.GVA_LOG.Info("register table success")
  47. }
  48. // GormMysql 初始化Mysql数据库
  49. func GormMysql() *gorm.DB {
  50. m := global.GVA_CONFIG.Mysql
  51. dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
  52. mysqlConfig := mysql.Config{
  53. DSN: dsn, // DSN data source name
  54. DefaultStringSize: 191, // string 类型字段的默认长度
  55. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  56. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  57. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  58. SkipInitializeWithVersion: false, // 根据版本自动配置
  59. }
  60. if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig(m.LogMode)); err != nil {
  61. global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
  62. os.Exit(0)
  63. return nil
  64. } else {
  65. sqlDB, _ := db.DB()
  66. sqlDB.SetMaxIdleConns(m.MaxIdleConns)
  67. sqlDB.SetMaxOpenConns(m.MaxOpenConns)
  68. return db
  69. }
  70. }
  71. // gormConfig 根据配置决定是否开启日志
  72. func gormConfig(mod bool) *gorm.Config {
  73. if mod {
  74. return &gorm.Config{
  75. Logger: logger.Default.LogMode(logger.Info),
  76. DisableForeignKeyConstraintWhenMigrating: true,
  77. }
  78. } else {
  79. return &gorm.Config{
  80. Logger: logger.Default.LogMode(logger.Silent),
  81. DisableForeignKeyConstraintWhenMigrating: true,
  82. }
  83. }
  84. }