pgx is a pure Go driver and toolkit for PostgreSQL providing a native high-performance interface with PostgreSQL-specific features plus a database/sql compatibility adapter.
—
pgconn provides low-level PostgreSQL connection handling at roughly the level of libpq. It operates on raw bytes and exposes the full extended query protocol, pipeline mode, and COPY support.
import "github.com/jackc/pgx/v5/pgconn"func Connect(ctx context.Context, connString string) (*PgConn, error)
func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error)
func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error)
func Construct(hc *HijackedConn) (*PgConn, error)func ParseConfig(connString string) (*Config, error)
func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error)type Config struct {
Host string
Port uint16
Database string
User string
Password string
TLSConfig *tls.Config
ConnectTimeout time.Duration
DialFunc DialFunc
LookupFunc LookupFunc
BuildFrontend BuildFrontendFunc
// BuildContextWatcherHandler creates a ContextWatcherHandler for a connection.
BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler
RuntimeParams map[string]string // e.g. {"search_path": "myschema", "application_name": "myapp"}
KerberosSrvName string
KerberosSpn string
Fallbacks []*FallbackConfig
SSLNegotiation string // "postgres" or "direct"
AfterNetConnect func(ctx context.Context, config *Config, conn net.Conn) (net.Conn, error)
ValidateConnect ValidateConnectFunc
AfterConnect AfterConnectFunc
OnNotice NoticeHandler
OnNotification NotificationHandler
OnPgError PgErrorHandler
}
func (c *Config) Copy() *Configtype FallbackConfig struct {
Host string
Port uint16
TLSConfig *tls.Config
}func (pgConn *PgConn) Close(ctx context.Context) error
func (pgConn *PgConn) IsClosed() bool
func (pgConn *PgConn) IsBusy() bool
func (pgConn *PgConn) Ping(ctx context.Context) error
func (pgConn *PgConn) CheckConn() error // deprecated: use Ping
func (pgConn *PgConn) PID() uint32
func (pgConn *PgConn) SecretKey() uint32
func (pgConn *PgConn) TxStatus() byte // 'I'=idle, 'T'=in tx, 'E'=failed tx
func (pgConn *PgConn) ParameterStatus(key string) string
func (pgConn *PgConn) Conn() net.Conn
func (pgConn *PgConn) Frontend() *pgproto3.Frontend
func (pgConn *PgConn) CustomData() map[string]any
func (pgConn *PgConn) CleanupDone() chan (struct{})func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReaderfunc (pgConn *PgConn) ExecParams(
ctx context.Context,
sql string,
paramValues [][]byte,
paramOIDs []uint32, // nil = server infers; 0 element = server infers for that param
paramFormats []int16, // nil = all text; len 1 = all same format
resultFormats []int16, // nil = all text; len 1 = all same format
) *ResultReaderfunc (pgConn *PgConn) ExecPrepared(
ctx context.Context,
stmtName string,
paramValues [][]byte,
paramFormats []int16,
resultFormats []int16,
) *ResultReaderfunc (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReaderfunc (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error)
func (pgConn *PgConn) Deallocate(ctx context.Context, name string) errorfunc (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (CommandTag, error)
func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (CommandTag, error)func (pgConn *PgConn) WaitForNotification(ctx context.Context) errorThe OnNotification callback on Config is called when a notification is received.
func (pgConn *PgConn) CancelRequest(ctx context.Context) errortype Batch struct{ /* unexported */ }
func (batch *Batch) ExecParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16)
func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16)type ResultReader struct{ /* unexported */ }
func (rr *ResultReader) Close() (CommandTag, error)
func (rr *ResultReader) FieldDescriptions() []FieldDescription
func (rr *ResultReader) NextRow() bool
func (rr *ResultReader) Values() [][]byte
func (rr *ResultReader) Read() *Resulttype MultiResultReader struct{ /* unexported */ }
func (mrr *MultiResultReader) NextResult() bool
func (mrr *MultiResultReader) ResultReader() *ResultReader
func (mrr *MultiResultReader) ReadAll() ([]*Result, error)
func (mrr *MultiResultReader) Close() errortype Result struct {
FieldDescriptions []FieldDescription
Rows [][][]byte
CommandTag CommandTag
Err error
}type CommandTag struct{ /* unexported */ }
func NewCommandTag(s string) CommandTag
func (ct CommandTag) String() string
func (ct CommandTag) RowsAffected() int64
func (ct CommandTag) Insert() bool
func (ct CommandTag) Update() bool
func (ct CommandTag) Delete() bool
func (ct CommandTag) Select() booltype FieldDescription struct {
Name string
TableOID uint32
TableAttributeNumber uint16
DataTypeOID uint32
DataTypeSize int16
TypeModifier int32
Format int16
}type StatementDescription struct {
Name string
SQL string
ParamOIDs []uint32
Fields []FieldDescription
}type PgError struct {
Severity string
SeverityUnlocalized string
Code string
Message string
Detail string
Hint string
Position int32
InternalPosition int32
InternalQuery string
Where string
SchemaName string
TableName string
ColumnName string
DataTypeName string
ConstraintName string
File string
Line int32
Routine string
}
func (pe *PgError) Error() string
func (pe *PgError) SQLState() string
func ErrorResponseToPgError(msg *pgproto3.ErrorResponse) *PgErrortype Notice PgError // server notice (distinct from LISTEN/NOTIFY)type Notification struct {
PID uint32
Channel string
Payload string
}Used to extract raw connection data for custom handling (e.g. proxies).
type HijackedConn struct {
Conn net.Conn
PID uint32
SecretKey uint32
ParameterStatuses map[string]string
TxStatus byte
Frontend *pgproto3.Frontend
Config *Config
CustomData map[string]any
}
func (pgConn *PgConn) Hijack() (*HijackedConn, error)
func Construct(hc *HijackedConn) (*PgConn, error)func (pgConn *PgConn) SyncConn(ctx context.Context) errorPrepare the underlying net.Conn for direct use. Call before Conn() or Hijack().
func (pgConn *PgConn) EscapeString(s string) (string, error)Escape for SQL interpolation. Requires standard_conforming_strings=on and client_encoding=UTF8.
func (pgConn *PgConn) ReceiveMessage(ctx context.Context) (pgproto3.BackendMessage, error)Low-level raw message receive. Requires the connection to be idle.
type CancelRequestContextWatcherHandler struct {
Conn *PgConn
CancelRequestDelay time.Duration
DeadlineDelay time.Duration
}
func (h *CancelRequestContextWatcherHandler) HandleCancel(context.Context)
func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel()
type DeadlineContextWatcherHandler struct {
Conn net.Conn
DeadlineDelay time.Duration
}
func (h *DeadlineContextWatcherHandler) HandleCancel(ctx context.Context)
func (h *DeadlineContextWatcherHandler) HandleUnwatchAfterCancel()func SafeToRetry(err error) bool
func Timeout(err error) bool
func NetworkAddress(host string, port uint16) (network, address string)
func RegisterGSSProvider(newGSSArg NewGSSFunc)
func NewParseConfigError(conn, msg string, err error) errorfunc ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error
func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) errorUse as ValidateConnect in Config for HA/read-replica setups.
type GSS interface {
GetInitToken(host, service string) ([]byte, error)
GetInitTokenFromSPN(spn string) ([]byte, error)
Continue(inToken []byte) (done bool, outToken []byte, err error)
}
type NewGSSFunc func() (GSS, error)
func RegisterGSSProvider(newGSSArg NewGSSFunc)type AfterConnectFunc func(ctx context.Context, pgconn *PgConn) error
type BuildFrontendFunc func(r io.Reader, w io.Writer) *pgproto3.Frontend
type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
type GetSSLPasswordFunc func(ctx context.Context) string
type LookupFunc func(ctx context.Context, host string) (addrs []string, err error)
type NoticeHandler func(*PgConn, *Notice)
type NotificationHandler func(*PgConn, *Notification)
type PgErrorHandler func(*PgConn, *PgError) bool
type ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) errortype ConnectError struct {
Config *Config
}
func (e *ConnectError) Error() string
func (e *ConnectError) Unwrap() error
type ParseConfigError struct {
ConnString string
}
func (e *ParseConfigError) Error() string
func (e *ParseConfigError) Unwrap() error
type PrepareError struct {
ParseComplete bool
}
func (e *PrepareError) Error() string
func (e *PrepareError) Unwrap() error
type NotPreferredError struct{ /* unexported */ }
func (e *NotPreferredError) Error() string
func (e *NotPreferredError) SafeToRetry() bool
func (e *NotPreferredError) Unwrap() errorimport "github.com/jackc/pgx/v5/pgconn/ctxwatch"type Handler interface {
HandleCancel(canceledCtx context.Context)
HandleUnwatchAfterCancel()
}
type ContextWatcher struct{ /* unexported */ }
func NewContextWatcher(handler Handler) *ContextWatcher
func (cw *ContextWatcher) Watch(ctx context.Context)
func (cw *ContextWatcher) Unwatch()Used internally by pgconn to handle context cancellation. Can be used for custom connection types needing context cancellation support.
Install with Tessl CLI
npx tessl i tessl/golang-github-com-jackc-pgx-v5