Help us shape the future of Go! Take the 2026 Go Developer Survey

postgres

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 14 Imported by: 0

README

postgres

CI CodeQL Coverage Mutation Documentation Published v2 Reference Release Go License

postgres is focused production infrastructure for PostgreSQL applications built directly on pgx/v5. It standardizes finite pool configuration, bounded lifecycle operations, transaction cleanup, SQLSTATE classification, health, safe telemetry, and real PostgreSQL testing without hiding native pgx types.

It is not a driver, ORM, query builder, migration engine, repository layer, or multi-database abstraction.

The published v2.0.0 release uses the /v2 module path. Existing published v1 consumers remain unchanged. See the migration guide.

Requirements

  • Go 1.27.0 or newer
  • pgx 5.11.x (root v2); the retained published-v1 example pins its own baseline
  • PostgreSQL 14, 15, 16, 17, or 18
  • Docker-compatible container runtime only for postgrestest and integration tests

Installation

go get github.com/faustbrian/go-postgres/v2@v2

Quick start

The complete examples/service program is the compiler-built five-minute starting point. In a repository checkout, run it against a development database with:

DATABASE_URL='postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable' \
  go run ./examples/service

The core construction and transaction flow is:

ctx := context.Background()
pool, err := postgres.Connect(ctx, postgres.Config{
	ResolveDSN:       resolveDSN, // explicit application policy; see migration guide
	StartupPolicy:    postgres.StartupPing, // opt into startup connectivity
    DSN:             os.Getenv("DATABASE_URL"),
    MaxConns:        20,
    AcquireTimeout:  2 * time.Second,
    PingTimeout:     time.Second,
    ShutdownTimeout: 10 * time.Second,
})
if err != nil {
    return err
}
defer pool.Shutdown(context.Background())

err = postgres.RunTransaction(ctx, pool.Raw(), postgres.TransactionOptions{
    TxOptions: pgx.TxOptions{IsoLevel: pgx.Serializable},
}, func(ctx context.Context, tx pgx.Tx) error {
    _, err := tx.Exec(ctx, "INSERT INTO jobs (name) VALUES ($1)", "reindex")
    return err
})

Connect defaults to lazy startup without proactive minimum connections. This example explicitly requests a bounded ping. Pool.Raw() returns the exact *pgxpool.Pool, so generated sqlc code and all native pgx operations remain available.

Safe defaults

Setting Default
connect timeout 5 seconds
acquire timeout 5 seconds
ping timeout 2 seconds
shutdown timeout 10 seconds
maximum connections 10
maximum connection lifetime 1 hour
lifetime jitter 5 minutes
maximum idle time 30 minutes
health-check period 1 minute
startup policy lazy, zero minimum connections

Zero values select these finite defaults. Admission budgets allow positive reductions, and native policies are revalidated after Configure. TLS remains an explicit deployment decision: use a DSN with sslmode=verify-full or provide a verified tls.Config with TLSRequire; never assume encryption authenticates the server when InsecureSkipVerify is enabled.

Packages

  • postgres: configuration, pool lifecycle, transactions, health, classification, bounded observations, and safe slog integration
  • adapters/service: service lifecycle, optional startup validation and readiness, and explicit shared or transferred pool ownership
  • adapters/otel: optional standard OpenTelemetry metrics adapter
  • postgrestest: optional Testcontainers lifecycle and always-rollback transaction helpers for real PostgreSQL

Query tracing is provided by telemetry/instrumentation/gopostgres through the native pgx.ConnConfig.Tracer hook. It records allow-listed query names and never SQL or arguments.

Service lifecycle

adapters/service.New accepts either an existing pool or a constructor. A constructor transfers ownership after successful startup. Existing pools remain shared unless TransferOwnership is explicit. StartupPing is opt-in, and callers opt into runtime readiness by adding adapter.Readiness() to the selected service.Plan.

The adapter performs no retries. It closes an owned pool once, never closes a shared pool, and uses the service lifecycle context together with the pool's configured ping and shutdown bounds.

The released postgresservice and otelpostgres import paths remain compatibility facades. New code should use the target-oriented adapter paths.

Documentation

