feat: postgresql数据库连接策略
This commit is contained in:
@@ -0,0 +1,40 @@
|
|||||||
|
package initialize
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"sundynix-go/config"
|
||||||
|
"sundynix-go/global"
|
||||||
|
"sundynix-go/initialize/internal"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GromPgsql 初始化 Postgresql 数据库
|
||||||
|
func GromPgsql() *gorm.DB {
|
||||||
|
p := global.Config.Pgsql
|
||||||
|
return initPgsqlDatabase(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GormPgsqlByConfig 根据配置文件初始化 Postgresql 数据库
|
||||||
|
func GormPgsqlByConfig(p config.Pgsql) *gorm.DB {
|
||||||
|
return initPgsqlDatabase(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// initPgsqlDatabase 初始化 Postgresql 数据库的辅助函数
|
||||||
|
func initPgsqlDatabase(p config.Pgsql) *gorm.DB {
|
||||||
|
if p.Dbname == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
pgsqlConfig := postgres.Config{
|
||||||
|
DSN: p.Dsn(), // DSN 数据库连接串
|
||||||
|
PreferSimpleProtocol: false, // 禁用隐式 prepared statement
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
global.Logger.Info("postgresql connect success")
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user