psql

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

PSQL

Production-Ready PostgreSQL Client with Retries, Health Checks and High-Load Optimizations for Go Services

psql is a lightweight wrapper around github.com/jackc/pgx/v5/pgxpool that provides a clean, configurable and highly reliable PostgreSQL client.
It includes smart connection pooling, automatic retries with jitter, dual health monitoring, centralized error handling and production-grade defaults — everything you need for high-load backends without boilerplate.

It supports:

  • High-performance connection pool with sensible defaults
  • Retry logic with exponential backoff + jitter
  • Dual health checking (generic HealthChecker + Prometheus-style metrics)
  • Centralized PostgreSQL error wrapping and helpers
  • Graceful shutdown
  • Pretty SQL logging
  • Safe DSN builder
  • Configurable query execution mode (PgBouncer-safe)

Perfect for REST APIs, gRPC services, microservices or any backend that needs stable and observable PostgreSQL access.

Features

  • Zero boilerplate configuration with powerful Option pattern
  • Production-optimized defaults (20/0 connections, 1h lifetime with jitter, etc.)
  • Automatic retries on connection failures with jitter
  • Two-level health monitoring (custom interface + metrics)
  • Centralized error wrappers (ErrCommit, ErrDoQuery, etc.)
  • Built-in unique violation detection and error parsing
  • PrettySQL utility for clean query logging
  • Safe DSN construction (proper escaping)
  • Thread-safe and context-aware
  • Full pgxpool.Pool compatibility (embedded)
  • 100% English godoc documentation

Installation

go get github.com/jwm1rr0rb10/go-postgresql

The library depends on:

  • github.com/jackc/pgx/v5
  • github.com/prometheus/client_golang
  • go.opentelemetry.io/otel

After adding the module, run:

go mod tidy

Quick Start

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/jackc/pgx/v5"
	psql "github.com/jwm1rr0rb10/go-postgresql"
)

