Skip to content

Commit

Permalink
add config function opts to db pool
Browse files Browse the repository at this point in the history
  • Loading branch information
richardbertozzo committed Sep 17, 2024
1 parent 686a632 commit 2eb91eb
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion infra/database/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down

0 comments on commit 2eb91eb

Please sign in to comment.