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

direct-connection.mddocs/

Connection Management

Overview

pgx.Conn is the primary connection handle. It is not safe for concurrent use — use pgxpool.Pool for concurrent applications. Connections are established using connection strings (URL or keyword/value format) or ConnConfig structs.

Import

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

Establishing Connections

func Connect(ctx context.Context, connString string) (*Conn, error)
func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error)
func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error)
  • Connect — fastest path; parses and connects in one call.
  • ConnectConfig — use when you need to modify config fields not exposed in the connection string (e.g., Tracer).
  • ConnectWithOptions — like Connect but accepts ParseConfigOptions (e.g., GetSSLPassword).
// URL format
conn, err := pgx.Connect(ctx, "postgres://user:pass@localhost:5432/mydb?sslmode=disable")

// Keyword/value format
conn, err := pgx.Connect(ctx, "host=localhost port=5432 user=pgx password=secret dbname=mydb sslmode=disable")

// Via config (allows setting tracer, query mode, etc.)
config, err := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
config.Tracer = myTracer
config.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
conn, err := pgx.ConnectConfig(ctx, config)

Parsing Configuration

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

ParseConfig understands the following environment variables (same as libpq): PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD, PGPASSFILE, PGSERVICE, PGSERVICEFILE, PGSSLMODE, PGSSLCERT, PGSSLKEY, PGSSLROOTCERT, PGSSLPASSWORD, PGOPTIONS, PGAPPNAME, PGCONNECT_TIMEOUT, PGTARGETSESSIONATTRS, PGTZ

Multiple hosts for HA:

conn, err := pgx.Connect(ctx, "postgres://user:pass@host1:5432,host2:5432/mydb")

ConnConfig

type ConnConfig struct {
    pgconn.Config                    // embedded low-level config

    Tracer                  QueryTracer   // query/batch/copy/prepare/connect tracer
    StatementCacheCapacity  int           // default 512
    DescriptionCacheCapacity int          // default 512
    DefaultQueryExecMode    QueryExecMode // default QueryExecModeCacheStatement
}

func (cc *ConnConfig) Copy() *ConnConfig
func (cc *ConnConfig) ConnString() string

The embedded pgconn.Config fields include: Host, Port, Database, User, Password, TLSConfig, ConnectTimeout, DialFunc, LookupFunc, RuntimeParams, OnNotice, OnNotification, OnPgError, ValidateConnect, AfterConnect, BuildContextWatcherHandler.

Conn Methods

func (c *Conn) Close(ctx context.Context) error
func (c *Conn) IsClosed() bool
func (c *Conn) Ping(ctx context.Context) error
func (c *Conn) Config() *ConnConfig
func (c *Conn) TypeMap() *pgtype.Map
func (c *Conn) PgConn() *pgconn.PgConn

Prepared Statements

pgx automatically prepares and caches statements in the default QueryExecModeCacheStatement mode. Manual preparation is rarely needed.

func (c *Conn) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error)
func (c *Conn) Deallocate(ctx context.Context, name string) error
func (c *Conn) DeallocateAll(ctx context.Context) error
sd, err := conn.Prepare(ctx, "get_user", "SELECT id, name FROM users WHERE id = $1")
// Use name in subsequent queries
rows, err := conn.Query(ctx, "get_user", 42)

LISTEN/NOTIFY

func (c *Conn) WaitForNotification(ctx context.Context) (*pgconn.Notification, error)
type Notification struct {
    PID     uint32
    Channel string
    Payload string
}
_, err := conn.Exec(ctx, "LISTEN channelname")
notification, err := conn.WaitForNotification(ctx)
// notification.Channel, notification.Payload

Loading Custom Types

func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, error)
func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Type, error)

Supported types: array, composite, domain, enum, range, multirange types. Requires all dependent types to be already registered.

// Load and register a custom enum type
t, err := conn.LoadType(ctx, "my_enum")
conn.TypeMap().RegisterType(t)

// Load an array of a custom type
t2, err := conn.LoadType(ctx, "_my_enum") // underscore prefix = array type
conn.TypeMap().RegisterType(t2)

// Load multiple types at once (handles dependencies automatically)
types, err := conn.LoadTypes(ctx, []string{"foo", "_foo", "bar", "_bar"})
for _, t := range types {
    conn.TypeMap().RegisterType(t)
}

ParseConfigOptions

type ParseConfigOptions struct {
    pgconn.ParseConfigOptions
}

// Embedded:
type ParseConfigOptions struct {
    GetSSLPassword GetSSLPasswordFunc
}

type GetSSLPasswordFunc func(ctx context.Context) string

Connection String Parameters

Beyond standard libpq parameters, pgx accepts:

  • default_query_exec_mode: "cache_statement" | "cache_describe" | "describe_exec" | "exec" | "simple_protocol"
  • statement_cache_capacity: integer (default 512)
  • description_cache_capacity: integer (default 512)

For pgxpool additional parameters, see Connection Pool.

Install with Tessl CLI

npx tessl i tessl/golang-github-com-jackc-pgx-v5@5.8.0

docs

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