CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-jackc-pgx-v5

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.

Overview
Eval results
Files

pgconn.mddocs/advanced/

Low-Level Connection (pgconn)

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

import "github.com/jackc/pgx/v5/pgconn"

Establishing Connections

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)

Parsing Configuration

func ParseConfig(connString string) (*Config, error)
func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error)

Config

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() *Config

FallbackConfig

type FallbackConfig struct {
    Host      string
    Port      uint16
    TLSConfig *tls.Config
}

PgConn Methods

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{})

Executing Queries

Simple Protocol (multiple queries)

func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader

Extended Protocol (single query, with parameters)

func (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
) *ResultReader

Execute Prepared Statement

func (pgConn *PgConn) ExecPrepared(
    ctx context.Context,
    stmtName string,
    paramValues [][]byte,
    paramFormats []int16,
    resultFormats []int16,
) *ResultReader

Batch Execution

func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader

Prepared Statements

func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error)
func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error

COPY

func (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)

LISTEN/NOTIFY

func (pgConn *PgConn) WaitForNotification(ctx context.Context) error

The OnNotification callback on Config is called when a notification is received.

Cancel Request

func (pgConn *PgConn) CancelRequest(ctx context.Context) error

Batch (pgconn level)

type 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)

ResultReader

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() *Result

MultiResultReader

type MultiResultReader struct{ /* unexported */ }

func (mrr *MultiResultReader) NextResult() bool
func (mrr *MultiResultReader) ResultReader() *ResultReader
func (mrr *MultiResultReader) ReadAll() ([]*Result, error)
func (mrr *MultiResultReader) Close() error

Result

type Result struct {
    FieldDescriptions []FieldDescription
    Rows              [][][]byte
    CommandTag        CommandTag
    Err               error
}

CommandTag

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() bool

FieldDescription

type FieldDescription struct {
    Name                 string
    TableOID             uint32
    TableAttributeNumber uint16
    DataTypeOID          uint32
    DataTypeSize         int16
    TypeModifier         int32
    Format               int16
}

StatementDescription

type StatementDescription struct {
    Name      string
    SQL       string
    ParamOIDs []uint32
    Fields    []FieldDescription
}

PgError

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) *PgError

Notice

type Notice PgError  // server notice (distinct from LISTEN/NOTIFY)

Notification

type Notification struct {
    PID     uint32
    Channel string
    Payload string
}

HijackedConn

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)

SyncConn

func (pgConn *PgConn) SyncConn(ctx context.Context) error

Prepare the underlying net.Conn for direct use. Call before Conn() or Hijack().

EscapeString

func (pgConn *PgConn) EscapeString(s string) (string, error)

Escape for SQL interpolation. Requires standard_conforming_strings=on and client_encoding=UTF8.

ReceiveMessage

func (pgConn *PgConn) ReceiveMessage(ctx context.Context) (pgproto3.BackendMessage, error)

Low-level raw message receive. Requires the connection to be idle.

Context Cancellation Handlers

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()

Error/Helper Functions

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) error

Target Session Attribute Validators

func 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) error

Use as ValidateConnect in Config for HA/read-replica setups.

GSS (Kerberos) Authentication

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)

Function Types

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) error

Error Types

type 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() error

Package: pgconn/ctxwatch

import "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@5.8.0

docs

advanced

pgconn.md

pipeline-mode.md

wire-protocol.md

batch.md

common-patterns.md

connection-pool.md

copy.md

database-sql.md

direct-connection.md

index.md

querying.md

testing.md

tracing.md

transactions.md

tile.json