Start with the documentation index, quickstart, and API reference. Operators should read the pool and lifecycle guide, TLS guide, Kubernetes guide, and operational FAQ. Adoption and maintenance references include migration, compatibility, performance, testing helpers, release history, support, and private security reporting. Shared construction, ownership, lifecycle, and composition expectations are in the versioned Golib ecosystem index and its Persistence and durability family.

Development

make inventory
make cohesion
make repository-check
make check
make ci

make check runs the bounded contract through the public tool pinned in .golib.yaml, including PostgreSQL fixtures, the root integration tag and the targeted single-cleanup/shutdown-admission race. The intentional migration example module retains its PostgreSQL fixture and public dependency baseline. make ci also validates repository/cohesion structure. Base-free checks run fuzz seeds; changed-source CI selects active smoke. make check-full retains all full campaigns and native coverage evidence. Scheduled CI uses the bounded route, not an automatic PostgreSQL-major matrix. See contributor verification for standalone tests, public installation, disposable-cache sessions and explicit release rehearsal.

License

MIT. See LICENSE and THIRD_PARTY_NOTICES.md.

Documentation navigation

Complete documentation map · Current source package map

Use the versioned ecosystem entry for package selection. The frozen compatibility cohort is separate from current package releases and unpublished source changes. Adopting them does not silently update that cohort.

Documentation

Overview

Package postgres provides finite pgx pool configuration, lifecycle helpers, transaction cleanup, error classification and bounded observations without hiding native pgx types. It is not a driver, ORM, migration engine or retry loop.

PrepareConfig requires an application ResolveDSN collaborator and transfers its fresh native configuration through typed defaults and admission checks. Connect owns the resulting pool; StartupLazy does not prove connectivity. Release every acquired connection and arrange Shutdown after users finish. Raw is a borrowed escape hatch, not an independently owned pool.

RunTransaction and RunSavepoint invoke application bodies once. Applications own SQL, operation contexts and any external effects; rollback cannot undo those effects. Observers are synchronous trusted collaborators. Diagnostic errors retain native data, while package telemetry projects finite categories. Optional service and OpenTelemetry adapters live under adapters; postgrestest provides separately acquired real PostgreSQL fixtures for integration tests.

Index

Constants

View Source
const (
	// DefaultConnectTimeout bounds each new PostgreSQL connection attempt.
	DefaultConnectTimeout = 5 * time.Second
	// DefaultAcquireTimeout bounds waiting for a pooled connection.
	DefaultAcquireTimeout = 5 * time.Second
	// DefaultPingTimeout bounds startup and readiness probes.
	DefaultPingTimeout = 2 * time.Second
	// DefaultShutdownTimeout bounds each Shutdown wait for native pool cleanup.
	DefaultShutdownTimeout = 10 * time.Second
	// DefaultConfigResolutionTimeout bounds cooperative resolver preparation.
	DefaultConfigResolutionTimeout = 5 * time.Second
)
View Source
const (
	// DefaultMaximumDSNBytes bounds input before resolver acquisition.
	DefaultMaximumDSNBytes = 8 << 10
	// DefaultMaximumFallbacks bounds native fallback host entries.
	DefaultMaximumFallbacks = 16
	// DefaultMaximumRuntimeParams bounds native session parameter entries.
	DefaultMaximumRuntimeParams = 128
	// DefaultMaximumNativeStringBytes bounds aggregate native credential strings.
	DefaultMaximumNativeStringBytes = 64 << 10
	// DefaultMaximumCacheEntries bounds each native statement/description cache.
	DefaultMaximumCacheEntries = 1024
	// DefaultMaximumProtocolMessageBodyBytes bounds each native wire-message body.
	DefaultMaximumProtocolMessageBodyBytes = 8 << 20
	// MaximumPoolConnections is the finite pool-size ceiling.
	MaximumPoolConnections = 1024
	// MaximumConfigTimeout bounds preparation and connection/operation timeouts.
	MaximumConfigTimeout = time.Hour
	// MaximumPoolLifetime caps native lifetime, idle and maintenance settings.
	MaximumPoolLifetime = 30 * 24 * time.Hour
)
View Source
const (
	// DefaultTransactionCleanupTimeout bounds rollback after cancellation.
	DefaultTransactionCleanupTimeout = 5 * time.Second
)

Variables

