Involved Source Filesbatch_results.goconn.go Package pgxpool is a concurrency-safe connection pool for pgx.
pgxpool implements a nearly identical interface to pgx connections.
Creating a Pool
The primary way of creating a pool is with [pgxpool.New]:
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
The database connection string can be in URL or keyword/value format. PostgreSQL settings, pgx settings, and pool settings can be
specified here. In addition, a config struct can be created by [ParseConfig].
config, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
// ...
}
config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
// do something with every new connection
}
pool, err := pgxpool.NewWithConfig(context.Background(), config)
A pool returns without waiting for any connections to be established. Acquire a connection immediately after creating
the pool to check if a connection can successfully be established.pool.gorows.gostat.gotracer.gotx.go
Package-Level Type Names (total 18, in which 11 are exported)
/* sort exporteds by: | */
AcquireTracer traces Acquire. TraceAcquireEnd is called when a connection has been acquired. TraceAcquireStart is called at the beginning of Acquire.
The returned context is used for the rest of the call and will be passed to the TraceAcquireEnd.
*github.com/jackc/pgx/v5/tracelog.TraceLog
Config is the configuration struct for creating a pool. It must be created by [ParseConfig] and then it can be
modified. AfterConnect is called after a connection is established, but before it is added to the pool. AfterRelease is called after a connection is released, but before it is returned to the pool. It must return true to
return the connection to the pool or false to destroy the connection. BeforeAcquire is called before a connection is acquired from the pool. It must return true to allow the
acquisition or false to indicate that the connection should be destroyed and a different connection should be
acquired.
Deprecated: Use PrepareConn instead. If both PrepareConn and BeforeAcquire are set, PrepareConn will take
precedence, ignoring BeforeAcquire. BeforeClose is called right before a connection is closed and removed from the pool. BeforeConnect is called before a new connection is made. It is passed a copy of the underlying pgx.ConnConfig and
will not impact any existing open connections.ConnConfig*pgx.ConnConfig HealthCheckPeriod is the duration between checks of the health of idle connections. MaxConnIdleTime is the duration after which an idle connection will be automatically closed by the health check. MaxConnLifetime is the duration since creation after which a connection will be automatically closed. MaxConnLifetimeJitter is the duration after MaxConnLifetime to randomly decide to close a connection.
This helps prevent all connections from being closed at the exact same time, starving the pool. MaxConns is the maximum size of the pool. The default is the greater of 4 or runtime.NumCPU(). MinConns is the minimum size of the pool. After connection closes, the pool might dip below MinConns. A low
number of MinConns might mean the pool is empty after MaxConnLifetime until the health check has a chance
to create new connections. MinIdleConns is the minimum number of idle connections in the pool. You can increase this to ensure that
there are always idle connections available. This can help reduce tail latencies during request processing,
as you can avoid the latency of establishing a new connection while handling requests. It is superior
to MinConns for this purpose.
Similar to MinConns, the pool might temporarily dip below MinIdleConns after connection closes. PingTimeout is the maximum amount of time to wait for a connection to pong before considering it as unhealthy and
destroying it. If zero, the default is no timeout. PrepareConn is called before a connection is acquired from the pool. If this function returns true, the connection
is considered valid, otherwise the connection is destroyed. If the function returns a non-nil error, the instigating
query will fail with the returned error.
Specifically, this means that:
- If it returns true and a nil error, the query proceeds as normal.
- If it returns true and an error, the connection will be returned to the pool, and the instigating query will fail with the returned error.
- If it returns false, and an error, the connection will be destroyed, and the query will fail with the returned error.
- If it returns false and a nil error, the connection will be destroyed, and the instigating query will be retried on a new connection. ShouldPing is called after a connection is acquired from the pool. If it returns true, the connection is pinged to check for liveness.
If this func is not set, the default behavior is to ping connections that have been idle for at least 1 second. // Used to enforce created by ParseConfig rule. ConnString returns the connection string as parsed by pgxpool.ParseConfig into pgxpool.Config. Copy returns a deep copy of the config that is safe to use and modify.
The only exception is the tls.Config:
according to the tls.Config docs it must not be modified after creation.
func ParseConfig(connString string) (*Config, error)
func (*Config).Copy() *Config
func (*Pool).Config() *Config
func NewWithConfig(ctx context.Context, config *Config) (*Pool, error)
Pool allows for connection reuse.acquireTracerAcquireTracerafterConnectfunc(context.Context, *pgx.Conn) errorafterReleasefunc(*pgx.Conn) boolbeforeClosefunc(*pgx.Conn)beforeConnectfunc(context.Context, *pgx.ConnConfig) errorcloseChanchan struct{}closeOncesync.Onceconfig*ConfighealthCheckChanchan struct{}healthCheckMusync.MutexhealthCheckPeriodtime.DurationhealthCheckTimer*time.TimeridleDestroyCountint64lifetimeDestroyCountint64maxConnIdleTimetime.DurationmaxConnLifetimetime.DurationmaxConnLifetimeJittertime.DurationmaxConnsint32minConnsint32minIdleConnsint32 64 bit fields accessed with atomics must be at beginning of struct to guarantee alignment for certain 32-bit
architectures. See BUGS section of https://pkg.go.dev/sync/atomic and https://github.com/jackc/pgx/issues/1288.p*puddle.Pool[*connResource]pingTimeouttime.DurationprepareConnfunc(context.Context, *pgx.Conn) (bool, error)releaseTracerReleaseTracershouldPingfunc(context.Context, ShouldPingParams) bool Acquire returns a connection (*Conn) from the Pool AcquireAllIdle atomically acquires all currently idle connections. Its intended use is for health check and
keep-alive functionality. It does not update pool statistics. AcquireFunc acquires a *Conn and calls f with that *Conn. ctx will only affect the Acquire. It has no effect on the
call of f. The return value is either an error acquiring the *Conn or the return value of f. The *Conn is
automatically released after the call of f. Begin acquires a connection from the Pool and starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no
auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see BeginTx with TxOptions if transaction mode is required).
*pgxpool.Tx is returned, which implements the pgx.Tx interface.
Commit or Rollback must be called on the returned transaction to finalize the transaction block. BeginTx acquires a connection from the Pool and starts a transaction with pgx.TxOptions determining the transaction mode.
Unlike database/sql, the context only affects the begin command. i.e. there is no auto-rollback on context cancellation.
*pgxpool.Tx is returned, which implements the pgx.Tx interface.
Commit or Rollback must be called on the returned transaction to finalize the transaction block. Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned
to pool and closed. Config returns a copy of config that was used to initialize this pool.(*Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) Exec acquires a connection from the Pool and executes the given SQL.
SQL can be either a prepared statement name or an SQL string.
Arguments should be referenced positionally from the SQL string as $1, $2, etc.
The acquired connection is returned to the pool when the Exec function returns. Ping acquires a connection from the Pool and executes an empty sql statement against it.
If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned. Query acquires a connection and executes a query that returns pgx.Rows.
Arguments should be referenced positionally from the SQL string as $1, $2, etc.
See pgx.Rows documentation to close the returned Rows and return the acquired connection to the Pool.
If there is an error, the returned pgx.Rows will be returned in an error state.
If preferred, ignore the error returned from Query and handle errors using the returned pgx.Rows.
For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and
QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely
needed. See the documentation for those types for details. QueryRow acquires a connection and executes a query that is expected
to return at most one row (pgx.Row). Errors are deferred until pgx.Row's
Scan method is called. If the query selects no rows, pgx.Row's Scan will
return ErrNoRows. Otherwise, pgx.Row's Scan scans the first selected row
and discards the rest. The acquired connection is returned to the Pool when
pgx.Row's Scan method is called.
Arguments should be referenced positionally from the SQL string as $1, $2, etc.
For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and
QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely
needed. See the documentation for those types for details. Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would
disrupt all connections (such as a network interruption or a server state change).
It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned
to the pool.(*Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults Stat returns a pgxpool.Stat struct with a snapshot of Pool statistics.(*Pool) backgroundHealthCheck() checkConnsHealth will check all idle connections, destroy a connection if
it's idle or too old, and returns true if any were destroyed(*Pool) checkHealth()(*Pool) checkMinConns() error(*Pool) createIdleResources(parentCtx context.Context, targetResources int) error(*Pool) isExpired(res *puddle.Resource[*connResource]) bool(*Pool) triggerHealthCheck()
*Pool : database/sql/driver.Pinger
*Pool : go.pact.im/x/pgxprocess.database
func New(ctx context.Context, connString string) (*Pool, error)
func NewWithConfig(ctx context.Context, config *Config) (*Pool, error)
func AcquireTracer.TraceAcquireEnd(ctx context.Context, pool *Pool, data TraceAcquireEndData)
func AcquireTracer.TraceAcquireStart(ctx context.Context, pool *Pool, data TraceAcquireStartData) context.Context
func ReleaseTracer.TraceRelease(pool *Pool, data TraceReleaseData)
func github.com/jackc/pgx/v5/tracelog.(*TraceLog).TraceAcquireEnd(ctx context.Context, _ *Pool, data TraceAcquireEndData)
func github.com/jackc/pgx/v5/tracelog.(*TraceLog).TraceAcquireStart(ctx context.Context, _ *Pool, _ TraceAcquireStartData) context.Context
func github.com/jackc/pgx/v5/tracelog.(*TraceLog).TraceRelease(_ *Pool, data TraceReleaseData)
ReleaseTracer traces Release. TraceRelease is called at the beginning of Release.
*github.com/jackc/pgx/v5/tracelog.TraceLog
Stat is a snapshot of Pool statistics.idleDestroyCountint64lifetimeDestroyCountint64newConnsCountint64s*puddle.Stat AcquireCount returns the cumulative count of successful acquires from the pool. AcquireDuration returns the total duration of all successful acquires from
the pool. AcquiredConns returns the number of currently acquired connections in the pool. CanceledAcquireCount returns the cumulative count of acquires from the pool
that were canceled by a context. ConstructingConns returns the number of conns with construction in progress in
the pool. EmptyAcquireCount returns the cumulative count of successful acquires from the pool
that waited for a resource to be released or constructed because the pool was
empty. EmptyAcquireWaitTime returns the cumulative time waited for successful acquires
from the pool for a resource to be released or constructed because the pool was
empty. IdleConns returns the number of currently idle conns in the pool. MaxConns returns the maximum size of the pool. MaxIdleDestroyCount returns the cumulative count of connections destroyed because
they exceeded MaxConnIdleTime. MaxLifetimeDestroyCount returns the cumulative count of connections destroyed
because they exceeded MaxConnLifetime. NewConnsCount returns the cumulative count of new connections opened. TotalConns returns the total number of resources currently in the pool.
The value is the sum of ConstructingConns, AcquiredConns, and
IdleConns.
func (*Pool).Stat() *Stat
Tx represents a database transaction acquired from a Pool.c*Conntpgx.Tx Begin starts a pseudo nested transaction implemented with a savepoint. Commit commits the transaction and returns the associated connection back to the Pool. Commit will return an error
where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is otherwise safe to call multiple times. If
the commit fails with a rollback status (e.g. the transaction was already in a broken state) then ErrTxCommitRollback
will be returned.(*Tx) Conn() *pgx.Conn(*Tx) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)(*Tx) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)(*Tx) LargeObjects() pgx.LargeObjects Prepare creates a prepared statement with name and sql. If the name is empty,
an anonymous prepared statement will be used. sql can contain placeholders
for bound parameters. These placeholders are referenced positionally as $1, $2, etc.
Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same
name and sql arguments. This allows a code path to Prepare and Query/Exec without
needing to first check whether the statement has already been prepared.(*Tx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)(*Tx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row Rollback rolls back the transaction and returns the associated connection back to the Pool. Rollback will return
where an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is otherwise safe to call
multiple times. Hence, defer tx.Rollback() is safe even if tx.Commit() will be called first in a non-error condition.(*Tx) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
*Tx : github.com/jackc/pgx/v5.Tx
Package-Level Functions (total 3, all are exported)
New creates a new Pool. See [ParseConfig] for information on connString format.
NewWithConfig creates a new Pool. config must have been created by [ParseConfig].
ParseConfig builds a Config from connString. It parses connString with the same behavior as [pgx.ParseConfig] with the
addition of the following variables:
- pool_max_conns: integer greater than 0 (default 4)
- pool_min_conns: integer 0 or greater (default 0)
- pool_max_conn_lifetime: duration string (default 1 hour)
- pool_max_conn_idle_time: duration string (default 30 minutes)
- pool_health_check_period: duration string (default 1 minute)
- pool_max_conn_lifetime_jitter: duration string (default 0)
See Config for definitions of these arguments.
# Example Keyword/Value
user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m
# Example URL
postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca&pool_max_conns=10&pool_max_conn_lifetime=1h30m
Package-Level Variables (total 6, none are exported)