fix(database): 数据库连接 - 消费 libpq keepalive 参数并默认限制闲置事务 (#737)

pgx 不识别 DSN 中 libpq 的 keepalives* 参数,会作为服务端运行参数发送导致连接被拒;改为在建连前消费并应用到 TCP 拨号器。
未显式配置时为每条连接默认设置 idle_in_transaction_session_timeout=5min,避免卡住的事务长期持锁;DSN 显式配置时以 DSN 为准。
建连钩子先复制共享的 RuntimeParams,避免多条连接之间累积修改。

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Catlaxy AI
2026-10-11 22:04:27 +08:00
committed by GitHub
parent 28f2362e3e
commit 6dedc5973c
5 changed files with 334 additions and 2 deletions

View File

@@ -8,6 +8,7 @@ import (
"yingce/backend/internal/logging"
"github.com/jackc/pgx/v5/stdlib"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
@@ -39,7 +40,10 @@ func Open(config Config) (*gorm.DB, error) {
if dsn == "" {
return nil, errors.New("PostgreSQL 模式必须配置 DATABASE_URL")
}
return gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logging.GormLogger()})
return gorm.Open(postgres.New(postgres.Config{
DSN: dsn,
OptionOpenDB: []stdlib.OptionOpenDB{stdlib.OptionBeforeConnect(configurePostgresConnection)},
}), &gorm.Config{Logger: logging.GormLogger()})
default:
return nil, fmt.Errorf("不支持的数据库驱动:%s", driver)
}