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.
—
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 "github.com/jackc/pgx/v5"type Batch struct {
QueuedQueries []*QueuedQuery
}
func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery
func (b *Batch) Len() inttype 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.
func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResultstype 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.
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 callbacksbatch := &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)batch := &pgx.Batch{}
for _, v := range values {
batch.Queue("INSERT INTO items(name) VALUES ($1)", v)
}
err := conn.SendBatch(ctx, batch).Close()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.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