From ffda7978cfd07611ad2c57bcafeabe498c17f34d Mon Sep 17 00:00:00 2001 From: Blizzard Date: Sat, 26 Apr 2025 00:00:59 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20postgresql=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- initialize/gorm_pgsql.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 initialize/gorm_pgsql.go diff --git a/initialize/gorm_pgsql.go b/initialize/gorm_pgsql.go new file mode 100644 index 0000000..809735d --- /dev/null +++ b/initialize/gorm_pgsql.go @@ -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 + } +}