wpgx

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 23 Imported by: 16

README

Wrapped pgx

Wrapped pgx is a simple wrap on the PostgreSQL driver library pgx. It is used by sqlc, providing telementry for generated code.

Components

  • Pool: a wrapper of pgxpool.Pool. It manages a set of connection pools, including a primary pool and a set of replica pools. We assume replica pools are heterogeneous read-only replicas, meaning some replicas can be a partial copy of the primary database, using logical replication.
  • WConn: a connection wrapper, implementing "WGConn".
  • WTx: a transaction wrapper, implementing "WGConn".
  • TestSuite: a comprehensive testing framework for PostgreSQL database tests.

Database timeouts

A database timeout bounds how long a statement holds a database connection, not how long it waits for one. sqlc generates wpgx.WithDBTimeout(ctx, name, T) for each query's timeout option; hand-written code can do the same:

ctx = wpgx.WithDBTimeout(ctx, "GetBook", 250*time.Millisecond)
row := pool.WConn().WQueryRow(ctx, "GetBook", sql, id)
  • On a pool connection the statement first waits for a connection, at most the larger of T and the pool's AcquireTimeout (default 2s). A statement in a transaction already has its connection.
  • T then starts and lasts until the connection is free again: Exec or CopyFrom returns, Row.Scan returns, or the Rows are read to the end or closed. Reading rows counts against T.
  • The context's own deadline and cancellation always apply. The wait includes the BeforeAcquire hook, which should return promptly once its context ends.
  • Rows already received before T expires can still be read; the statement's context reports the expiry and wpgx_timeout_total counts it.
  • An expired wait matches wpgx.ErrAcquireTimeout and an expired T matches wpgx.ErrDBTimeout; both also match context.DeadlineExceeded.
  • Rows returned under a database timeout have a Context() context.Context method returning the statement's context. wpgx.StatementErr(ctx, err) marks a deadline error from that context with ErrDBTimeout, and for a nil err reports whether the database timeout expired (finishing the rows cancels the context; that is not an error).
  • The timeout applies only to operations named name; nested statements with other names are not affected. Without it, operations behave as before.

Pool settings (also on read replicas; environment names with the default postgres prefix):

Field Environment Default Meaning
AcquireTimeout POSTGRES_ACQUIRETIMEOUT 2s shortest wait for a connection; zero means the default
MaxAcquireWaiters POSTGRES_MAXACQUIREWAITERS 0 statements that may wait at once; more fail with ErrTooManyAcquireWaiters; zero means no cap

Metrics for statements with a database timeout (existing metrics are unchanged; wpgx_latency_milliseconds still covers the wait):

  • wpgx_acquire_wait_milliseconds{app,replica}: time waited for a connection.
  • wpgx_db_latency_milliseconds{app,op,replica}: time the connection was held.
  • wpgx_timeout_total{app,op,replica,phase}: expired budgets, phase is acquire (waiting for a connection) or db (expired before the statement finished).
  • wpgx_conn_pool{op=...} adds acquire_waiting (statements waiting now) and the cumulative acquire_rejected_count, empty_acquire_count, empty_acquire_wait_seconds, canceled_acquire_count and new_conns_count.
  • Spans record the wait as wpgx.acquire_wait_ms.

Testing

This project includes a powerful test suite framework that supports two testing modes:

1. Direct Connection Mode (Traditional)

Connect to an existing PostgreSQL instance:

# Start PostgreSQL
make docker-postgres-start

# Run tests
make test

# Stop PostgreSQL
make docker-postgres-stop

Automatically manages PostgreSQL containers using testcontainers-go:

# Run tests with testcontainers (no manual setup needed!)
make test-container

Benefits:

  • ✅ No manual PostgreSQL setup required
  • ✅ Automatic container lifecycle management
  • ✅ Perfect test isolation
  • ✅ Works seamlessly in CI/CD (GitHub Actions, etc.)
  • ✅ Only requires Docker to be running

PostgreSQL version: testsuite.NewWPgxTestSuiteTcDefault starts postgres:14.5 (testsuite.DefaultPostgresImage). Test against the major version your production database runs:

testsuite.NewWPgxTestSuiteTcDefault(tables, testsuite.WithPostgresImage("postgres:18.6"))
Environment Variables
CI/CD Integration

Two GitHub Actions workflows are provided:

  1. test-with-containers.yml - Uses testcontainers (recommended)
  2. go.yml - Uses GitHub Actions services (traditional)

For more details, see the testsuite package documentation.