View Source
var (
	// ErrContextRequired identifies an operation that received a nil context.
	ErrContextRequired = errors.New("postgres: context required")
	// ErrAcquireTimeout identifies the configured acquisition deadline.
	ErrAcquireTimeout = errors.New("postgres: acquire timeout")
	// ErrPoolExhausted identifies an acquisition timeout observed while all
	// configured connection slots were acquired or constructing.
	ErrPoolExhausted = errors.New("postgres: pool exhausted")
	// ErrHealthTimeout identifies a configured or caller health-check deadline.
	ErrHealthTimeout = errors.New("postgres: health check timeout")
	// ErrPoolClosed identifies a pool whose shutdown has begun.
	ErrPoolClosed = errors.New("postgres: pool closed")
	// ErrShutdownTimeout identifies a shutdown that outlasted its context.
	ErrShutdownTimeout = errors.New("postgres: shutdown timeout")
)
View Source
var (
	// ErrNilTransactionCallback reports a missing transaction body.
	ErrNilTransactionCallback = errors.New("postgres: transaction callback is nil")
)

Functions

func IsCancellation

func IsCancellation(err error) bool

IsCancellation reports caller context cancellation.

func IsCheckViolation

func IsCheckViolation(err error) bool

IsCheckViolation reports SQLSTATE 23514.

func IsConnectivity

func IsConnectivity(err error) bool

IsConnectivity reports PostgreSQL connection-class or network errors.

func IsDeadlock

func IsDeadlock(err error) bool

IsDeadlock reports SQLSTATE 40P01.

func IsExclusionViolation

func IsExclusionViolation(err error) bool

IsExclusionViolation reports SQLSTATE 23P01.

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

IsForeignKeyViolation reports SQLSTATE 23503.

func IsKind

func IsKind(err error, kind ErrorKind) bool

IsKind reports whether err classifies as kind.

func IsLockUnavailable

func IsLockUnavailable(err error) bool

IsLockUnavailable reports SQLSTATE 55P03. The state alone does not distinguish NOWAIT from lock_timeout.

func IsPoolExhaustion

func IsPoolExhaustion(err error) bool

IsPoolExhaustion reports a bounded acquisition timeout.

func IsQueryCanceled

func IsQueryCanceled(err error) bool

IsQueryCanceled reports SQLSTATE 57014. The state alone does not distinguish explicit cancellation from statement_timeout.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable is advisory classification only. It never executes or retries a closure because callers must account for external side effects themselves.

func IsSerializationFailure

func IsSerializationFailure(err error) bool

IsSerializationFailure reports SQLSTATE 40001.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports a context deadline.

func IsUniqueViolation

func IsUniqueViolation(err error) bool

IsUniqueViolation reports SQLSTATE 23505.

func RunSavepoint

func RunSavepoint(
	ctx context.Context,
	parent pgx.Tx,
	cleanupTimeout time.Duration,
	fn func(context.Context, pgx.Tx) error,
) error

RunSavepoint executes fn in pgx's explicit pseudo-nested transaction. pgx implements this with SAVEPOINT, RELEASE SAVEPOINT, and ROLLBACK TO SAVEPOINT. See RunSavepointWithOptions for context, borrowing and failure-window rules.

func RunSavepointWithOptions

func RunSavepointWithOptions(
	ctx context.Context,
	parent pgx.Tx,
	options SavepointOptions,
	fn func(context.Context, pgx.Tx) error,
) (err error)

RunSavepointWithOptions executes fn in an observed pgx pseudo-nested transaction with bounded rollback cleanup. The callback borrows the child transaction; it must not finalize or retain it. The parent stays caller-owned and must still be finalized independently. Context, retry and failure-window rules are the same as RunTransaction; releasing a savepoint is not a durable commit of its parent.

func RunTransaction

func RunTransaction(
	ctx context.Context,
	beginner Beginner,
	options TransactionOptions,
	fn func(context.Context, pgx.Tx) error,
) (err error)

RunTransaction begins a transaction and invokes fn once after a successful begin. A nil callback is refused before begin. A non-nil ctx and usable beginner are required. The callback borrows tx for this invocation: do not retain it or finalize it yourself. A nil callback result requests commit; an error requests rollback. A returned commit error is preserved without another rollback attempt or a durability guarantee. It never retries fn.

Callback and rollback errors are joined so callers can inspect both with errors.Is and errors.As. A cleanup panic cannot replace a returned callback error, callback panic, or goroutine termination. A panic during commit triggers bounded rollback before the original value propagates.

