Passing DB pool settings via config

This commit is contained in:
Pavel Shevaev 2022-10-28 12:11:05 +03:00
parent d6d473e848
commit 02ab848efe
1 changed files with 18 additions and 5 deletions

23
db.go
View File

@ -3,6 +3,7 @@ package db
import (
"database/sql"
"reflect"
"time"
"git.bit5.ru/backend/colog"
"git.bit5.ru/backend/dbr"
@ -15,6 +16,8 @@ type Settings struct {
Driver string
LogLevel int
Weight uint32
MaxIdleConns, MaxOpenConns int
ConnMaxLifetimeSec, ConnMaxIdleTimeSec int
}
func (s *Settings) ConnStr() string {
@ -49,11 +52,21 @@ func OpenPool(s Settings) *Pool {
//NOTE: sql.Open(..) doesn't happen to return an error
sqlDb, _ := sql.Open(driver, s.ConnStr())
//TODO: take values from Settings
sqlDb.SetMaxIdleConns(100)
sqlDb.SetMaxOpenConns(0)
sqlDb.SetConnMaxLifetime(0)
sqlDb.SetConnMaxIdleTime(0)
if s.MaxIdleConns == 0 {
//NOTE: using default sql.DB settings
sqlDb.SetMaxIdleConns(2)
} else {
sqlDb.SetMaxIdleConns(s.MaxIdleConns)
}
if s.MaxOpenConns != 0 {
sqlDb.SetMaxOpenConns(s.MaxOpenConns)
}
if s.ConnMaxLifetimeSec != 0 {
sqlDb.SetConnMaxLifetime(time.Second * time.Duration(s.ConnMaxLifetimeSec))
}
if s.ConnMaxIdleTimeSec != 0 {
sqlDb.SetConnMaxIdleTime(time.Second * time.Duration(s.ConnMaxIdleTimeSec))
}
return &Pool{DB: sqlDb, S: s}
}