Documentation

Index

Constants

View Source
const (
	DefaultEnvPrefix = "postgres"
	AppNameLengthMax = 32
)
View Source
const DefaultAcquireTimeout = 2 * time.Second

DefaultAcquireTimeout is the AcquireTimeout of a pool configured with zero.

View Source
const (
	// ReservedReplicaNamePrimary is the name of the primary replica.
	ReservedReplicaNamePrimary = "primary"
)

Variables

View Source
var (
	// ErrAcquireTimeout is matched by the error of a statement run with a
	// database timeout that ran out of time waiting for a pooled connection.
	// Such an error also matches context.DeadlineExceeded.
	ErrAcquireTimeout = errors.New("wpgx: timed out waiting for a database connection")
	// ErrDBTimeout is matched by the error of a statement that exceeded its
	// database timeout. Such an error also matches context.DeadlineExceeded.
	ErrDBTimeout = errors.New("wpgx: database timeout exceeded")
	// ErrTooManyAcquireWaiters is returned by a statement run with a database
	// timeout when MaxAcquireWaiters statements already wait for a connection.
	ErrTooManyAcquireWaiters = errors.New("wpgx: too many statements waiting for a database connection")
)
View Source
var (
	// ErrReplicaNotFound is the error when the replica is not found.
	ErrReplicaNotFound = fmt.Errorf("replica not found")
)

Functions

func StatementErr added in v0.6.0

func StatementErr(ctx context.Context, err error) error

StatementErr returns the error to report for work done under @p ctx, a statement context (Rows.Context under WithDBTimeout) or one derived from it, that ended with @p err:

  • a non-nil @p err, also matching ErrDBTimeout when it is the deadline of the statement's database timeout;
  • for a nil @p err, an error matching ErrDBTimeout and context.DeadlineExceeded if that database timeout has expired, and nil otherwise. Finishing the rows cancels the statement context; that is not an error.

For example, a row visitor checks StatementErr(ctx, ctx.Err()), and a reader that stopped early checks StatementErr(ctx, rows.Err()) after closing rows.

func WithDBTimeout added in v0.6.0

func WithDBTimeout(ctx context.Context, name string, timeout time.Duration) context.Context

WithDBTimeout returns a copy of @p ctx that gives the statement named @p name a database timeout. A WConn or WTx operation with that name and context then runs as follows; operations with another name are not affected.

  • On a pool connection (WConn), the statement first waits for a connection, at most the larger of @p timeout and the pool's AcquireTimeout.
  • @p timeout then starts once the statement has a connection, or at the call inside a transaction (WTx), and lasts until the connection is free again: when Exec or CopyFrom returns, when Row.Scan returns, or when Rows are read to the end or closed.

Both bounds also end with @p ctx, whose deadline and cancellation always apply. Errors from an expired bound match ErrAcquireTimeout or ErrDBTimeout, and context.DeadlineExceeded. Rows returned under a database timeout have a Context method that returns the statement's context.

A non-positive @p timeout returns @p ctx unchanged.

Types

type Config

type Config struct {
	Username        string        `default:"postgres"`
	Password        string        `default:"my-secret"`
	Host            string        `default:"localhost"`
	Port            int           `default:"5432"`
	DBName          string        `default:"wpgx_test_db"`
	MaxConns        int32         `default:"20"`
	MinConns        int32         `default:"0"`
	MinIdleConns    int32         `default:"0"`
	MaxConnLifetime time.Duration `default:"6h"`
	MaxConnIdleTime time.Duration `default:"1m"`
	// AcquireTimeout bounds how long a statement run with a database timeout
	// (see WithDBTimeout) waits for a pooled connection: it waits at most the
	// larger of AcquireTimeout and its own database timeout, and never past
	// its context. Zero means DefaultAcquireTimeout. Other operations wait
	// within their context only. The wait includes the BeforeAcquire hook,
	// which should return promptly once its context ends: a connection it
	// accepts after the wait ended is released and the statement fails.
	AcquireTimeout time.Duration `default:"2s"`
	// MaxAcquireWaiters caps how many statements run with a database timeout
	// may wait for a pooled connection at the same time. A statement beyond
	// the cap fails at once with ErrTooManyAcquireWaiters. The count includes
	// statements that are taking an idle connection, so set it well above
	// MaxConns. Zero means no cap.
	MaxAcquireWaiters int32 `default:"0"`
	// AfterConnect is called once for each new connection, before it is added to
	// the pool; a returned error discards the connection. Use it for setup that
	// lasts for the connection's lifetime, such as registering types on
	// conn.TypeMap(): with IsProxy, pgx encodes a parameter only when its Go type
	// maps to a PostgreSQL type. Read replicas have their own AfterConnect.
	AfterConnect func(context.Context, *pgx.Conn) error `ignored:"true"`
	// BeforeAcquire is a function that is called before acquiring a connection.
	BeforeAcquire func(context.Context, *pgx.Conn) bool `ignored:"true"`
	IsProxy       bool                                  `default:"false"`
	SSLMode       string                                `default:"disable"`

	EnablePrometheus bool   `default:"true"`
	EnableTracing    bool   `default:"true"`
	AppName          string `required:"true"`

	// ReplicaConfigPrefixes is a list of replica configuration prefixes. They will
	// be used to create ReadReplicas by using envconfig to parse them.
	ReplicaPrefixes []string `default:""`
	// ReadReplicas is a list of read replicas, parsed from ReplicaNames.
	ReadReplicas []ReadReplicaConfig `ignored:"true"`
}