Rollback uses context.WithoutCancel(ctx) plus CleanupTimeout, preserving values but not caller cancellation/deadlines. Begin, body and commit retain the caller context and native semantics; deadlines cannot preempt uncooperative code. External callback effects are not undone by rollback.

func SQLState

func SQLState(err error) (string, bool)

SQLState returns the first native PostgreSQL SQLSTATE in the error graph.

Types

type Beginner

type Beginner interface {
	// BeginTx returns a transaction whose finalization is delegated to the runner.
	BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)
}

Beginner is implemented by pgx.Conn, pgxpool.Pool, pgxpool.Conn, and other native pgx values that can begin a transaction with explicit options.

type Config

type Config struct {
	// DSN is an admitted credential string passed to ResolveDSN; never log it.
	DSN string

	// ResolveDSN is required. It owns any environment, filesystem or other
	// acquisition used to resolve the admitted DSN, must cooperate with ctx,
	// and transfers a fresh parser-created native configuration exclusively.
	ResolveDSN func(context.Context, string) (*PoolConfig, error)

	// ConfigResolutionTimeout bounds cooperative preparation; zero uses 5s.
	ConfigResolutionTimeout time.Duration
	// Limits selects finite native credential admission budgets.
	Limits ConfigLimits

	// ConnectTimeout bounds native connection attempts; zero selects 5s.
	ConnectTimeout time.Duration
	// AcquireTimeout bounds wrapper acquisition, not subsequent queries; zero
	// selects 5s.
	AcquireTimeout time.Duration
	// PingTimeout bounds wrapper probes and supplies the native default; zero
	// selects 2s.
	PingTimeout time.Duration
	// ShutdownTimeout bounds each wrapper shutdown wait, not native cleanup;
	// zero selects 10s.
	ShutdownTimeout time.Duration

	// MaxConns selects the native connection ceiling; zero selects 10.
	MaxConns int32
	// MinConns requests a native minimum; StartupLazy requires zero.
	MinConns int32
	// MinIdleConns requests a native idle minimum; StartupLazy requires zero.
	MinIdleConns int32

	// MaxConnLifetime selects the native maximum lifetime; zero selects one hour.
	MaxConnLifetime time.Duration
	// MaxConnLifetimeJitter spreads native expiry; zero selects five minutes.
	MaxConnLifetimeJitter time.Duration
	// MaxConnIdleTime selects the native idle lifetime; zero selects thirty minutes.
	MaxConnIdleTime time.Duration
	// HealthCheckPeriod selects native maintenance frequency; zero selects one minute.
	HealthCheckPeriod time.Duration
	// StartupPolicy chooses lazy construction or an explicit connectivity probe.
	StartupPolicy StartupPolicy
	// TLS applies host-specific overrides before Configure.
	TLS TLSConfig
	// Observer receives synchronous wrapper observations; nil disables them.
	Observer Observer

	// SessionInit runs for every newly established connection after any native
	// AfterConnect hook. Returning an error rejects that connection.
	SessionInit func(context.Context, *pgx.Conn) error

	// Configure receives the admitted native configuration and preparation
	// deadline after typed options. It must cooperate with ctx and exclusively
	// mutate the transferred configuration without retaining it for later use.
	Configure func(context.Context, *PoolConfig) error
}

Config defines safe, finite defaults for constructing a PostgreSQL pool. ResolveDSN is required; other zero fields select documented defaults. Negative sizes or durations are rejected rather than passed through to pgxpool.

type ConfigError

type ConfigError struct {
	// Field names the rejected configuration field or admission boundary.
	Field string
	// Problem is the diagnostic included by Error; package-created text omits
	// credentials.
	Problem string
	// Cause is retained for trusted Configure failures, not resolver failures.
	Cause error
}

ConfigError reports a field without echoing credentials. Resolver causes are withheld; trusted Configure causes remain inspectable.

func (*ConfigError) Error

func (e *ConfigError) Error() string

Error implements error.

func (*ConfigError) Unwrap

func (e *ConfigError) Unwrap() error

Unwrap exposes Cause when present. Trusted hook errors retain their original data; the application is responsible for safe inspection or logging.

type ConfigLimits

