gorm_mysql.go 1.6 KB

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