Documentation
¶
Overview ¶
Package postgres provides production infrastructure helpers around pgx and pgxpool without hiding their native types or behavior.
Index ¶
- Constants
- Variables
- func IsCancellation(err error) bool
- func IsCheckViolation(err error) bool
- func IsConnectivity(err error) bool
- func IsDeadlock(err error) bool
- func IsExclusionViolation(err error) bool
- func IsForeignKeyViolation(err error) bool
- func IsKind(err error, kind ErrorKind) bool
- func IsLockUnavailable(err error) bool
- func IsPoolExhaustion(err error) bool
- func IsQueryCanceled(err error) bool
- func IsRetryable(err error) bool
- func IsSerializationFailure(err error) bool
- func IsTimeout(err error) bool
- func IsUniqueViolation(err error) bool
- func RunSavepoint(ctx context.Context, parent pgx.Tx, cleanupTimeout time.Duration, ...) error
- func RunSavepointWithOptions(ctx context.Context, parent pgx.Tx, options SavepointOptions, ...) (err error)
- func RunTransaction(ctx context.Context, beginner Beginner, options TransactionOptions, ...) (err error)
- func SQLState(err error) (string, bool)
- type Beginner
- type Config
- type ConfigError
- type ConfigLimits
- type ErrorInfo
- type ErrorKind
- type Health
- type Observation
- type Observer
- type ObserverFunc
- type Operation
- type Outcome
- type Pool
- func (p *Pool) Acquire(ctx context.Context) (*pgxpool.Conn, error)
- func (p *Pool) Close(ctx context.Context) errordeprecated
- func (p *Pool) Liveness() Health
- func (p *Pool) Ping(ctx context.Context) error
- func (p *Pool) Raw() *pgxpool.Pool
- func (p *Pool) Readiness(ctx context.Context) Health
- func (p *Pool) Shutdown(ctx context.Context) error
- func (p *Pool) Stats() Stats
- type PoolConfig
- type SavepointOptions
- type StartupPolicy
- type Stats
- type TLSConfig
- type TLSMode
- type TransactionOptions
Constants ¶
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 how long Close waits for borrowed connections. DefaultShutdownTimeout = 10 * time.Second // DefaultConfigResolutionTimeout bounds cooperative resolver preparation. DefaultConfigResolutionTimeout = 5 * time.Second )
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 bounds pool lifetime, idle and maintenance durations. MaximumPoolLifetime = 30 * 24 * time.Hour )
const ( // DefaultTransactionCleanupTimeout bounds rollback after cancellation. DefaultTransactionCleanupTimeout = 5 * time.Second )
Variables ¶
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") )
var ( // ErrNilTransactionCallback reports a missing transaction body. ErrNilTransactionCallback = errors.New("postgres: transaction callback is nil") )
Functions ¶
func IsCancellation ¶
IsCancellation reports caller context cancellation.
func IsCheckViolation ¶
IsCheckViolation reports SQLSTATE 23514.
func IsConnectivity ¶
IsConnectivity reports PostgreSQL connection-class or network errors.
func IsExclusionViolation ¶
IsExclusionViolation reports SQLSTATE 23P01.
func IsForeignKeyViolation ¶
IsForeignKeyViolation reports SQLSTATE 23503.
func IsLockUnavailable ¶
IsLockUnavailable reports SQLSTATE 55P03. The state alone does not distinguish NOWAIT from lock_timeout.
func IsPoolExhaustion ¶
IsPoolExhaustion reports a bounded acquisition timeout.
func IsQueryCanceled ¶
IsQueryCanceled reports SQLSTATE 57014. The state alone does not distinguish explicit cancellation from statement_timeout.
func IsRetryable ¶
IsRetryable is advisory classification only. It never executes or retries a closure because callers must account for external side effects themselves.
func IsSerializationFailure ¶
IsSerializationFailure reports SQLSTATE 40001.
func IsUniqueViolation ¶
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.
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.
func RunTransaction ¶
func RunTransaction( ctx context.Context, beginner Beginner, options TransactionOptions, fn func(context.Context, pgx.Tx) error, ) (err error)
RunTransaction begins a transaction, invokes fn once, and finalizes exactly once. 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.
Types ¶
type Beginner ¶
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 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 time.Duration
AcquireTimeout time.Duration
PingTimeout time.Duration
ShutdownTimeout time.Duration
MaxConns int32
MinConns int32
MinIdleConns int32
MaxConnLifetime time.Duration
MaxConnLifetimeJitter time.Duration
MaxConnIdleTime time.Duration
HealthCheckPeriod time.Duration
StartupPolicy StartupPolicy
TLS TLSConfig
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 ¶
ConfigError reports a field without echoing credentials. Resolver causes are withheld; trusted Configure causes remain inspectable.
func (*ConfigError) Unwrap ¶
func (e *ConfigError) Unwrap() error
Unwrap exposes a safe underlying cause when one is available.
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. Opaque TLS and callback data remain bounded, trusted application-owned collaborators.
type ErrorInfo ¶
type ErrorInfo struct {
Kind ErrorKind
SQLState string
Retryable bool
Cause error
Postgres *pgconn.PgError
Severity string
Constraint string
Schema string
Table string
Column string
Detail string
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.
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" // 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 Observation ¶
type Observation struct {
Operation Operation
Outcome Outcome
Duration time.Duration
ErrorKind ErrorKind
SQLState string
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(context.Context, Observation)
}
Observer consumes bounded lifecycle and transaction observations.
func NewSlogObserver ¶
NewSlogObserver creates a privacy-preserving Observer compatible with slog and log. It records only fixed operation metadata and pool gauges.
type ObserverFunc ¶
type ObserverFunc func(context.Context, Observation)
ObserverFunc adapts a function to Observer.
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 that a transaction callback panicked. OutcomePanic Outcome = "panic" // OutcomeAborted indicates that a callback terminated its goroutine. OutcomeAborted Outcome = "aborted" )
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool adds bounded lifecycle operations while retaining the native pgxpool.
func Connect ¶
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.
func (*Pool) Acquire ¶
Acquire obtains a connection while honoring the earlier of the caller's deadline and the configured acquisition timeout.
func (*Pool) Liveness ¶
Liveness reports whether pool shutdown has started without contacting the database. Database availability belongs to Readiness rather than liveness.
type PoolConfig ¶
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. It does not recover collaborator panics.
type SavepointOptions ¶
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 int64
AcquiredConns int32
CanceledAcquireCount int64
ConstructingConns int32
EmptyAcquireCount int64
EmptyAcquireWaitTime time.Duration
IdleConns int32
MaxConns int32
NewConnsCount int64
TotalConns int32
}
Stats is an immutable snapshot of native pgxpool statistics.
type TLSConfig ¶
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.
Source Files
¶
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
|
|
|
sqlc
command
|
|
|
worker
command
|
|
|
internal
|
|
|
oteladapter
Package oteladapter contains the shared OpenTelemetry adapter implementation.
|
Package oteladapter contains the shared OpenTelemetry adapter implementation. |
|
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. |