type ConfigLimits struct {
	// MaximumDSNBytes admits the input before application resolution.
	MaximumDSNBytes int
	// MaximumFallbacks admits the native fallback slice before traversal.
	MaximumFallbacks int
	// MaximumRuntimeParams admits the native map before traversal.
	MaximumRuntimeParams int
	// MaximumNativeStringBytes charges every native string occurrence, including
	// the retained original connection string, all scalar settings, fallback
	// hosts, and runtime parameter keys/values. Opaque TLS data is not charged.
	MaximumNativeStringBytes int
	// MaximumStatementCacheEntries bounds the native prepared statement cache.
	MaximumStatementCacheEntries int
	// MaximumDescriptionCacheEntries bounds the native description cache.
	MaximumDescriptionCacheEntries int
	// MaximumProtocolMessageBodyBytes bounds each native wire-message body.
	MaximumProtocolMessageBodyBytes int
}

ConfigLimits controls package-owned admission. Zero selects finite defaults; positive values may only reduce the defaults. The application must bound opaque TLS data and resource use by trusted callbacks separately.

type ErrorInfo

type ErrorInfo struct {
	// Kind is the selected policy category, with native PostgreSQL errors
	// taking precedence.
	Kind ErrorKind
	// SQLState is the unredacted native code when a PgError matches.
	SQLState string
	// Retryable is advisory for serialization/deadlock or native safe-to-retry
	// network errors.
	Retryable bool
	// Cause is the exact input error, including sensitive data it may carry.
	Cause error
	// Postgres borrows the matched native error; it is not cloned or redacted.
	Postgres *pgconn.PgError

	// Severity retains native server severity text.
	Severity string
	// Constraint retains the native constraint name.
	Constraint string
	// Schema retains the native schema name.
	Schema string
	// Table retains the native table name.
	Table string
	// Column retains the native column name.
	Column string
	// Detail retains server detail text and may contain sensitive values.
	Detail string
	// Hint retains server advice and may contain sensitive values.
	Hint string
}

ErrorInfo classifies an error without replacing it. Cause is the exact input error, Postgres is the matched native PgError, and server metadata remains available for policy code that is allowed to inspect it.

func Classify

func Classify(err error) ErrorInfo

Classify returns stable policy metadata while preserving the original error graph for errors.Is and errors.As. Detail and Hint may contain sensitive values and must not be logged without an application redaction policy. A matched native PgError takes precedence over joined pool or context errors; classification does not prove retry safety for external effects or a commit outcome.

type ErrorKind

type ErrorKind string

ErrorKind is a stable policy category derived from an original error.

const (
	// ErrorNone is the classification of a nil error.
	ErrorNone ErrorKind = ""
	// ErrorUnknown indicates that no supported category matched.
	ErrorUnknown ErrorKind = "unknown"
	// ErrorUniqueViolation identifies SQLSTATE 23505.
	ErrorUniqueViolation ErrorKind = "unique_violation"
	// ErrorForeignKeyViolation identifies SQLSTATE 23503.
	ErrorForeignKeyViolation ErrorKind = "foreign_key_violation"
	// ErrorCheckViolation identifies SQLSTATE 23514.
	ErrorCheckViolation ErrorKind = "check_violation"
	// ErrorExclusionViolation identifies SQLSTATE 23P01.
	ErrorExclusionViolation ErrorKind = "exclusion_violation"
	// ErrorSerializationFailure identifies SQLSTATE 40001.
	ErrorSerializationFailure ErrorKind = "serialization_failure"
	// ErrorDeadlock identifies SQLSTATE 40P01.
	ErrorDeadlock ErrorKind = "deadlock"
	// ErrorTimeout identifies context deadlines.
	ErrorTimeout ErrorKind = "timeout"
	// ErrorCancellation identifies caller context cancellation.
	ErrorCancellation ErrorKind = "cancellation"
	// ErrorQueryCanceled identifies SQLSTATE 57014. PostgreSQL uses it for
	// explicit cancellation and statement_timeout, so policy must inspect its
	// own operation context rather than assume one cause.
	ErrorQueryCanceled ErrorKind = "query_canceled"
	// ErrorLockUnavailable identifies SQLSTATE 55P03. PostgreSQL uses it for
	// both NOWAIT and lock_timeout failures.
	ErrorLockUnavailable ErrorKind = "lock_unavailable"
	// ErrorConnectivity identifies connection-class and network errors.
	ErrorConnectivity ErrorKind = "connectivity"
	// ErrorPoolExhaustion identifies a bounded pool acquisition timeout.
	ErrorPoolExhaustion ErrorKind = "pool_exhaustion"
)

