package postgres import ( "context" "errors" "fmt" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" ) // NewPool creates a connection pool without opening a connection; the pool // connects lazily on first use, so constructing it never waits for the // database. Startup migrations, not the pool, decide whether the service // requires the database before serving. The caller owns the pool and must // close it. func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { poolConfig, err := parsePoolConfig(databaseURL) if err != nil { return nil, err } pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { return nil, fmt.Errorf("postgres.NewPool - create PostgreSQL pool: %w", err) } return pool, nil } // NewSizedPool is NewPool with at most maxConns connections, for a component // whose concurrency is known, so it cannot take connections that request // handling needs. func NewSizedPool(ctx context.Context, databaseURL string, maxConns int32) (*pgxpool.Pool, error) { if maxConns < 1 { return nil, errors.New("postgres.NewSizedPool - maxConns must be positive") } poolConfig, err := parsePoolConfig(databaseURL) if err != nil { return nil, err } poolConfig.MaxConns = maxConns pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { return nil, fmt.Errorf("postgres.NewSizedPool - create PostgreSQL pool: %w", err) } return pool, nil } func parsePoolConfig(databaseURL string) (*pgxpool.Config, error) { poolConfig, err := pgxpool.ParseConfig(databaseURL) if err != nil { // pgx redacts passwords only on a best-effort basis, so the parse error // is not wrapped to keep the connection string out of logs. return nil, errors.New("postgres.parsePoolConfig - DATABASE_URL is not a valid PostgreSQL connection string") } return poolConfig, nil } // sanitizeConnectError drops the pgx connection prefix, which names the // database user and database, while keeping the network or server cause. func sanitizeConnectError(err error) error { var connectError *pgconn.ConnectError if !errors.As(err, &connectError) { return err } if cause := connectError.Unwrap(); cause != nil { return fmt.Errorf("postgres.sanitizeConnectError - connect to PostgreSQL: %w", cause) } return errors.New("postgres.sanitizeConnectError - connect to PostgreSQL failed") }