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.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

pgx v5

pgx is a pure Go driver and toolkit for PostgreSQL. It provides both a native high-performance PostgreSQL interface and a database/sql-compatible adapter. The native interface exposes PostgreSQL-specific features such as LISTEN/NOTIFY, COPY protocol, pipeline mode, batch queries, large objects, and a comprehensive type system.

Package Information

  • Module: github.com/jackc/pgx/v5
  • Package Type: Go module (golang)
  • Language: Go
  • Installation: go get github.com/jackc/pgx/v5
  • Documentation: https://pkg.go.dev/github.com/jackc/pgx/v5

Core Imports

import "github.com/jackc/pgx/v5"                    // main package
import "github.com/jackc/pgx/v5/pgxpool"             // connection pool
import "github.com/jackc/pgx/v5/pgconn"              // low-level connection
import "github.com/jackc/pgx/v5/pgtype"              // type system
import "github.com/jackc/pgx/v5/stdlib"              // database/sql adapter
import "github.com/jackc/pgx/v5/tracelog"            // logging tracer
import "github.com/jackc/pgx/v5/multitracer"         // combine tracers
import "github.com/jackc/pgx/v5/pgproto3"            // wire protocol
import "github.com/jackc/pgx/v5/pgtype/zeronull"     // zero-value ↔ NULL types
import "github.com/jackc/pgx/v5/pgconn/ctxwatch"     // context watcher
import "github.com/jackc/pgx/v5/log/testingadapter"  // test logger
import "github.com/jackc/pgx/v5/pgxtest"             // testing utilities

Quick Start

For Production Applications (Recommended)

Use pgxpool for concurrent applications:

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

pool, err := pgxpool.New(ctx, "postgres://user:pass@localhost/mydb")
if err != nil {
    log.Fatal(err)
}
defer pool.Close()

// Query
var name string
err = pool.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", 42).Scan(&name)

// Execute
_, err = pool.Exec(ctx, "UPDATE users SET status = $1 WHERE id = $2", "active", 42)

See: Connection Pool

For Single-Connection Use

Use pgx.Conn for scripts, CLIs, or single-goroutine applications:

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

conn, err := pgx.Connect(ctx, "postgres://user:pass@localhost/mydb")
if err != nil {
    log.Fatal(err)
}
defer conn.Close(ctx)

// Query with row collection
rows, _ := conn.Query(ctx, "SELECT id, name FROM users WHERE active = $1", true)
type User struct {
    ID   int64  `db:"id"`
    Name string `db:"name"`
}
users, err := pgx.CollectRows(rows, pgx.RowToStructByName[User])

See: Direct Connection

With database/sql

Use the stdlib adapter for compatibility with database/sql:

import _ "github.com/jackc/pgx/v5/stdlib"
import "database/sql"

db, err := sql.Open("pgx", "postgres://user:pass@localhost/mydb")
defer db.Close()

rows, err := db.Query("SELECT name FROM users WHERE id = $1", 42)

See: database/sql Adapter

Common Tasks Quick Reference

TaskPool MethodConn MethodSee
Execute non-SELECTpool.Exec(ctx, sql, args...)conn.Exec(ctx, sql, args...)Querying
Query multiple rowspool.Query(ctx, sql, args...)conn.Query(ctx, sql, args...)Querying
Query single rowpool.QueryRow(ctx, sql, args...)conn.QueryRow(ctx, sql, args...)Querying
Start transactionpool.Begin(ctx)conn.Begin(ctx)Transactions
Batch queriespool.SendBatch(ctx, batch)conn.SendBatch(ctx, batch)Batch
Bulk insertpool.CopyFrom(ctx, ...)conn.CopyFrom(ctx, ...)COPY

Architecture Decision: Pool vs Connection

Use pgxpool.Pool when:

  • Multiple goroutines need database access
  • Building web servers, APIs, or long-running services
  • Need automatic connection management and health checks

Use pgx.Conn when:

  • Single-threaded scripts or CLI tools
  • Want explicit control over connection lifecycle
  • Testing or development utilities

Use database/sql when:

  • Need compatibility with existing database/sql code
  • Using third-party libraries that expect database/sql
  • Portability across multiple database drivers is required

Feature Overview

Connection Management

Connection Pool (pgxpool) — Thread-safe pool for concurrent applications

func New(ctx context.Context, connString string) (*Pool, error)
func (p *Pool) Acquire(ctx context.Context) (*Conn, error)
func (p *Pool) Close()

Full Documentation

Direct Connection (pgx.Conn) — Single connection with full control

func Connect(ctx context.Context, connString string) (*Conn, error)
func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error)
func (c *Conn) Close(ctx context.Context) error

Full Documentation

Data Access

Querying — Execute queries and scan results