type Health

type Health struct {
	// Ready reports success of this probe, not a persistent availability guarantee.
	Ready bool
	// Err preserves the probe error; nil means the probe succeeded.
	Err error
	// Stats is sampled separately from the readiness ping or liveness check.
	Stats Stats
}

Health is the result of a readiness probe and its contemporaneous stats.

type Observation

type Observation struct {
	// Operation identifies a wrapper lifecycle operation, not application SQL.
	Operation Operation
	// Outcome identifies completion, error, panic or goroutine termination.
	Outcome Outcome
	// Duration is sampled before observer delivery and excludes its own callback time.
	Duration time.Duration
	// ErrorKind is the finite projection of diagnostic classification.
	ErrorKind ErrorKind
	// SQLState is an exact recognized state, empty, or the fixed unknown category.
	SQLState string
	// Pool contains a separate native statistics snapshot when HasPoolStats is true.
	Pool Stats
	// HasPoolStats distinguishes an actual zero-valued snapshot from an
	// operation, such as a transaction, that did not sample pool state.
	HasPoolStats bool
}

Observation contains bounded metadata only. It intentionally excludes SQL, query arguments, DSNs, database error text, and arbitrary caller labels. Package-produced observations and built-in observers project unrecognized categories to "unknown"; Classify and SQLState retain native diagnostic data.

type Observer

type Observer interface {
	// Observe consumes metadata synchronously; concurrent calls must be safe.
	Observe(context.Context, Observation)
}

Observer consumes bounded lifecycle and transaction observations. Package delivery is synchronous and may be concurrent across operations. Keep callbacks prompt and concurrency-safe: ordinary panics are recovered, but blocking and goroutine termination are not isolated. The operation context may be canceled. Avoid recursively invoking observed operations from their own observer; delivery has no recursion guard and may still hold acquired resources.

func NewSlogObserver

func NewSlogObserver(logger *slog.Logger) Observer

NewSlogObserver creates a privacy-preserving Observer compatible with slog and log. It records only fixed operation metadata and pool gauges. A nil logger uses slog.Default. The logger and handler stay caller-owned; delivery is synchronous and this constructor does not configure or shut them down.

type ObserverFunc

type ObserverFunc func(context.Context, Observation)

ObserverFunc adapts a non-nil function to Observer without synchronization or recovery of direct calls. Package delivery supplies its own panic boundary.

func (ObserverFunc) Observe

func (f ObserverFunc) Observe(ctx context.Context, observation Observation)

Observe implements Observer.

type Operation

type Operation string

Operation is a fixed low-cardinality operation name.

const (
	// OperationAcquire identifies pool connection acquisition.
	OperationAcquire Operation = "pool.acquire"
	// OperationPing identifies pool health checks.
	OperationPing Operation = "pool.ping"
	// OperationClose identifies bounded pool shutdown waits.
	OperationClose Operation = "pool.close"
	// OperationTransaction identifies top-level transactions.
	OperationTransaction Operation = "transaction"
	// OperationSavepoint identifies explicit nested savepoints.
	OperationSavepoint Operation = "savepoint"
)

type Outcome

type Outcome string

Outcome is a fixed low-cardinality operation result.

const (
	// OutcomeSuccess indicates a nil operation error.
	OutcomeSuccess Outcome = "success"
	// OutcomeError indicates a classified operation error.
	OutcomeError Outcome = "error"
	// OutcomePanic indicates a transaction or savepoint panic.
	OutcomePanic Outcome = "panic"
	// OutcomeAborted indicates goroutine termination before the runner completed.
	OutcomeAborted Outcome = "aborted"
)

type Pool

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

Pool owns a native pgxpool and adds bounded lifecycle waits. Use Connect; a zero Pool is not usable. Native operations and observer callbacks retain their own cooperation and concurrency requirements. Wrapper admission and shutdown state are synchronized; concurrent operations require safe native hooks and observers. Do not copy a Pool after use.

func Connect

func Connect(ctx context.Context, input Config) (*Pool, error)