func main() {
	ctx := context.Background()

	// Create config with options
	cfg, err := psql.NewConfig("postgres://user:pass@localhost:5432/mydb?sslmode=disable",
		psql.WithMaxAttempts(7),
		psql.WithQueryExecMode(pgx.QueryExecModeCacheDescribe), // only behind PgBouncer
		psql.WithConnectionPool(100, 20, 2*time.Hour),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create client
	client, err := psql.NewClient(ctx, cfg)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// You can use client exactly like *pgxpool.Pool
	rows, err := client.Query(ctx, "SELECT id, name FROM users WHERE status = $1", "active")
	// ... your normal pgx code
}
2. Using DSN builder
dsnCfg := &psql.DSNConfig{
	Username: "user",
	Password: "super@secret:pass",
	Host:     "db.example.com",
	Port:     "5432",
	Database: "mydb",
}
dsn := dsnCfg.ToPostgresDSN()

cfg, _ := psql.NewConfig(dsn)
3. Health checking + metrics
// Example with custom health checker
type MyHealth struct{ /* ... */ }
func (h *MyHealth) SetStatus(name string, status bool, details interface{}) { /* ... */ }

cfg, _ := psql.NewConfig(dsn,
	psql.WithHealthChecker("postgres-main", &MyHealth{}),
	psql.WithIntervalCheck(15*time.Second),
	psql.WithFailureThreshold(3), // consecutive failed pings before "unhealthy"
)

The client turns unhealthy after WithFailureThreshold consecutive failed pings (default 3) and recovers on the first success. A ping that times out waiting on a fully busy pool leaves the status unchanged: saturation is not an outage, and reporting it as one would drop replicas from Cluster rotation or fail readiness probes exactly under peak load. Health pings bypass query traces and latency metrics.


Core Concepts

Config + Option pattern

All configuration is done through NewConfig(dsn, options...). You can override retries, pool settings, health checks, query exec mode, etc.

HealthChecker interface
type HealthChecker interface {
	SetStatus(dependencyName string, status bool, details interface{})
}

Used by the library for background health reporting.

Error handling
if pgErr, ok := psql.IsErrUniqueViolation(err); ok {
	// handle unique violation
}

err = psql.ParsePgError(err) // nice formatted error
PrettySQL
clean := psql.PrettySQL(`
    SELECT * FROM users 
    WHERE id = $1
`)

API Overview

Main functions & types
Function / Type Description
"NewConfig(dsn, opts...)" Parse DSN and apply options
"NewClient(ctx, cfg)" Create ready-to-use connection pool
(*Client).Close() Graceful shutdown
WithMaxAttempts Set retry attempts
WithMaxDelay Set maximum backoff delay
WithQueryExecMode pgx query exec mode (CacheDescribe/Exec for PgBouncer)
WithHealthChecker Attach custom health reporter
WithIntervalCheck Set health check interval
WithFailureThreshold Failed pings before reporting unhealthy
WithRegisterer Custom Prometheus registry (nil disables metrics)
WithMaxReplicationLag Lag-aware replica routing in Cluster
WithConnectionPool Configure pool size and lifetime
"ErrCommit, ErrDoQuery..." Error wrappers with context
IsErrUniqueViolation Check for unique violation
ParsePgError PostgreSQL error details; keeps *PgError in the chain
Config.RedactedDSN() DSN with the password masked, safe for logs
PrettySQL Collapse whitespace for logs
DSNConfig.ToPostgresDSN() Safe DSN builder

Client embeds *pgxpool.Pool, so you get all pgx methods + the extra helpers.


Complete Example (REST service)

func initDB() (*psql.Client, error) {
	cfg, err := psql.NewConfig(os.Getenv("DATABASE_URL"),
		psql.WithMaxAttempts(10),
		psql.WithQueryExecMode(pgx.QueryExecModeCacheDescribe), // only behind PgBouncer
		psql.WithHealthChecker("postgres", healthChecker),
		psql.WithIntervalCheck(10*time.Second),
	)
	if err != nil {
		return nil, err
	}

	return psql.NewClient(context.Background(), cfg)
}

// In your handler:
rows, err := db.Query(ctx, "SELECT * FROM orders WHERE user_id = $1", userID)

Testing

Tests use embedded PostgreSQL — no Docker required.

GOTOOLCHAIN=go1.26.2 go test -cover ./...

Coverage includes config options, retry logic, metrics availability, health checks, error wrappers, and client lifecycle.


Production / highload

Pool defaults

max=20, min=0 per instance (no idle connections pinned by every replica of a service), lifetime 1h with 10% jitter so connections are not recycled at once. Precedence: package defaults < pool_* DSN parameters < options.

cfg, _ := psql.NewConfig(dsn,
	psql.WithPoolName("primary"),                 // "pool" label in metrics/traces
	psql.WithConnectionPool(40, 0, time.Hour),
	psql.WithMaxConnIdleTime(5*time.Minute),
	psql.WithStatementTimeout(5*time.Second),     // server-side backstop
	psql.WithApplicationName("kline-service"),    // visible in pg_stat_activity
)
Observability

Built in, no extra setup:

  • postgres_query_duration_seconds{pool,query,status}: label queries with psql.WithQueryName(ctx, "kline.save"), otherwise the SQL verb is used.
  • postgres_pool_*: pgxpool.Stat (acquired/idle conns, empty acquires, acquire wait, destroyed conns). Rising postgres_pool_empty_acquires_total means the pool is too small.
  • OpenTelemetry client spans for queries, batches and COPY via the global TracerProvider. WithTracing(false), WithTraceSQL(false) to tune; WithQueryTracer adds your own pgx tracer.
  • Metrics go to prometheus.DefaultRegisterer; pass psql.WithRegisterer(reg) to use your own registry, or nil to disable them.
Transactions
err := client.WithTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable}, func(tx pgx.Tx) error {
	// must be safe to re-run: retried on 40001 / 40P01 (WithTxMaxAttempts, default 3)
	_, err := tx.Exec(ctx, "UPDATE ...")
	return err
})
Read replicas
cluster, _ := psql.NewCluster(primary, replica1, replica2)
cluster.Replica().Query(ctx, ...) // healthy replica round-robin, falls back to primary
cluster.Primary().Exec(ctx, ...)  // writes and read-your-writes

Create replica clients with psql.WithMaxReplicationLag(5*time.Second) to measure replay lag on every health check: Replica() skips a replica while it lags more than that, and the lag is exported as postgres_replication_lag_seconds. Without the option lag is not tracked.

Testability

Depend on psql.Querier (satisfied by *Client, pgx.Tx, *pgx.Conn) and psql.TxRunner instead of *psql.Client to mock the database.

Benchmarks

go test -run '^$' -bench . ./... (-short skips the embedded-PostgreSQL round-trip benchmark).

Changelog

Unreleased
  • Health monitor: unhealthy only after WithFailureThreshold consecutive failures (default 3); a saturated pool no longer counts as a failure
  • Health pings no longer produce spans and query="other" latency samples
  • Fixed: calling Close twice (e.g. Cluster.Close plus the client) could mark a database still used by another client unavailable
  • OpenTelemetry instrumentation scope renamed to github.com/jwm1rr0rb10/go-postgresql
  • WithRegisterer for a custom Prometheus registry (or nil to disable metrics)
  • WithMaxReplicationLag: lag-aware Cluster.Replica() routing and postgres_replication_lag_seconds
  • DoWithAttempts keeps the last error when the context ends (errors.Is matches both)
  • Dropped the go-errors and go-metrics dependencies (and with them gRPC): stdlib errors and prometheus directly
