Add max idle/open params to DB connect

This commit is contained in:
Kailash Nadh 2019-12-05 17:28:22 +05:30
parent 0d8abf9435
commit 6b6dc59067
3 changed files with 25 additions and 9 deletions

View File

@ -68,6 +68,9 @@ password = "listmonk"
database = "listmonk"
ssl_mode = "disable"
# Maximum active and idle connections to pool.
max_open = 50
max_idle = 10
# SMTP servers.
[smtp]

11
main.go
View File

@ -227,12 +227,11 @@ func initMediaStore() media.Store {
func main() {
// Connect to the DB.
db, err := connectDB(ko.String("db.host"),
ko.Int("db.port"),
ko.String("db.user"),
ko.String("db.password"),
ko.String("db.database"),
ko.String("db.ssl_mode"))
var dbCfg dbConf
if err := ko.Unmarshal("db", &dbCfg); err != nil {
log.Fatalf("error loading db config: %v", err)
}
db, err := connectDB(dbCfg)
if err != nil {
logger.Fatalf("error connecting to DB: %v", err)
}

View File

@ -75,14 +75,28 @@ type Queries struct {
// GetStats *sqlx.Stmt `query:"get-stats"`
}
// dbConf contains database config required for connecting to a DB.
type dbConf struct {
Host string `koanf:"host"`
Port int `koanf:"port"`
User string `koanf:"user"`
Password string `koanf:"password"`
DBName string `koanf:"database"`
SSLMode string `koanf:"ssl_mode"`
MaxOpen int `koanf:"max_open"`
MaxIdle int `koanf:"max_idle"`
}
// connectDB initializes a database connection.
func connectDB(host string, port int, user, pwd, dbName string, sslMode string) (*sqlx.DB, error) {
func connectDB(c dbConf) (*sqlx.DB, error) {
db, err := sqlx.Connect("postgres",
fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", host, port, user, pwd, dbName, sslMode))
fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
c.Host, c.Port, c.User, c.Password, c.DBName, c.SSLMode))
if err != nil {
return nil, err
}
db.SetMaxOpenConns(c.MaxOpen)
db.SetMaxIdleConns(c.MaxIdle)
return db, nil
}