Config is the configuration for the WPgx. Note: for backward compatibility, connection settings of the primary instance are kept in the root Config, creating a bit code duplication with ReadReplicaConfig.

func ConfigFromEnv

func ConfigFromEnv() *Config

func ConfigFromEnvPrefix

func ConfigFromEnvPrefix(prefix string) *Config

func (*Config) String

func (c *Config) String() string

func (*Config) Valid

func (c *Config) Valid() error

type Pool

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

Pool is the wrapped pgx pool that registers Prometheus.

func NewPool

func NewPool(ctx context.Context, config *Config) (*Pool, error)

NewPool creates a new Pool with the given context and config. The context is only used while creating the underlying pgx pools; canceling it later does not close the Pool, call Close for that.

func (*Pool) Close

func (p *Pool) Close()

Close closes all pools, spawned goroutines, and cancels the context.

func (*Pool) MustReplicaPool added in v0.3.0

func (p *Pool) MustReplicaPool(name ReplicaName) *pgxpool.Pool

MustReplicaPool returns the replica pool by name, panics if not found.

func (*Pool) Ping

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

Ping pings all the instances in the pool, returns the first error encountered.

func (*Pool) PingPrimary added in v0.3.0

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

PingPrimary pings the primary instance in the pool.

func (*Pool) RawPool

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

RawPool returns the raw primary pgx pool. Deprecated: For backward compatibility only, use RawPrimaryPool instead.

func (*Pool) RawPrimaryPool added in v0.3.0

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

RawPrimaryPool returns the raw primary pgx pool.

func (*Pool) ReplicaPool added in v0.3.0

func (p *Pool) ReplicaPool(name ReplicaName) (pp *pgxpool.Pool, ok bool)

ReplicaPool returns the replica pool by name.

func (*Pool) ReplicaPools added in v0.3.0

func (p *Pool) ReplicaPools() map[ReplicaName]*pgxpool.Pool

RawReplicaPools returns the raw replica pgx pools. NOTE: due to go's lack of constant qualifier, the returned map should be treated as read-only.

func (*Pool) Transact

func (p *Pool) Transact(ctx context.Context, txOptions pgx.TxOptions, fn TxFunc) (resp interface{}, err error)

Transact is a wrapper of pgx.Transaction It acquires a connection from the Pool and starts a transaction with pgx.TxOptions determining the transaction mode. The context will be used when executing the transaction control statements (BEGIN, ROLLBACK, and COMMIT), and when if tracing is enabled, the context with transaction span will be passed down to @p fn. If @p fn returns nil, the transaction is committed, unless @p fn already committed it with tx.Commit.

func (*Pool) WConn

func (p *Pool) WConn() *WConn

WConn returns a wrapped connection for the primary instance.

func (*Pool) WQuerier added in v0.3.1

func (p *Pool) WQuerier(name *ReplicaName) (WQuerier, error)

WQuerier returns a wrapped querier based on the given replica name. When the name is nil, it returns the primary connection.

type PostExecFunc

type PostExecFunc = func() error

PostExecFunc is the function that must be ran after a successful CRUD. NOTE: context should have been captured into the function.

type ReadReplicaConfig added in v0.3.0

