feat: 增强 PostgreSQL 配置,添加连接生命周期和日志配置选项

This commit is contained in:
Rogee
2025-09-11 16:26:47 +08:00
parent 55a335e9ad
commit da4875fc16
2 changed files with 105 additions and 12 deletions

65
templates/project/providers/postgres/config.go.tpl Executable file → Normal file
View File

@@ -2,9 +2,12 @@ package postgres
import (
"fmt"
"strconv"
"time"
"go.ipao.vip/atom/container"
"go.ipao.vip/atom/opt"
"gorm.io/gorm/logger"
)
const DefaultPrefix = "Database"
@@ -31,6 +34,42 @@ type Config struct {
Singular bool // true表示开启
MaxIdleConns int //
MaxOpenConns int //
// 0
ConnMaxLifetimeSeconds uint
ConnMaxIdleTimeSeconds uint
// GORM
LogLevel string // silent|error|warn|infoinfo
SlowThresholdMs uint // 200
ParameterizedQueries bool // 便
PrepareStmt bool //
SkipDefaultTransaction bool //
// DSN
UseSearchPath bool // DSN search_path
ApplicationName string // application_name
}
func (m Config) GormSlowThreshold() time.Duration {
if m.SlowThresholdMs == 0 {
return 200 * time.Millisecond // 200ms
}
return time.Duration(m.SlowThresholdMs) * time.Millisecond
}
func (m Config) GormLogLevel() logger.LogLevel {
switch m.LogLevel {
case "silent":
return logger.Silent
case "error":
return logger.Error
case "warn":
return logger.Warn
case "info", "":
return logger.Info
default:
return logger.Info
}
}
func (m *Config) checkDefault() {
@@ -64,16 +103,34 @@ func (m *Config) checkDefault() {
}
func (m *Config) EmptyDsn() string {
// DSN
dsnTpl := "host=%s user=%s password=%s port=%d dbname=%s sslmode=%s TimeZone=%s"
m.checkDefault()
return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Port, m.Database, m.SslMode, m.TimeZone)
base := fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Port, m.Database, m.SslMode, m.TimeZone)
//
extras := ""
if m.UseSearchPath && m.Schema != "" {
extras += " search_path=" + m.Schema
}
if m.ApplicationName != "" {
extras += " application_name=" + strconv.Quote(m.ApplicationName)
}
return base + extras
}
// DSN connection dsn
func (m *Config) DSN() string {
// DSN
dsnTpl := "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s"
m.checkDefault()
return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Database, m.Port, m.SslMode, m.TimeZone)
base := fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Database, m.Port, m.SslMode, m.TimeZone)
//
extras := ""
if m.UseSearchPath && m.Schema != "" {
extras += " search_path=" + m.Schema
}
if m.ApplicationName != "" {
extras += " application_name=" + strconv.Quote(m.ApplicationName)
}
return base + extras
}