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

batch.mddocs/

Batch Queries

Batch queries send multiple SQL statements to the server in a single round trip, reducing network latency. A Batch must only be sent once.

Import

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

Batch

type Batch struct {
    QueuedQueries []*QueuedQuery
}

func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery
func (b *Batch) Len() int

QueuedQuery

type QueuedQuery struct {
    SQL       string
    Arguments []any
}

func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error)
func (qq *QueuedQuery) Query(fn func(rows Rows) error)
func (qq *QueuedQuery) QueryRow(fn func(row Row) error)

Callbacks are invoked when BatchResults.Close() is called. If no callbacks are set, use BatchResults.Close() to check the overall error.

Sending a Batch

func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResults

BatchResults

type BatchResults interface {
    Exec() (pgconn.CommandTag, error)
    Query() (Rows, error)
    QueryRow() Row
    Close() error
}

Important: Close() must be called before the connection can be used again. It reads any unread results and calls all pending callbacks.

Usage Patterns

Pattern 1: Callbacks (recommended)

batch := &pgx.Batch{}

var users []User
batch.Queue("SELECT id, name FROM users WHERE active = $1", true).
    Query(func(rows pgx.Rows) error {
        var err error
        users, err = pgx.CollectRows(rows, pgx.RowToStructByName[User])
        return err
    })

batch.Queue("UPDATE stats SET last_checked = now()").
    Exec(func(ct pgconn.CommandTag) error {
        return nil
    })

br := conn.SendBatch(ctx, batch)
err := br.Close() // triggers callbacks

Pattern 2: Manual reading

batch := &pgx.Batch{}
batch.Queue("INSERT INTO foo VALUES ($1)", 1)
batch.Queue("INSERT INTO foo VALUES ($1)", 2)
batch.Queue("SELECT count(*) FROM foo")

br := conn.SendBatch(ctx, batch)
defer br.Close()

_, err := br.Exec()    // first query result
_, err = br.Exec()     // second query result
row := br.QueryRow()   // third query result
var count int
row.Scan(&count)

Pattern 3: Simple bulk insert (no callbacks needed)

batch := &pgx.Batch{}
for _, v := range values {
    batch.Queue("INSERT INTO items(name) VALUES ($1)", v)
}
err := conn.SendBatch(ctx, batch).Close()

Notes

  • Queries in a batch execute in an implicit transaction unless explicit transaction control is used.
  • When using QueryExecModeSimpleProtocol, a query string may contain multiple statements but callbacks will only be called for the first.
  • BatchResults.Close() is safe to call multiple times; subsequent calls return the same error.
  • If a callback returns an error or a batch query fails, subsequent callbacks are not called.
  • Works on pgxpool.Pool, pgxpool.Conn, pgxpool.Tx, and pgx.Tx — all implement SendBatch.

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