gorm_pgsql.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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/postgres"
  7. "gorm.io/gorm"
  8. )
  9. // GormPgSql 初始化 Postgresql 数据库
  10. // Author [piexlmax](https://github.com/piexlmax)
  11. // Author [SliverHorn](https://github.com/SliverHorn)
  12. func GormPgSql() *gorm.DB {
  13. p := global.GVA_CONFIG.Pgsql
  14. return initPgSqlDatabase(p)
  15. }
  16. // GormPgSqlByConfig 初始化 Postgresql 数据库 通过指定参数
  17. func GormPgSqlByConfig(p config.Pgsql) *gorm.DB {
  18. return initPgSqlDatabase(p)
  19. }
  20. // initPgSqlDatabase 初始化 Postgresql 数据库的辅助函数
  21. func initPgSqlDatabase(p config.Pgsql) *gorm.DB {
  22. if p.Dbname == "" {
  23. return nil
  24. }
  25. pgsqlConfig := postgres.Config{
  26. DSN: p.Dsn(), // DSN data source name
  27. PreferSimpleProtocol: false,
  28. }
  29. // 数据库配置
  30. general := p.GeneralDB
  31. if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config(general)); err != nil {
  32. panic(err)
  33. } else {
  34. sqlDB, _ := db.DB()
  35. sqlDB.SetMaxIdleConns(p.MaxIdleConns)
  36. sqlDB.SetMaxOpenConns(p.MaxOpenConns)
  37. return db
  38. }
  39. }