Documentation
¶
Index ¶
- Variables
- func DoWithAttempts(ctx context.Context, r *rand.Rand, fn func() error, maxAttempts int, ...) error
- func ErrCommit(err error) error
- func ErrCreateQuery(err error) error
- func ErrCreateTx(err error) error
- func ErrDoQuery(err error) error
- func ErrOverload(err error) error
- func ErrRollback(err error) error
- func ErrScan(err error) error
- func ErrTimeout(err error) error
- func IsRetryableTxError(err error) bool
- func ParsePgError(err error) error
- func PrettySQL(q string) string
- func WithQueryName(ctx context.Context, name string) context.Context
- type Client
- type Cluster
- type Config
- type DSNConfig
- type HealthChecker
- type Option
- func WithAfterConnect(fn func(context.Context, *pgx.Conn) error) Option
- func WithApplicationName(name string) Option
- func WithBinaryExecMode(binary bool) Optiondeprecated
- func WithConnectionPool(maxConns, minConns int32, maxLifetime time.Duration) Option
- func WithFailureThreshold(n int) Option
- func WithHealthCheckPeriod(d time.Duration) Option
- func WithHealthChecker(name string, hc HealthChecker) Option
- func WithIntervalCheck(interval time.Duration) Option
- func WithMaxAttempts(attempts int) Option
- func WithMaxConnIdleTime(d time.Duration) Option
- func WithMaxConnLifetimeJitter(d time.Duration) Option
- func WithMaxDelay(delay time.Duration) Option
- func WithMaxReplicationLag(d time.Duration) Option
- func WithPoolName(name string) Option
- func WithPrepareConn(fn func(context.Context, *pgx.Conn) (bool, error)) Option
- func WithQueryExecMode(mode pgx.QueryExecMode) Option
- func WithQueryTracer(t pgx.QueryTracer) Option
- func WithRegisterer(reg prometheus.Registerer) Option
- func WithRuntimeParam(key, value string) Option
- func WithStatementTimeout(d time.Duration) Option
- func WithTLSConfig(tlsCfg *tls.Config) Option
- func WithTraceSQL(enabled bool) Option
- func WithTracing(enabled bool) Option
- func WithTxMaxAttempts(n int) Option
- type PgError
- type Querier
- type TxRunner
Constants ¶
This section is empty.
Variables ¶
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 ErrCreateQuery ¶
func ErrCreateTx ¶
func ErrDoQuery ¶
func ErrOverload ¶
func ErrRollback ¶
func ErrTimeout ¶
func IsRetryableTxError ¶
IsRetryableTxError reports errors after which the whole transaction may be retried as is: serialization failures and deadlocks.
func ParsePgError ¶
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 ¶
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 ¶
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 ¶
Client represents a thread-safe PostgreSQL connection pool.
func NewClient ¶
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 ¶
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) ReplicationLag ¶
ReplicationLag returns the replay lag measured by the last successful health check. It is always 0 unless WithMaxReplicationLag is set.
func (*Client) WithTx ¶
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 ¶
NewCluster groups already connected clients. Give each a distinct WithPoolName ("primary", "replica-1", ...) to tell them apart in metrics.
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config holds PostgreSQL client configuration.
func (*Config) HealthCheckInterval ¶
HealthCheckInterval returns the configured background health-check interval.
func (*Config) RedactedDSN ¶
RedactedDSN returns the configured connection string with the password masked, safe for logs.
type DSNConfig ¶
DSNConfig contains parameters for building PostgreSQL connection string.
func (*DSNConfig) ToPostgresDSN ¶
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 ¶
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 ¶
WithApplicationName tags connections in pg_stat_activity and server logs.
func WithBinaryExecMode
deprecated
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 ¶
WithConnectionPool configures connection pool parameters.
func WithFailureThreshold ¶
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 ¶
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 ¶
WithIntervalCheck sets the health check interval for background monitoring.
func WithMaxAttempts ¶
WithMaxAttempts sets the maximum number of retry attempts for database operations.
func WithMaxConnIdleTime ¶
WithMaxConnIdleTime closes connections idle for longer than d, letting the pool shrink back after a burst. pgx defaults to 30 minutes.
func WithMaxConnLifetimeJitter ¶
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 ¶
WithMaxDelay sets the maximum delay between retry attempts.
func WithMaxReplicationLag ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithStatementTimeout makes the server abort any statement running longer than d. It is the backstop for queries whose context carries no deadline.
func WithTLSConfig ¶
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 ¶
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 ¶
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 ¶
WithTxMaxAttempts sets how many times WithTx runs a transaction that fails with a serialization failure or deadlock. Defaults to 3.
type PgError ¶
PgError aliases pgconn.PgError to decouple from external library. Used for centralized PostgreSQL error handling.
func IsErrUniqueViolation ¶
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.