init
This commit is contained in:
54
database/sql/postgresql.go
Normal file
54
database/sql/postgresql.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package sql
|
||||
|
||||
import (
|
||||
"git.apinb.com/bsm-sdk/core/types"
|
||||
"git.apinb.com/bsm-sdk/core/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,
|
||||
}
|
||||
}
|
||||
|
||||
gormDb, err := gorm.Open(postgres.New(postgres.Config{
|
||||
DSN: dsn,
|
||||
// PreferSimpleProtocol: true, disables implicit prepared statement usage
|
||||
|
||||
}), &gorm.Config{
|
||||
//Logger:newLogger,
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user