type ReadReplicaConfig struct {
	Name            ReplicaName   `required:"true"`
	Username        string        `default:"postgres"`
	Password        string        `default:"my-secret"`
	Host            string        `default:"localhost"`
	Port            int           `default:"5432"`
	DBName          string        `default:"wpgx_test_db"`
	MaxConns        int32         `default:"20"`
	MinConns        int32         `default:"0"`
	MinIdleConns    int32         `default:"0"`
	MaxConnLifetime time.Duration `default:"6h"`
	MaxConnIdleTime time.Duration `default:"1m"`
	// AcquireTimeout and MaxAcquireWaiters apply to this replica's pool, see Config.
	AcquireTimeout    time.Duration `default:"2s"`
	MaxAcquireWaiters int32         `default:"0"`
	// AfterConnect is called once for each new connection, see Config.AfterConnect.
	AfterConnect func(context.Context, *pgx.Conn) error `ignored:"true"`
	// BeforeAcquire is a function that is called before acquiring a connection.
	BeforeAcquire func(context.Context, *pgx.Conn) bool `ignored:"true"`
	IsProxy       bool                                  `default:"false"`
	Broken        bool                                  `default:"false"`
	SSLMode       string                                `default:"disable"`
}

type ReplicaName added in v0.3.0

type ReplicaName string

ReplicaName is the name of the replica instance.

type TxFunc

type TxFunc = func(ctx context.Context, tx *WTx) (any, error)

TxFunc is the body of a transaction. ctx must be used to generate proper tracing spans. If not, you might see incorrect parallel spans.

type WConn

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

func (*WConn) CountIntent added in v0.2.0

func (c *WConn) CountIntent(name string)

func (*WConn) PostExec

func (c *WConn) PostExec(fn PostExecFunc) error

func (*WConn) WCopyFrom added in v0.0.3

func (c *WConn) WCopyFrom(
	ctx context.Context, name string, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (n int64, err error)

func (*WConn) WExec

func (c *WConn) WExec(ctx context.Context, name string, unprepared string, args ...interface{}) (cmd pgconn.CommandTag, err error)

func (*WConn) WQuery

func (c *WConn) WQuery(ctx context.Context, name string, unprepared string, args ...interface{}) (pgx.Rows, error)

func (*WConn) WQueryRow

func (c *WConn) WQueryRow(ctx context.Context, name string, unprepared string, args ...interface{}) pgx.Row

type WCopyFromer added in v0.3.0

type WCopyFromer interface {
	WCopyFrom(
		ctx context.Context, name string, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}

WCopyFromer is the abstraction of connections that can use PostgreSQL's copyfrom.

type WExecer added in v0.3.0

type WExecer interface {
	// WExec is used to run a CRUD operation.
	WExec(
		ctx context.Context, name string, unprepared string, args ...interface{}) (pgconn.CommandTag, error)
	// PostExec is used to run a function after a successful CRUD, like invalidating a cache.
	PostExec(f PostExecFunc) error
}

WExecer is the abstraction of connections that can execute mutations.

type WGConn

type WGConn interface {
	WQuerier
	WExecer
	WCopyFromer
}

WGConn is the abstraction over wrapped connections and transactions.

type WQuerier added in v0.3.0

type WQuerier interface {
	WQuery(
		ctx context.Context, name string, unprepared string, args ...interface{}) (pgx.Rows, error)
	WQueryRow(
		ctx context.Context, name string, unprepared string, args ...interface{}) pgx.Row
	// CountIntent is used to count the number of query intents.
	CountIntent(name string)
}

WQuerier is the abstraction of connections that are read-only.

type WTx

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

WTx is a wrapped pgx.Tx. The main reason is to overwrite the PostExec method that run all of them until the transaction is successfully committed.

func (*WTx) Commit

func (t *WTx) Commit(ctx context.Context) error

func (*WTx) CountIntent added in v0.2.0

func (t *WTx) CountIntent(name string)

func (*WTx) PostExec

func (t *WTx) PostExec(f PostExecFunc) error

func (*WTx) Rollback

func (t *WTx) Rollback(ctx context.Context) error

func (*WTx) WCopyFrom added in v0.0.3

func (t *WTx) WCopyFrom(
	ctx context.Context, name string, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (n int64, err error)

func (*WTx) WExec

func (t *WTx) WExec(ctx context.Context, name string, unprepared string, args ...interface{}) (cmd pgconn.CommandTag, err error)

func (*WTx) WQuery

func (t *WTx) WQuery(ctx context.Context, name string, unprepared string, args ...interface{}) (pgx.Rows, error)

func (*WTx) WQueryRow

func (t *WTx) WQueryRow(ctx context.Context, name string, unprepared string, args ...interface{}) pgx.Row

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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