Files
lincodex/backend/internal/adapter/secondary/postgres/pool.go
T

43 lines
1.5 KiB
Go

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 := 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.NewPool - DATABASE_URL is not a valid PostgreSQL connection string")
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("postgres.NewPool - create PostgreSQL pool: %w", err)
}
return pool, 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")
}