1.2.0
  • Breaking: pool defaults max=20, min=0 (were 50/10); Config.DSN() replaced by RedactedDSN(); NewClient no longer accepts a nil context
  • OpenTelemetry spans, query latency histogram, pgxpool.Stat metrics
  • WithTx with serialization/deadlock retry, Cluster for read replicas, Querier interface
  • Pool tuning, statement_timeout, application_name, TLS and connection hooks options
  • Fixed: DSN pool_* params ignored, ParsePgError dropped the cause, duplicate health pings
1.1.0
  • Expanded tests: config options, metrics, connection failure paths, all error wrappers
  • Embedded PostgreSQL tests (no Docker required for CI)
  • README install path fixed (postgresql, not psql)
  • Coverage: 94%+
1.0.5
  • Initial production release

License

MIT License – © Raman Zaitsau @jwm1rrr0rb10


🙌 Contributions

PRs and suggestions welcome! Feel free

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNilConfig     = errors.New("postgresql config is nil")
	ErrEmptyDSN      = errors.New("postgresql dsn is empty")
	ErrInvalidConfig = errors.New("postgresql config is invalid")
	ErrNilPrimary    = errors.New("postgresql cluster primary is nil")

	// ErrOperationTimeout and ErrOverloaded are matched with errors.Is on
	// results of ErrTimeout and ErrOverload.
	ErrOperationTimeout = errors.New("db operation timeout")
	ErrOverloaded       = errors.New("db overload")
)

Functions

func DoWithAttempts

func DoWithAttempts(
	ctx context.Context,
	r *rand.Rand,
	fn func() error,
	maxAttempts int,
	maxDelay time.Duration,
) error

DoWithAttempts implements advanced retry logic with exponential backoff and jitter. Returns the last error wrapped so the root cause is not lost.

func ErrCommit

func ErrCommit(err error) error

func ErrCreateQuery

func ErrCreateQuery(err error) error

func ErrCreateTx

func ErrCreateTx(err error) error

func ErrDoQuery

func ErrDoQuery(err error) error

func ErrOverload

func ErrOverload(err error) error

func ErrRollback

func ErrRollback(err error) error

func ErrScan

func ErrScan(err error) error

func ErrTimeout

func ErrTimeout(err error) error

func IsRetryableTxError

func IsRetryableTxError(err error) bool

IsRetryableTxError reports errors after which the whole transaction may be retried as is: serialization failures and deadlocks.

func ParsePgError

func ParsePgError(err error) error

ParsePgError formats details from a PostgreSQL error into the message while keeping the original error in the chain, so errors.As(err, &pgErr) still works. Returns the original error unchanged if it's not a *PgError.

func PrettySQL

func PrettySQL(q string) string

PrettySQL collapses runs of whitespace (spaces, tabs, CR, LF) into a single space for compact logging. Whitespace inside single-quoted string literals and double-quoted identifiers is preserved.

func WithQueryName

func WithQueryName(ctx context.Context, name string) context.Context

WithQueryName labels queries run with ctx in metrics and spans, e.g. "kline.save_batch". Without it the label is the SQL verb ("select", "insert", ...). Use a fixed set of names: every distinct name is a new metric series.

Types

type Client

type Client struct {
	*pgxpool.Pool
	// contains filtered or unexported fields
}

Client represents a thread-safe PostgreSQL connection pool.

func NewClient

func NewClient(ctx context.Context, cfg *Config) (*Client, error)

NewClient creates a new PostgreSQL connection pool with highload optimizations, retry logic and health monitoring.

func (*Client) Close

func (c *Client) Close()

Close gracefully terminates the connection pool and health checks. It is safe to call more than once, e.g. via both Cluster.Close and the client.

func (*Client) Healthy

func (c *Client) Healthy() bool

Healthy reports the client's health as seen by the background monitor (see WithFailureThreshold). It is refreshed every health-check interval and turns false once Close starts.

func (*Client) Name

func (c *Client) Name() string

Name returns the pool name used in metrics and traces (see WithPoolName).

func (*Client) ReplicationLag

func (c *Client) ReplicationLag() time.Duration

ReplicationLag returns the replay lag measured by the last successful health check. It is always 0 unless WithMaxReplicationLag is set.

func (*Client) WithTx

func (c *Client) WithTx(ctx context.Context, opts pgx.TxOptions, fn func(pgx.Tx) error) error

