153 lines
4.6 KiB
Go
153 lines
4.6 KiB
Go
// Package postgres centralizes PostgreSQL pool creation and the small pieces
|
|||
|
|
// of error/transaction handling that are repeated by the Go services.
|
||
|
|
package postgres
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"strings"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/jackc/pgx/v5"
|
||
|
|
"github.com/jackc/pgx/v5/pgconn"
|
||
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
||
|
|
|
||
|
|
"repos.gfranz.ch/Gabriel20xx/SharedCode/backend/config"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Config controls a shared pgx connection pool. URL is normally read from
|
||
|
|
// DATABASE_URL with FromEnv.
|
||
|
|
type Config struct {
|
||
|
|
URL string
|
||
|
|
MaxConns int32
|
||
|
|
MinConns int32
|
||
|
|
MaxConnLifetime time.Duration
|
||
|
|
MaxConnIdleTime time.Duration
|
||
|
|
HealthCheckPeriod time.Duration
|
||
|
|
ConnectTimeout time.Duration
|
||
|
|
}
|
||
|
|
|
||
|
|
// DefaultConfig returns sensible defaults for a small self-hosted service.
|
||
|
|
func DefaultConfig(url string) Config {
|
||
|
|
return Config{
|
||
|
|
URL: strings.TrimSpace(url),
|
||
|
|
MaxConns: 20,
|
||
|
|
MinConns: 0,
|
||
|
|
MaxConnLifetime: time.Hour,
|
||
|
|
MaxConnIdleTime: 30 * time.Minute,
|
||
|
|
HealthCheckPeriod: 30 * time.Second,
|
||
|
|
ConnectTimeout: 10 * time.Second,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// FromEnv loads DATABASE_URL and optional pool settings. Duration values use
|
||
|
|
// Go duration syntax, for example 30s or 1h. Invalid optional values fall back
|
||
|
|
// to defaults; the URL is the only required setting.
|
||
|
|
func FromEnv() (Config, error) {
|
||
|
|
url, err := config.Required("DATABASE_URL")
|
||
|
|
if err != nil {
|
||
|
|
return Config{}, err
|
||
|
|
}
|
||
|
|
|
||
|
|
cfg := DefaultConfig(url)
|
||
|
|
cfg.MaxConns = int32(config.Int("DATABASE_MAX_CONNS", int(cfg.MaxConns)))
|
||
|
|
cfg.MinConns = int32(config.Int("DATABASE_MIN_CONNS", int(cfg.MinConns)))
|
||
|
|
cfg.MaxConnLifetime = config.Duration("DATABASE_MAX_CONN_LIFETIME", cfg.MaxConnLifetime)
|
||
|
|
cfg.MaxConnIdleTime = config.Duration("DATABASE_MAX_CONN_IDLE_TIME", cfg.MaxConnIdleTime)
|
||
|
|
cfg.HealthCheckPeriod = config.Duration("DATABASE_HEALTH_CHECK_PERIOD", cfg.HealthCheckPeriod)
|
||
|
|
cfg.ConnectTimeout = config.Duration("DATABASE_CONNECT_TIMEOUT", cfg.ConnectTimeout)
|
||
|
|
|
||
|
|
if cfg.MaxConns < 1 {
|
||
|
|
return Config{}, fmt.Errorf("DATABASE_MAX_CONNS must be at least 1")
|
||
|
|
}
|
||
|
|
if cfg.MinConns < 0 || cfg.MinConns > cfg.MaxConns {
|
||
|
|
return Config{}, fmt.Errorf("DATABASE_MIN_CONNS must be between 0 and DATABASE_MAX_CONNS")
|
||
|
|
}
|
||
|
|
if cfg.ConnectTimeout <= 0 {
|
||
|
|
return Config{}, fmt.Errorf("DATABASE_CONNECT_TIMEOUT must be greater than 0")
|
||
|
|
}
|
||
|
|
return cfg, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// Open creates and verifies a PostgreSQL pool. A failed ping closes the pool
|
||
|
|
// before returning so callers do not leak connections during startup errors.
|
||
|
|
func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||
|
|
if strings.TrimSpace(cfg.URL) == "" {
|
||
|
|
return nil, errors.New("postgres URL is required")
|
||
|
|
}
|
||
|
|
|
||
|
|
poolConfig, err := pgxpool.ParseConfig(cfg.URL)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("parse postgres URL: %w", err)
|
||
|
|
}
|
||
|
|
if cfg.MaxConns > 0 {
|
||
|
|
poolConfig.MaxConns = cfg.MaxConns
|
||
|
|
}
|
||
|
|
if cfg.MinConns >= 0 {
|
||
|
|
poolConfig.MinConns = cfg.MinConns
|
||
|
|
}
|
||
|
|
if cfg.MaxConnLifetime > 0 {
|
||
|
|
poolConfig.MaxConnLifetime = cfg.MaxConnLifetime
|
||
|
|
}
|
||
|
|
if cfg.MaxConnIdleTime > 0 {
|
||
|
|
poolConfig.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||
|
|
}
|
||
|
|
if cfg.HealthCheckPeriod > 0 {
|
||
|
|
poolConfig.HealthCheckPeriod = cfg.HealthCheckPeriod
|
||
|
|
}
|
||
|
|
if cfg.ConnectTimeout > 0 {
|
||
|
|
poolConfig.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||
|
|
}
|
||
|
|
|
||
|
|
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("create postgres pool: %w", err)
|
||
|
|
}
|
||
|
|
if err := pool.Ping(ctx); err != nil {
|
||
|
|
pool.Close()
|
||
|
|
return nil, fmt.Errorf("ping postgres: %w", err)
|
||
|
|
}
|
||
|
|
return pool, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// WithTx runs fn in a transaction and rolls back on all error paths.
|
||
|
|
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
|
||
|
|
if pool == nil {
|
||
|
|
return errors.New("postgres pool is nil")
|
||
|
|
}
|
||
|
|
if fn == nil {
|
||
|
|
return errors.New("postgres transaction callback is nil")
|
||
|
|
}
|
||
|
|
|
||
|
|
tx, err := pool.Begin(ctx)
|
||
|
|
if err != nil {
|
||
|
|
return fmt.Errorf("begin postgres transaction: %w", err)
|
||
|
|
}
|
||
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
||
|
|
|
||
|
|
if err := fn(tx); err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
if err := tx.Commit(ctx); err != nil {
|
||
|
|
return fmt.Errorf("commit postgres transaction: %w", err)
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// IsNoRows reports whether err is pgx's not-found sentinel.
|
||
|
|
func IsNoRows(err error) bool {
|
||
|
|
return errors.Is(err, pgx.ErrNoRows)
|
||
|
|
}
|
||
|
|
|
||
|
|
// IsUniqueViolation reports a PostgreSQL unique/exclusion constraint error.
|
||
|
|
func IsUniqueViolation(err error) bool {
|
||
|
|
var pgErr *pgconn.PgError
|
||
|
|
return errors.As(err, &pgErr) && (pgErr.Code == "23505" || pgErr.Code == "23P01")
|
||
|
|
}
|
||
|
|
|
||
|
|
// IsForeignKeyViolation reports a PostgreSQL foreign-key constraint error.
|
||
|
|
func IsForeignKeyViolation(err error) bool {
|
||
|
|
var pgErr *pgconn.PgError
|
||
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||
|
|
}
|