Connect constructs a native pgxpool without a startup connection by default. StartupPing explicitly requests a bounded connectivity check. A nil or already-canceled context is rejected before configuration or I/O. The caller owns the successful pool and must Shutdown it. A failed startup ping closes the constructed backend before returning; native Close and application callbacks are not forcibly interrupted by the caller deadline.

func New deprecated

func New(ctx context.Context, input Config) (*Pool, error)

New constructs a native pgxpool.

Deprecated: use Connect to make resource acquisition explicit.

func (*Pool) Acquire

func (p *Pool) Acquire(ctx context.Context) (*pgxpool.Conn, error)

Acquire obtains a connection while honoring the earlier of the caller's deadline and the configured acquisition timeout. A non-nil ctx is required. On success the caller must Release the connection; the timeout does not bound how long it is held or any subsequent query. Saturation is inferred from the sampled statistics only when the configured timeout is the context cause. Observer delivery runs before returning the connection and can extend the overall call duration.

func (*Pool) Close deprecated

func (p *Pool) Close(ctx context.Context) error

Close delegates to Shutdown.

Deprecated: use Shutdown for complete bounded owned shutdown.

func (*Pool) Liveness

func (p *Pool) Liveness() Health

Liveness reports whether pool shutdown has started without contacting the database. Database availability belongs to Readiness rather than liveness.

func (*Pool) Ping

func (p *Pool) Ping(ctx context.Context) error

Ping checks PostgreSQL connectivity using the earlier caller or configured deadline. A non-nil ctx is required. The observer runs synchronously after the native probe and can extend the overall call duration.

func (*Pool) Raw

func (p *Pool) Raw() *pgxpool.Pool

Raw returns a borrowed native pool without copying it or transferring ownership. Operations through Raw bypass wrapper acquisition bounds, shutdown admission checks and observations. Do not close it independently of its owning Pool.

func (*Pool) Readiness

func (p *Pool) Readiness(ctx context.Context) Health

Readiness performs a bounded ping and returns a pool-statistics snapshot.

func (*Pool) Shutdown

func (p *Pool) Shutdown(ctx context.Context) error

Shutdown closes admission and starts native pool shutdown exactly once. Each caller waits independently until its own or the configured shutdown bound. Native cleanup continues after an individual caller stops waiting, so a timeout is not proof of resource release. Release borrowed connections to allow cleanup to finish. Even an already-canceled non-nil ctx starts shutdown; nil ctx returns ErrContextRequired without changing admission. In-flight calls that passed the admission check retain native pgx behavior.

func (*Pool) Stats

func (p *Pool) Stats() Stats

Stats returns a detached value copy of native pgxpool counters and gauges.

type PoolConfig

type PoolConfig = pgxpool.Config

PoolConfig is the native pgxpool configuration type. The alias makes hooks explicit while preserving direct access to every pgxpool option.

func ParseConfig

func ParseConfig(input Config) (*PoolConfig, error)

ParseConfig delegates to PrepareConfig with a finite cooperative deadline. ResolveDSN is required and owns native parsing and its ambient acquisitions. A deadline cannot preempt an uncooperative application callback.

func PrepareConfig

func PrepareConfig(ctx context.Context, input Config) (*PoolConfig, error)

PrepareConfig admits the DSN before calling the required application resolver, validates native shapes before typed overrides, and revalidates after Configure. The resolver transfers a fresh parser-created configuration; TLS data, native callbacks, parser allocations and their resource bounds remain application-owned. Preparation cooperatively honors ctx and ConfigResolutionTimeout, including callback completion checks. The successful result is transferred to the caller, not retained or copied by preparation. It does not recover collaborator panics. Native parsing and callbacks can still block past a deadline if they do not cooperate; these checks are not a total process-memory budget.

type SavepointOptions

type SavepointOptions struct {
	// CleanupTimeout bounds cooperative rollback; zero selects 5s, negative
	// expires immediately.
	CleanupTimeout time.Duration
	// Observer receives the final synchronous savepoint observation; nil disables it.
	Observer Observer
}

SavepointOptions controls cleanup and observation for a nested transaction.

type StartupPolicy

type StartupPolicy uint8

StartupPolicy controls whether Connect proves connectivity before returning.

