From 2eb91eb20ca523a280fe04507b845047cc7eb8de Mon Sep 17 00:00:00 2001 From: Richard Bertozzo Date: Tue, 17 Sep 2024 10:58:48 -0300 Subject: [PATCH] add config function opts to db pool --- infra/database/postgres.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/infra/database/postgres.go b/infra/database/postgres.go index 040e6b2..ba6227e 100644 --- a/infra/database/postgres.go +++ b/infra/database/postgres.go @@ -8,10 +8,25 @@ import ( "github.com/jackc/pgx/v5/pgxpool" ) +type OptFunc func(*pgxpool.Config) + +func WithMaxConn(maxConn int32) OptFunc { + return func(cfg *pgxpool.Config) { + cfg.MaxConns = maxConn + } +} + +func WithMinConn(minConn int32) OptFunc { + return func(cfg *pgxpool.Config) { + cfg.MinConns = minConn + } +} + // NewConnection creates a new pooled connection for pgx func NewConnection( ctx context.Context, url string, + opts ...OptFunc, ) ( *pgxpool.Pool, error, @@ -22,12 +37,16 @@ func NewConnection( return nil, fmt.Errorf("unable to parse connection string") } - // pool settings + // pool settings defaults cfg.MaxConns = 10 cfg.MinConns = 5 cfg.MaxConnLifetime = time.Minute * 10 cfg.MaxConnIdleTime = time.Minute * 5 + for _, fn := range opts { + fn(cfg) + } + // connect pool, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil {