You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dorm/gorm_postgres.go

93 lines
2.2 KiB

5 months ago
package dorm
import (
"context"
"errors"
"fmt"
"go.dtapp.net/gotime"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
2 months ago
// NewGormPostgresClient 创建GormClient实例 postgres
5 months ago
func NewGormPostgresClient(ctx context.Context, config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{}
c.config = config
// 判断路径
if c.config.LogPath == "" {
2 months ago
logsURL = "/logs/postgresql"
5 months ago
} else {
2 months ago
logsURL = c.config.LogPath
5 months ago
}
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
}
c.db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
return gotime.Current().Now().Local()
},
})
} else {
c.db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
}
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
3 months ago
c.sqlDd, err = c.db.DB()
5 months ago
if err != nil {
3 months ago
return nil, errors.New(fmt.Sprintf("获取通用数据库对象失败:%v", err))
5 months ago
}
// 设置空闲连接池中连接的最大数量
if c.config.ConnSetMaxIdle == 0 {
3 months ago
c.sqlDd.SetMaxIdleConns(10)
5 months ago
} else {
3 months ago
c.sqlDd.SetMaxIdleConns(c.config.ConnSetMaxIdle)
5 months ago
}
// 设置打开数据库连接的最大数量
if c.config.ConnSetMaxOpen == 0 {
3 months ago
c.sqlDd.SetMaxOpenConns(100)
5 months ago
} else {
3 months ago
c.sqlDd.SetMaxOpenConns(c.config.ConnSetMaxOpen)
5 months ago
}
// 设置了连接可复用的最大时间
if c.config.ConnSetConnMaxLifetime == 0 {
3 months ago
c.sqlDd.SetConnMaxLifetime(time.Hour)
5 months ago
} else {
3 months ago
c.sqlDd.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
5 months ago
}
return c, nil
}