const (
	// StartupLazy is the default: no startup ping or proactive minimum connections.
	StartupLazy StartupPolicy = iota
	// StartupPing explicitly requests a bounded connectivity check during Connect.
	StartupPing
)

type Stats

type Stats struct {
	// AcquireCount is the native count of successful acquisitions.
	AcquireCount int64
	// AcquiredConns is the number of connections currently borrowed.
	AcquiredConns int32
	// CanceledAcquireCount is the native count of canceled acquisitions.
	CanceledAcquireCount int64
	// ConstructingConns is the number of connections being constructed.
	ConstructingConns int32
	// EmptyAcquireCount counts successful acquisitions that waited for an empty pool.
	EmptyAcquireCount int64
	// EmptyAcquireWaitTime is cumulative wait time for successful acquisitions
	// from an empty pool; canceled waits are not included.
	EmptyAcquireWaitTime time.Duration
	// IdleConns is the number of currently idle connections.
	IdleConns int32
	// MaxConns is the configured native maximum connection count.
	MaxConns int32
	// NewConnsCount is the native cumulative count of created connections.
	NewConnsCount int64
	// TotalConns includes idle, acquired and constructing connections.
	TotalConns int32
}

Stats is a detached value snapshot of native pgxpool statistics.

type TLSConfig

type TLSConfig struct {
	// Mode chooses DSN preservation, TLS disablement or an explicit override.
	Mode TLSMode
	// Config is required for TLSRequire; it is ignored by other modes.
	Config *tls.Config
}

TLSConfig is an explicit TLS override. TLSRequire copies Config and its certificate pools, protocol slices, and certificate bytes before use. Callback, private-key, cache, random-source, clock, and writer values remain caller-owned collaborators and must be safe for concurrent use.

type TLSMode

type TLSMode uint8

TLSMode controls whether typed TLS settings override the DSN.

const (
	// TLSFromDSN preserves pgx parsing of sslmode and related DSN settings.
	TLSFromDSN TLSMode = iota
	// TLSDisable explicitly disables TLS for every configured host.
	TLSDisable
	// TLSRequire requires the supplied tls.Config for every configured host.
	TLSRequire
)

type TransactionOptions

type TransactionOptions struct {
	// TxOptions passes native transaction modes through without validation.
	pgx.TxOptions
	// CleanupTimeout bounds cooperative rollback; zero selects 5s, negative
	// expires immediately.
	CleanupTimeout time.Duration
	// Observer receives the final synchronous transaction observation; nil disables it.
	Observer Observer
}

TransactionOptions combines native pgx transaction modes with the bounded cleanup policy used when the callback returns an error, panics, or terminates its goroutine.

Directories

Path Synopsis
adapters
otel
Package postgresotel adapts postgres observations to standard OpenTelemetry metrics without recording SQL, arguments, DSNs, or raw errors.
Package postgresotel adapts postgres observations to standard OpenTelemetry metrics without recording SQL, arguments, DSNs, or raw errors.
service
Package postgresservice adapts PostgreSQL pools to the service lifecycle.
Package postgresservice adapts PostgreSQL pools to the service lifecycle.
examples
service command
Command service demonstrates explicit startup connectivity and separate HTTP readiness/liveness probes.
Command service demonstrates explicit startup connectivity and separate HTTP readiness/liveness probes.
sqlc command
Command sqlc demonstrates transaction-bound queries with native pgx types.
Command sqlc demonstrates transaction-bound queries with native pgx types.
worker command
Command worker demonstrates a periodic transactional job claim.
Command worker demonstrates a periodic transactional job claim.
internal
oteladapter
Package oteladapter implements both public OpenTelemetry adapter paths while retaining their distinct instrumentation scopes.
Package oteladapter implements both public OpenTelemetry adapter paths while retaining their distinct instrumentation scopes.
telemetry
Package telemetry owns the finite categorical projection shared by observers.
Package telemetry owns the finite categorical projection shared by observers.
Package otelpostgres preserves the released OpenTelemetry adapter path.
Package otelpostgres preserves the released OpenTelemetry adapter path.
Package postgresservice preserves the released service-adapter path.
Package postgresservice preserves the released service-adapter path.
Package postgrestest provides real PostgreSQL containers for integration tests.
Package postgrestest provides real PostgreSQL containers for integration tests.

Jump to

Keyboard shortcuts

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