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.

52 lines
1.5 KiB

  1. package initialize
  2. import (
  3. "github.com/flipped-aurora/gin-vue-admin/server/config"
  4. "github.com/flipped-aurora/gin-vue-admin/server/global"
  5. "github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
  6. "gorm.io/driver/mysql"
  7. "gorm.io/gorm"
  8. )
  9. // GormMysql 初始化Mysql数据库
  10. // Author [piexlmax](https://github.com/piexlmax)
  11. // Author [SliverHorn](https://github.com/SliverHorn)
  12. func GormMysql() *gorm.DB {
  13. m := global.GVA_CONFIG.Mysql
  14. if m.Dbname == "" {
  15. return nil
  16. }
  17. mysqlConfig := mysql.Config{
  18. DSN: m.Dsn(), // DSN data source name
  19. DefaultStringSize: 191, // string 类型字段的默认长度
  20. SkipInitializeWithVersion: false, // 根据版本自动配置
  21. }
  22. if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config()); err != nil {
  23. return nil
  24. } else {
  25. sqlDB, _ := db.DB()
  26. sqlDB.SetMaxIdleConns(m.MaxIdleConns)
  27. sqlDB.SetMaxOpenConns(m.MaxOpenConns)
  28. return db
  29. }
  30. }
  31. // GormMysqlByConfig 初始化Mysql数据库用过传入配置
  32. func GormMysqlByConfig(m config.DB) *gorm.DB {
  33. if m.Dbname == "" {
  34. return nil
  35. }
  36. mysqlConfig := mysql.Config{
  37. DSN: m.Dsn(), // DSN data source name
  38. DefaultStringSize: 191, // string 类型字段的默认长度
  39. SkipInitializeWithVersion: false, // 根据版本自动配置
  40. }
  41. if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config()); err != nil {
  42. panic(err)
  43. } else {
  44. sqlDB, _ := db.DB()
  45. sqlDB.SetMaxIdleConns(m.MaxIdleConns)
  46. sqlDB.SetMaxOpenConns(m.MaxOpenConns)
  47. return db
  48. }
  49. }