112 lines
3.0 KiB
Go
112 lines
3.0 KiB
Go
// common/db/options.go
|
||
package db
|
||
|
||
import (
|
||
"time"
|
||
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
// PostgresOptions PostgreSQL连接配置项
|
||
// 包含基础连接信息+连接池配置,按需暴露,无冗余
|
||
type PostgresOptions struct {
|
||
Host string // 数据库地址
|
||
Port string // 数据库端口
|
||
User string // 数据库账号
|
||
Password string // 数据库密码
|
||
DBName string // 数据库名
|
||
SSLMode string // SSL模式(开发环境一般disable,生产可enable)
|
||
TimeZone string // 时区(如Asia/Shanghai)
|
||
// 连接池配置
|
||
MaxOpenConns int // 最大打开连接数
|
||
MaxIdleConns int // 最大空闲连接数
|
||
ConnMaxLifetime time.Duration // 连接最大生命周期
|
||
ConnMaxIdleTime time.Duration // 连接最大空闲时间
|
||
// GORM配置
|
||
LogLevel gorm.LogLevel // GORM日志级别(开发:Info,生产:Error)
|
||
}
|
||
|
||
// PostgresOption 选项模式函数类型
|
||
type PostgresOption func(*PostgresOptions)
|
||
|
||
// 初始化默认配置,避免用户传参不全导致连接失败
|
||
// 开发环境常用默认值,生产环境通过业务层传参覆盖
|
||
func defaultPostgresOptions() *PostgresOptions {
|
||
return &PostgresOptions{
|
||
Host: "postgres", // 默认匹配根目录Compose的服务名,开发环境直接用
|
||
Port: "5432",
|
||
SSLMode: "disable",
|
||
TimeZone: "Asia/Shanghai",
|
||
MaxOpenConns: 20,
|
||
MaxIdleConns: 10,
|
||
ConnMaxLifetime: 30 * time.Minute,
|
||
ConnMaxIdleTime: 10 * time.Minute,
|
||
LogLevel: gorm.LogLevelInfo, // 开发环境默认打印Info日志
|
||
}
|
||
}
|
||
|
||
// 以下为配置项的设置函数,用户可通过链式调用配置
|
||
// 示例:db.WithHost("192.168.1.100").WithUser("prod_user")
|
||
|
||
// WithHost 设置数据库地址
|
||
func WithHost(host string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.Host = host
|
||
}
|
||
}
|
||
|
||
// WithPort 设置数据库端口
|
||
func WithPort(port string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.Port = port
|
||
}
|
||
}
|
||
|
||
// WithUser 设置数据库账号
|
||
func WithUser(user string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.User = user
|
||
}
|
||
}
|
||
|
||
// WithPassword 设置数据库密码
|
||
func WithPassword(pwd string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.Password = pwd
|
||
}
|
||
}
|
||
|
||
// WithDBName 设置数据库名
|
||
func WithDBName(dbName string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.DBName = dbName
|
||
}
|
||
}
|
||
|
||
// WithSSLMode 设置SSL模式
|
||
func WithSSLMode(mode string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.SSLMode = mode
|
||
}
|
||
}
|
||
|
||
// WithTimeZone 设置时区
|
||
func WithTimeZone(tz string) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.TimeZone = tz
|
||
}
|
||
}
|
||
|
||
// WithMaxOpenConns 设置最大打开连接数
|
||
func WithMaxOpenConns(num int) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.MaxOpenConns = num
|
||
}
|
||
}
|
||
|
||
// WithLogLevel 设置GORM日志级别
|
||
func WithLogLevel(level gorm.LogLevel) PostgresOption {
|
||
return func(o *PostgresOptions) {
|
||
o.LogLevel = level
|
||
}
|
||
} |