Run a database transaction
Edit this pageProducer · Related pages
Posted: 2026-09-16 · Report this thread
InTransaction(ctx context.Context, transactionFunc TransactionFunc) errorOpens a transaction on the client’s pool and calls transactionFunc once.
A nil callback result commits. An error rolls back the transaction and is
returned unchanged. InTransaction does not retry the callback.
Example
Use an initialized client and a registered producer for the
payments.requested stream, with the example payload.
The application owns an orders table with an id text PRIMARY KEY column.
err := client.InTransaction(ctx, func(ctx context.Context, tx sqlstreams.Tx) error { if _, err := tx.Exec(ctx, `INSERT INTO orders (id) VALUES ($1) ON CONFLICT DO NOTHING`, "order-123"); err != nil { return err } _, err := producer.ProduceInTx(ctx, tx, &PaymentRequestedV1{OrderId: "order-123"}, &sqlstreams.ProduceOptions{IdempotencyKey: "payment-request:order-123"}) return err})if err != nil { return err}Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx |
context.Context |
Yes | Controls beginning the transaction, statements using this context, and commit. |
transactionFunc |
TransactionFunc |
Yes | A non-nil callback. Run database work through its tx and return errors to roll back. |
TransactionFunc
type TransactionFunc func(ctx context.Context, tx Tx) errorTx and Querier
Tx exposes the statement methods of Querier and Raw() pgx.Tx.
Transaction completion belongs to InTransaction, so the callback must not
commit or roll back the underlying transaction. Use tx sequentially.
| Method | Return value | Purpose |
|---|---|---|
Exec(ctx, sql, args...) |
(pgconn.CommandTag, error) |
Execute a statement without result rows. |
Query(ctx, sql, args...) |
(pgx.Rows, error) |
Read multiple rows. Close the rows after use. |
QueryRow(ctx, sql, args...) |
pgx.Row |
Read one row. Scan reports its error. |
SendBatch(ctx, batch) |
pgx.BatchResults |
Send a batch of statements. Close the results after use. |
CopyFrom(ctx, tableName, columnNames, rowSource) |
(int64, error) |
Copy rows into a table. |
Raw() |
pgx.Tx |
Access pgx operations beyond the statement interface. |
Returns
| Condition | Return value |
|---|---|
| Callback succeeds and commit is confirmed | nil. |
| Callback returns an error | That error. Its transaction is rolled back. |
| Begin or commit fails | The database or context error. A commit error can leave the outcome uncertain. |
Related topics
- Produce a message from database work — A producer-owned transaction that may retry its callback.
- Produce a message — Idempotency keys and result fields.
- Make message processing safe to repeat — Record a reward and update its balance in one transaction.