Documentation
¶
Index ¶
- Constants
- Variables
- func StatementErr(ctx context.Context, err error) error
- func WithDBTimeout(ctx context.Context, name string, timeout time.Duration) context.Context
- type Config
- type Pool
- func (p *Pool) Close()
- func (p *Pool) MustReplicaPool(name ReplicaName) *pgxpool.Pool
- func (p *Pool) Ping(ctx context.Context) error
- func (p *Pool) PingPrimary(ctx context.Context) error
- func (p *Pool) RawPool() *pgxpool.Pool
- func (p *Pool) RawPrimaryPool() *pgxpool.Pool
- func (p *Pool) ReplicaPool(name ReplicaName) (pp *pgxpool.Pool, ok bool)
- func (p *Pool) ReplicaPools() map[ReplicaName]*pgxpool.Pool
- func (p *Pool) Transact(ctx context.Context, txOptions pgx.TxOptions, fn TxFunc) (resp interface{}, err error)
- func (p *Pool) WConn() *WConn
- func (p *Pool) WQuerier(name *ReplicaName) (WQuerier, error)
- type PostExecFunc
- type ReadReplicaConfig
- type ReplicaName
- type TxFunc
- type WConn
- func (c *WConn) CountIntent(name string)
- func (c *WConn) PostExec(fn PostExecFunc) error
- func (c *WConn) WCopyFrom(ctx context.Context, name string, tableName pgx.Identifier, ...) (n int64, err error)
- func (c *WConn) WExec(ctx context.Context, name string, unprepared string, args ...interface{}) (cmd pgconn.CommandTag, err error)
- func (c *WConn) WQuery(ctx context.Context, name string, unprepared string, args ...interface{}) (pgx.Rows, error)
- func (c *WConn) WQueryRow(ctx context.Context, name string, unprepared string, args ...interface{}) pgx.Row
- type WCopyFromer
- type WExecer
- type WGConn
- type WQuerier
- type WTx
- func (t *WTx) Commit(ctx context.Context) error
- func (t *WTx) CountIntent(name string)
- func (t *WTx) PostExec(f PostExecFunc) error
- func (t *WTx) Rollback(ctx context.Context) error
- func (t *WTx) WCopyFrom(ctx context.Context, name string, tableName pgx.Identifier, ...) (n int64, err error)
- func (t *WTx) WExec(ctx context.Context, name string, unprepared string, args ...interface{}) (cmd pgconn.CommandTag, err error)
- func (t *WTx) WQuery(ctx context.Context, name string, unprepared string, args ...interface{}) (pgx.Rows, error)
- func (t *WTx) WQueryRow(ctx context.Context, name string, unprepared string, args ...interface{}) pgx.Row
Constants ¶
const ( DefaultEnvPrefix = "postgres" AppNameLengthMax = 32 )
const DefaultAcquireTimeout = 2 * time.Second
DefaultAcquireTimeout is the AcquireTimeout of a pool configured with zero.
const (
// ReservedReplicaNamePrimary is the name of the primary replica.
ReservedReplicaNamePrimary = "primary"
)
Variables ¶
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") )
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
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
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 ¶
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is the wrapped pgx pool that registers Prometheus.
func NewPool ¶
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) PingPrimary ¶ added in v0.3.0
PingPrimary pings the primary instance in the pool.
func (*Pool) RawPool ¶
RawPool returns the raw primary pgx pool. Deprecated: For backward compatibility only, use RawPrimaryPool instead.
func (*Pool) RawPrimaryPool ¶ added in v0.3.0
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.
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 ¶
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 (*WConn) PostExec ¶
func (c *WConn) PostExec(fn PostExecFunc) error
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) CountIntent ¶ added in v0.2.0
func (*WTx) PostExec ¶
func (t *WTx) PostExec(f PostExecFunc) error