WithTx runs fn in a transaction: it commits when fn returns nil and rolls back on error or panic. Serialization failures and deadlocks (common under RepeatableRead/Serializable and hot rows) restart the whole transaction up to WithTxMaxAttempts times, so fn must be safe to re-run: keep side effects outside the database (HTTP calls, channel sends) out of it.

type Cluster

type Cluster struct {
	// contains filtered or unexported fields
}

Cluster routes work between a primary and read replicas.

Replica() round-robins over healthy replicas and falls back to the primary when none is healthy. A replica leaves rotation after WithFailureThreshold consecutive failed pings, so it can stay in rotation for up to threshold × WithIntervalCheck after it fails. A replica whose pool is merely saturated stays in rotation.

Replicas created with WithMaxReplicationLag also leave rotation while their measured lag exceeds the limit. Without it lag is not tracked, and either way read-your-writes paths must use Primary().

func NewCluster

func NewCluster(primary *Client, replicas ...*Client) (*Cluster, error)

NewCluster groups already connected clients. Give each a distinct WithPoolName ("primary", "replica-1", ...) to tell them apart in metrics.

func (*Cluster) Close

func (c *Cluster) Close()

Close closes all replicas, then the primary.

func (*Cluster) Primary

func (c *Cluster) Primary() *Client

Primary returns the read-write client.

func (*Cluster) Replica

func (c *Cluster) Replica() *Client

Replica returns a healthy replica for read-only queries, or the primary when no replica is configured or healthy.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config holds PostgreSQL client configuration.

func NewConfig

func NewConfig(dsn string, options ...Option) (*Config, error)

NewConfig parses DSN and applies options.

func (*Config) HealthCheckInterval

func (c *Config) HealthCheckInterval() time.Duration

HealthCheckInterval returns the configured background health-check interval.

func (*Config) RedactedDSN

func (c *Config) RedactedDSN() string

RedactedDSN returns the configured connection string with the password masked, safe for logs.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks whether the configuration can be used to create a client.

type DSNConfig

type DSNConfig struct {
	Username string
	Password string
	Host     string
	Port     string
	Database string
}

DSNConfig contains parameters for building PostgreSQL connection string.

func (*DSNConfig) ToPostgresDSN

func (c *DSNConfig) ToPostgresDSN() string

ToPostgresDSN converts DSNConfig to a properly escaped PostgreSQL connection string.

type HealthChecker

type HealthChecker interface {
	// SetStatus updates component status with optional details.
	SetStatus(dependencyName string, status bool, details interface{})
}

HealthChecker defines an interface for dependency health reporting. Implementations must be safe for concurrent use from multiple goroutines.

type Option

type Option func(*Config)

Option configures the PostgreSQL client.

func WithAfterConnect

func WithAfterConnect(fn func(context.Context, *pgx.Conn) error) Option

WithAfterConnect runs fn on every new connection before it joins the pool, e.g. to register custom types. An error discards the connection.

func WithApplicationName

func WithApplicationName(name string) Option

WithApplicationName tags connections in pg_stat_activity and server logs.

func WithBinaryExecMode deprecated

func WithBinaryExecMode(binary bool) Option

WithBinaryExecMode switches to QueryExecModeCacheDescribe when binary is true and does nothing otherwise.

Deprecated: the name is misleading — every cached pgx mode already uses the binary protocol, and CacheDescribe is a PgBouncer-compatibility mode that is usually slower than the pgx default. Use WithQueryExecMode.

func WithConnectionPool

func WithConnectionPool(maxConns, minConns int32, maxLifetime time.Duration) Option

WithConnectionPool configures connection pool parameters.

func WithFailureThreshold

func WithFailureThreshold(n int) Option

WithFailureThreshold sets how many consecutive failed health pings turn the client unhealthy (Healthy, the availability gauge, the HealthChecker and Cluster routing). A single success restores it. Defaults to 3, so an outage is detected within threshold × WithIntervalCheck.

func WithHealthCheckPeriod

func WithHealthCheckPeriod(d time.Duration) Option

WithHealthCheckPeriod sets how often pgx checks idle connections and enforces lifetime/idle limits. pgx defaults to 1 minute.

func WithHealthChecker

func WithHealthChecker(name string, hc HealthChecker) Option

WithHealthChecker configures health monitoring for the database connection.

func WithIntervalCheck

func WithIntervalCheck(interval time.Duration) Option

WithIntervalCheck sets the health check interval for background monitoring.

func WithMaxAttempts

func WithMaxAttempts(attempts int) Option

WithMaxAttempts sets the maximum number of retry attempts for database operations.

func WithMaxConnIdleTime

