Documentation
¶
Overview ¶
Package xpg provides PostgreSQL infrastructure utilities built on pgx.
Index ¶
- func AdvisoryXactLock(ctx context.Context, tx pgx.Tx, key int64) error
- func InSavepoint(ctx context.Context, tx pgx.Tx, fn func(context.Context, pgx.Tx) error) error
- func IsCheckViolation(err error) bool
- func IsConnectionError(err error) bool
- func IsDeadlock(err error) bool
- func IsForeignKeyViolation(err error) bool
- func IsLockNotAvailable(err error) bool
- func IsNoRows(err error) bool
- func IsNotNullViolation(err error) bool
- func IsQueryCanceled(err error) bool
- func IsRetryableTransaction(err error) bool
- func IsSerializationFailure(err error) bool
- func IsUniqueViolation(err error) bool
- func SQLState(err error) string
- func TryAdvisoryXactLock(ctx context.Context, tx pgx.Tx, key int64) (bool, error)
- type Metrics
- type MetricsRegistration
- type Option
- func WithLabel(key, value string) Option
- func WithLabels(labels map[string]string) Option
- func WithLogger(logger tracelog.Logger, level tracelog.LogLevel) Option
- func WithMetrics(metrics Metrics) Option
- func WithName(name string) Option
- func WithTracer(tracer pgx.QueryTracer) Option
- func WithTracers(tracers ...pgx.QueryTracer) Option
- type Pool
- func (p *Pool) Close()
- func (p *Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, ...) (int64, error)
- func (p *Pool) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
- func (p *Pool) InTx(ctx context.Context, txOptions pgx.TxOptions, ...) error
- func (p *Pool) Labels() map[string]string
- func (p *Pool) Name() string
- func (p *Pool) Ping(ctx context.Context) error
- func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
- func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
- func (p *Pool) Raw() *pgxpool.Pool
- func (p *Pool) SendBatch(ctx context.Context, batch *pgx.Batch) pgx.BatchResults
- func (p *Pool) Stats() PoolStats
- type PoolStats
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AdvisoryXactLock ¶
AdvisoryXactLock acquires an exclusive transaction-level advisory lock.
The call blocks until the lock is acquired or ctx is canceled. PostgreSQL releases the lock automatically when tx is committed or rolled back.
func InSavepoint ¶
InSavepoint executes fn within a PostgreSQL savepoint.
If fn returns nil, the savepoint is released; otherwise it is rolled back. If fn panics, rollback is attempted before the panic is propagated. The callback must not call Commit or Rollback; InSavepoint owns savepoint finalization.
The callback receives ctx unchanged and should observe its cancellation.
func IsCheckViolation ¶
IsCheckViolation reports whether err is a PostgreSQL check_violation.
func IsConnectionError ¶
IsConnectionError reports whether err represents a PostgreSQL connection failure known to pgx or the Go networking stack.
func IsDeadlock ¶
IsDeadlock reports whether err is a PostgreSQL deadlock_detected error.
func IsForeignKeyViolation ¶
IsForeignKeyViolation reports whether err is a PostgreSQL foreign_key_violation.
func IsLockNotAvailable ¶
IsLockNotAvailable reports whether err is a PostgreSQL lock_not_available error.
func IsNotNullViolation ¶
IsNotNullViolation reports whether err is a PostgreSQL not_null_violation.
func IsQueryCanceled ¶
IsQueryCanceled reports whether PostgreSQL canceled the query.
Client-side context cancellation remains available through errors.Is with context.Canceled or context.DeadlineExceeded.
func IsRetryableTransaction ¶
IsRetryableTransaction reports whether PostgreSQL aborted the transaction because of a serialization failure or a deadlock.
The entire transaction callback must still be safe to replay. Connection failures are deliberately not classified as transaction-retryable.
func IsSerializationFailure ¶
IsSerializationFailure reports whether err is a PostgreSQL serialization_failure.
func IsUniqueViolation ¶
IsUniqueViolation reports whether err is a PostgreSQL unique_violation.
Types ¶
type Metrics ¶
type Metrics interface {
Register(pool *Pool) (MetricsRegistration, error)
}
Metrics registers metrics for a Pool.
Implementations must be safe to reuse across multiple pools. Register is called after the underlying pgxpool.Pool has been created.
type MetricsRegistration ¶
type MetricsRegistration interface {
Close()
}
MetricsRegistration represents a metrics registration for one Pool.
Close is called once before the underlying pgxpool.Pool is closed.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a Pool.
The interface is sealed so options can only be created by this package.
func WithLabels ¶
WithLabels merges labels into the pool metadata.
Labels are defensively copied. When the same key is configured more than once, the last value wins.
func WithLogger ¶
WithLogger attaches a pgx-compatible logger to the pool.
Logging uses pgx tracelog and participates in the same tracing pipeline as tracers configured through xpg. pgx tracelog may include SQL text and query arguments in log records; applications are responsible for choosing an appropriate level and handling sensitive values.
func WithMetrics ¶
WithMetrics attaches one metrics implementation to the pool.
Metrics are registered when the pool is created and unregistered automatically when the Pool is closed.
func WithName ¶
WithName assigns a stable logical name to the pool.
Name is metadata for diagnostics and observability. It does not change the PostgreSQL application_name runtime parameter.
func WithTracer ¶
func WithTracer(tracer pgx.QueryTracer) Option
WithTracer attaches one pgx query tracer to the pool.
The option may be specified multiple times. Configured loggers and tracers are combined through pgx multitracer. When xpg logging or tracing options are configured, the resulting tracing pipeline replaces any tracer already configured on the pgx connection config.
func WithTracers ¶
func WithTracers(tracers ...pgx.QueryTracer) Option
WithTracers attaches multiple pgx query tracers to the pool.
Configured loggers and tracers are invoked in configuration order and combined through pgx multitracer. When xpg logging or tracing options are configured, the resulting tracing pipeline replaces any tracer already configured on the pgx connection config.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is a concurrency-safe PostgreSQL connection pool backed by pgxpool.
func New ¶
New creates a Pool from config.
Config must have been created by pgxpool.ParseConfig. New passes a defensive copy to pgxpool, so subsequent changes to config do not affect the Pool.
As with pgxpool.Config.Copy, the referenced tls.Config remains shared and must not be modified after it has been used to create connections.
func (*Pool) Close ¶
func (p *Pool) Close()
Close closes the pool and waits for acquired connections to be returned. Close is safe to call multiple times.
func (*Pool) CopyFrom ¶
func (p *Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
CopyFrom copies rows into the specified table.
func (*Pool) InTx ¶
func (p *Pool) InTx( ctx context.Context, txOptions pgx.TxOptions, fn func(context.Context, pgx.Tx) error, ) error
InTx executes fn in a transaction configured by txOptions.
If fn returns nil, the transaction is committed; otherwise it is rolled back. If fn panics, rollback is attempted before the panic is propagated. The callback must not call Commit or Rollback; InTx owns transaction finalization.
The callback receives ctx unchanged. Context cancellation does not automatically finalize the transaction while fn is running; fn should observe ctx and return promptly.
func (*Pool) Name ¶
Name returns the logical pool name.
If WithName is not configured, the name is derived from the connection host, port, and database.
func (*Pool) Raw ¶
Raw returns the underlying pgxpool.Pool.
The returned pool is owned by Pool and must not be closed directly.
type PoolStats ¶
type PoolStats struct {
// AcquiredConns is the number of connections currently checked out from the
// pool.
AcquiredConns int32
// ConstructingConns is the number of connections currently being created.
ConstructingConns int32
// IdleConns is the number of currently idle connections.
IdleConns int32
// MaxConns is the maximum number of connections allowed by the pool.
MaxConns int32
// TotalConns is the number of acquired, idle, and constructing connections.
TotalConns int32
// AcquireCount is the cumulative number of successful connection acquires.
AcquireCount int64
// AcquireDuration is the cumulative duration of successful connection
// acquires.
AcquireDuration time.Duration
// CanceledAcquireCount is the cumulative number of connection acquires
// canceled by context cancellation.
CanceledAcquireCount int64
// EmptyAcquireCount is the cumulative number of successful acquires that
// waited because the pool was empty.
EmptyAcquireCount int64
// EmptyAcquireWaitTime is the cumulative time spent waiting on successful
// acquires while the pool was empty.
EmptyAcquireWaitTime time.Duration
// NewConnsCount is the cumulative number of connections created by the pool.
NewConnsCount int64
// MaxIdleDestroyCount is the cumulative number of connections closed because
// they exceeded MaxConnIdleTime.
MaxIdleDestroyCount int64
// MaxLifetimeDestroyCount is the cumulative number of connections closed
// because they exceeded MaxConnLifetime.
MaxLifetimeDestroyCount int64
}
PoolStats is a detached point-in-time snapshot of connection pool statistics.
Counter fields are cumulative for the lifetime of the pool.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
extra
|
|
|
otelxpg
module
|
|
|
slogxpg
module
|
|
|
topology
|
|
|
cluster
Package cluster provides primary/replica routing for PostgreSQL connection pools.
|
Package cluster provides primary/replica routing for PostgreSQL connection pools. |
|
shard
Package shard provides application-level routing across PostgreSQL clusters.
|
Package shard provides application-level routing across PostgreSQL clusters. |
|
shard/resolver
Package resolver provides routing strategies for shard.Topology.
|
Package resolver provides routing strategies for shard.Topology. |