35 lines
724 B
Go
35 lines
724 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
|
}
|
|
|
|
// Defaults razoáveis para um serviço pequeno/médio.
|
|
cfg.MaxConns = 10
|
|
cfg.MinConns = 0
|
|
cfg.MaxConnLifetime = 60 * time.Minute
|
|
cfg.MaxConnIdleTime = 10 * time.Minute
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := pool.Ping(ctxPing); err != nil {
|
|
pool.Close()
|
|
return nil, err
|
|
}
|
|
return pool, nil
|
|
}
|