2024-02-11 01:31:01 +08:00
|
|
|
package sql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"git.apinb.com/bsm-sdk/engine/types"
|
|
|
|
"git.apinb.com/bsm-sdk/engine/vars"
|
|
|
|
"gorm.io/driver/postgres"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/schema"
|
|
|
|
)
|
|
|
|
|
|
|
|
// new grom db.
|
|
|
|
func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
//set connection default val.
|
|
|
|
if options == nil {
|
|
|
|
options = &types.SqlOptions{
|
|
|
|
MaxIdleConns: vars.SqlOptionMaxIdleConns,
|
|
|
|
MaxOpenConns: vars.SqlOptionMaxIdleConns,
|
|
|
|
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
|
|
|
|
LogStdout: false,
|
|
|
|
Debug: true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//控制台和文件同时输出日志
|
|
|
|
var newLogger = setLogger(vars.ServiceKey, options.LogStdout)
|
|
|
|
|
|
|
|
gormDb, err := gorm.Open(postgres.New(postgres.Config{
|
|
|
|
DSN: dsn,
|
|
|
|
// PreferSimpleProtocol: true, disables implicit prepared statement usage
|
|
|
|
|
|
|
|
}), &gorm.Config{
|
2024-03-22 12:12:17 +08:00
|
|
|
Logger: newLogger,
|
|
|
|
DisableForeignKeyConstraintWhenMigrating: true,
|
2024-02-11 01:31:01 +08:00
|
|
|
NamingStrategy: schema.NamingStrategy{
|
|
|
|
SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user`
|
|
|
|
}})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if options.Debug {
|
|
|
|
gormDb = gormDb.Debug()
|
|
|
|
}
|
|
|
|
|
|
|
|
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
|
|
|
|
sqlDB, _ := gormDb.DB()
|
|
|
|
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
|
|
|
|
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
|
|
|
|
// SetMaxOpenConns 设置打开数据库连接的最大数量。
|
|
|
|
sqlDB.SetMaxOpenConns(options.MaxOpenConns)
|
|
|
|
// SetConnMaxLifetime 设置了连接可复用的最大时间。
|
|
|
|
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
|
|
|
|
|
|
|
|
return gormDb, nil
|
|
|
|
}
|