func WithMaxConnIdleTime(d time.Duration) Option

WithMaxConnIdleTime closes connections idle for longer than d, letting the pool shrink back after a burst. pgx defaults to 30 minutes.

func WithMaxConnLifetimeJitter

func WithMaxConnLifetimeJitter(d time.Duration) Option

WithMaxConnLifetimeJitter spreads connection recycling over [lifetime, lifetime+d) so connections opened together are not all closed at once. Defaults to 10% of the max connection lifetime.

func WithMaxDelay

func WithMaxDelay(delay time.Duration) Option

WithMaxDelay sets the maximum delay between retry attempts.

func WithMaxReplicationLag

func WithMaxReplicationLag(d time.Duration) Option

WithMaxReplicationLag marks the client as a replica whose replay lag is measured on every health check: Cluster.Replica skips it while the lag exceeds d, and the lag is exported as postgres_replication_lag_seconds. A lagging replica stays healthy for the HealthChecker.

Lag is the age of the last replayed transaction while WAL is still being replayed. A replica that lost its connection to the primary but replayed everything it received reports 0: alert on pg_stat_wal_receiver for that.

func WithPoolName

func WithPoolName(name string) Option

WithPoolName names the pool in metrics and traces ("pool" label). Give each client a distinct name when one process talks to several databases or to a primary and its replicas, e.g. "primary", "replica-1".

func WithPrepareConn

func WithPrepareConn(fn func(context.Context, *pgx.Conn) (bool, error)) Option

WithPrepareConn runs fn before a connection is handed out by Acquire. Returning false (or an error) destroys the connection and acquires another.

func WithQueryExecMode

func WithQueryExecMode(mode pgx.QueryExecMode) Option

WithQueryExecMode sets the default pgx query execution mode. pgx defaults to QueryExecModeCacheStatement (prepared statements cached per connection), which is the fastest mode against a direct PostgreSQL connection. Use QueryExecModeCacheDescribe or QueryExecModeExec behind PgBouncer in transaction pooling mode.

func WithQueryTracer

func WithQueryTracer(t pgx.QueryTracer) Option

WithQueryTracer adds a pgx tracer (e.g. tracelog) next to the built-in one.

func WithRegisterer

func WithRegisterer(reg prometheus.Registerer) Option

WithRegisterer registers the client's metrics with reg instead of prometheus.DefaultRegisterer. Clients sharing a registerer share the collectors. A nil reg disables metric registration.

func WithRuntimeParam

func WithRuntimeParam(key, value string) Option

WithRuntimeParam sets a server run-time parameter in the startup message of every new connection. PgBouncer rejects unknown startup parameters unless they are listed in its ignore_startup_parameters.

func WithStatementTimeout

func WithStatementTimeout(d time.Duration) Option

WithStatementTimeout makes the server abort any statement running longer than d. It is the backstop for queries whose context carries no deadline.

func WithTLSConfig

func WithTLSConfig(tlsCfg *tls.Config) Option

WithTLSConfig forces TLS with the given config (e.g. mTLS client certificates). It overrides the DSN sslmode: plaintext fallbacks are dropped and ServerName defaults to each host.

func WithTraceSQL

func WithTraceSQL(enabled bool) Option

WithTraceSQL toggles the db.query.text span attribute. Queries are parameterized so values are not included, but disable it when the SQL text itself is sensitive or very large. Enabled by default.

func WithTracing

func WithTracing(enabled bool) Option

WithTracing toggles OpenTelemetry spans for queries, batches and COPY. Query latency metrics are recorded either way. Enabled by default; spans go to the global TracerProvider and cost nothing until one is installed.

func WithTxMaxAttempts

func WithTxMaxAttempts(n int) Option

WithTxMaxAttempts sets how many times WithTx runs a transaction that fails with a serialization failure or deadlock. Defaults to 3.

type PgError

type PgError = pgconn.PgError

PgError aliases pgconn.PgError to decouple from external library. Used for centralized PostgreSQL error handling.

func IsErrUniqueViolation

func IsErrUniqueViolation(err error) (*PgError, bool)

IsErrUniqueViolation checks if the error is a PostgreSQL unique violation error.

type Querier

type Querier interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
	CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}

Querier is the query surface shared by *Client, pgx.Tx and *pgx.Conn. Depend on it in repositories so the same code runs inside or outside a transaction and can be replaced by a mock (e.g. pgxmock) in tests.

type TxRunner

type TxRunner interface {
	WithTx(ctx context.Context, opts pgx.TxOptions, fn func(pgx.Tx) error) error
}

TxRunner runs a function inside a retried transaction (see Client.WithTx).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址