func (c *Conn) Query(ctx context.Context, sql string, args ...any) (Rows, error)
func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row
func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error)
func RowToStructByName[T any](row CollectableRow) (T, error)

Full Documentation

Transactions — Transaction management with isolation levels

func (c *Conn) Begin(ctx context.Context) (Tx, error)
func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error)
func BeginFunc(ctx context.Context, db interface{ Begin(ctx context.Context) (Tx, error) }, fn func(Tx) error) error

Full Documentation

Batch Queries — Multiple queries in one round trip

func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResults
func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery

Full Documentation

COPY Protocol — Bulk loading with binary COPY

func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
func CopyFromRows(rows [][]any) CopyFromSource
func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource

Full Documentation

Type System

PostgreSQL type encoding/decoding via pgtype package. Supports all standard types, arrays, composites, ranges, enums, and custom types.

Type System Overview

Common Types: Nullable Types — Bool, Int, Float, Text, Date, Timestamp, UUID
Collections: Arrays & Slices — Generic Array[T] and FlatArray[T]
Advanced: Ranges & Multiranges | JSON Types | Geometric Types | Custom Types

Integration & Advanced Features

database/sql Adapter — Use pgx with database/sql interface

func OpenDB(config pgx.ConnConfig, opts ...OptionOpenDB) *sql.DB
func OpenDBFromPool(pool *pgxpool.Pool, opts ...OptionOpenDB) *sql.DB

Full Documentation

Tracing & Logging — Instrument queries and connections

type QueryTracer interface {
    TraceQueryStart(ctx context.Context, conn *Conn, data TraceQueryStartData) context.Context
    TraceQueryEnd(ctx context.Context, conn *Conn, data TraceQueryEndData)
}

Full Documentation

Low-Level Connection (pgconn) — Direct wire protocol access for advanced use cases
Full Documentation | Pipeline Mode

Wire Protocol (pgproto3) — Message types for building proxies and tools
Full Documentation

Testing Utilities (pgxtest) — Test helpers and multi-mode testing
Full Documentation

Query Execution Modes

type QueryExecMode int32

const (
    QueryExecModeCacheStatement  QueryExecMode // default: auto-prepare, cache statements
    QueryExecModeCacheDescribe   QueryExecMode // cache descriptions only
    QueryExecModeDescribeExec    QueryExecMode // describe every time, two round trips
    QueryExecModeExec            QueryExecMode // extended protocol, text params, no cache
    QueryExecModeSimpleProtocol  QueryExecMode // simple protocol, client-side interpolation
)

Override default mode by passing as first argument:

rows, err := conn.Query(ctx, "SELECT ...", pgx.QueryExecModeSimpleProtocol, arg1, arg2)

Set default in ConnConfig.DefaultQueryExecMode.

Named Arguments

type NamedArgs map[string]any
type StrictNamedArgs map[string]any

Use @name placeholders instead of $1, $2:

conn.Query(ctx, "SELECT * FROM widgets WHERE foo = @foo AND bar = @bar",
    pgx.NamedArgs{"foo": 1, "bar": 2})

Common Errors

var ErrNoRows error          // no rows in result set (wraps sql.ErrNoRows)
var ErrTooManyRows error     // more rows than expected
var ErrTxClosed error        // transaction already closed
var ErrTxCommitRollback error // commit resulted in rollback

Check with errors.Is(err, pgx.ErrNoRows). Inspect PostgreSQL errors with errors.As(err, &pgconn.PgError{}).

Connection Strings

URL Format

postgres://user:password@host:port/database?param1=value1&param2=value2

Keyword/Value Format

host=localhost port=5432 user=myuser password=secret dbname=mydb sslmode=require

Common Parameters

pgx Parameters:

  • default_query_exec_mode: execution mode (default: cache_statement)
  • statement_cache_capacity: prepared statement cache size (default: 512)
  • description_cache_capacity: description cache size (default: 512)

pgxpool Parameters:

  • pool_max_conns: maximum connections (default: max(4, NumCPU))
  • pool_min_conns: minimum idle connections (default: 0)
  • pool_max_conn_lifetime: max connection age (default: 1h)
  • pool_max_conn_idle_time: max idle time (default: 30m)
  • pool_health_check_period: health check interval (default: 1m)

Environment Variables: Same as libpq — PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD, PGSSLMODE, PGSSLCERT, PGSSLKEY, PGSSLROOTCERT, etc.

Format Codes

const (
    TextFormatCode   = 0
    BinaryFormatCode = 1
)

PostgreSQL supports text and binary formats. pgx automatically uses binary format where supported for better performance.

Documentation Index

Getting Started

  • Start Here: Quick Start (above)
  • Common Patterns — Frequently used code patterns

Core Features

Type System

Integration

Advanced

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