From 02ab848efe59d918b98abe1a5b3a9451677a2e05 Mon Sep 17 00:00:00 2001 From: Pavel Shevaev Date: Fri, 28 Oct 2022 12:11:05 +0300 Subject: [PATCH] Passing DB pool settings via config --- db.go | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/db.go b/db.go index c7ef812..c18d6ba 100644 --- a/db.go +++ b/db.go @@ -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} }