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