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.

92 lines
2.7 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.SysWorkflow{},
  30. model.SysWorkflowStepInfo{},
  31. model.SysDictionary{},
  32. model.SysDictionaryDetail{},
  33. model.ExaFileUploadAndDownload{},
  34. model.ExaFile{},
  35. model.ExaFileChunk{},
  36. model.ExaSimpleUploader{},
  37. model.ExaCustomer{},
  38. model.SysOperationRecord{},
  39. )
  40. if err != nil {
  41. global.GVA_LOG.Error("register table failed", zap.Any("err", err))
  42. os.Exit(0)
  43. }
  44. global.GVA_LOG.Info("register table success")
  45. }
  46. // GormMysql 初始化Mysql数据库
  47. func GormMysql() *gorm.DB {
  48. m := global.GVA_CONFIG.Mysql
  49. dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
  50. mysqlConfig := mysql.Config{
  51. DSN: dsn, // DSN data source name
  52. DefaultStringSize: 191, // string 类型字段的默认长度
  53. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  54. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  55. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  56. SkipInitializeWithVersion: false, // 根据版本自动配置
  57. }
  58. if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig(m.LogMode)); err != nil {
  59. global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
  60. os.Exit(0)
  61. return nil
  62. } else {
  63. sqlDB, _ := db.DB()
  64. sqlDB.SetMaxIdleConns(m.MaxIdleConns)
  65. sqlDB.SetMaxOpenConns(m.MaxOpenConns)
  66. return db
  67. }
  68. }
  69. // gormConfig 根据配置决定是否开启日志
  70. func gormConfig(mod bool) *gorm.Config {
  71. if global.GVA_CONFIG.Mysql.LogZap {
  72. return &gorm.Config{
  73. Logger: Default.LogMode(logger.Info),
  74. DisableForeignKeyConstraintWhenMigrating: true,
  75. }
  76. }
  77. if mod {
  78. return &gorm.Config{
  79. Logger: logger.Default.LogMode(logger.Info),
  80. DisableForeignKeyConstraintWhenMigrating: true,
  81. }
  82. } else {
  83. return &gorm.Config{
  84. Logger: logger.Default.LogMode(logger.Silent),
  85. DisableForeignKeyConstraintWhenMigrating: true,
  86. }
  87. }
  88. }