51 lines
1.3 KiB
Go
51 lines
1.3 KiB
Go
|
package initialize
|
||
|
|
||
|
import (
|
||
|
"gorm.io/driver/postgres"
|
||
|
"gorm.io/gorm"
|
||
|
"miniapp/config"
|
||
|
"miniapp/global"
|
||
|
"miniapp/initialize/internal"
|
||
|
)
|
||
|
|
||
|
// GormPgSql 初始化 Postgresql 数据库
|
||
|
// Author [piexlmax](https://github.com/piexlmax)
|
||
|
// Author [SliverHorn](https://github.com/SliverHorn)
|
||
|
func GormPgSql() *gorm.DB {
|
||
|
p := global.GVA_CONFIG.Pgsql
|
||
|
if p.Dbname == "" {
|
||
|
return nil
|
||
|
}
|
||
|
pgsqlConfig := postgres.Config{
|
||
|
DSN: p.Dsn(), // DSN data source name
|
||
|
PreferSimpleProtocol: false,
|
||
|
}
|
||
|
if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config(p.Prefix, p.Singular)); err != nil {
|
||
|
return nil
|
||
|
} else {
|
||
|
sqlDB, _ := db.DB()
|
||
|
sqlDB.SetMaxIdleConns(p.MaxIdleConns)
|
||
|
sqlDB.SetMaxOpenConns(p.MaxOpenConns)
|
||
|
return db
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// GormPgSqlByConfig 初始化 Postgresql 数据库 通过参数
|
||
|
func GormPgSqlByConfig(p config.Pgsql) *gorm.DB {
|
||
|
if p.Dbname == "" {
|
||
|
return nil
|
||
|
}
|
||
|
pgsqlConfig := postgres.Config{
|
||
|
DSN: p.Dsn(), // DSN data source name
|
||
|
PreferSimpleProtocol: false,
|
||
|
}
|
||
|
if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config(p.Prefix, p.Singular)); err != nil {
|
||
|
panic(err)
|
||
|
} else {
|
||
|
sqlDB, _ := db.DB()
|
||
|
sqlDB.SetMaxIdleConns(p.MaxIdleConns)
|
||
|
sqlDB.SetMaxOpenConns(p.MaxOpenConns)
|
||
|
return db
|
||
|
}
|
||
|
}
|