Skip to content

Commit b653965

Browse files
committed
docs: explain how to use the batch object
The :batchexec, :batchmany and :batchone sections listed the batch object's methods but never said what the callback receives, what its int argument means, what Close does to statements that have not run yet, or when Close is even needed. Issue #4631 reports exactly this: readers cannot tell what to do with the returned batch object. Add a 'Using the batch object' section that documents the callback contract and Close semantics, and point each batch annotation at it: - the callback is invoked once per queued statement, in order, and the int is the statement's 0-based position in the batch - a failing statement does not stop iteration; errors must be handled inside the callback - Close before or during iteration skips the remaining statements and delivers ErrBatchAlreadyClosed once per remaining statement - Close is called automatically when the iteration method returns, so a fully iterated batch needs no explicit Close The behaviour described is taken from the generated code itself (internal/codegen/golang/templates/pgx/batchCode.tmpl and the batch endtoend golden files), not paraphrased from other docs. Fixes #4631
1 parent bdbe55d commit b653965

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

‎docs/reference/query-annotations.md‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ the following methods:
122122
- `Exec`, that takes a `func(int, error)` parameter,
123123
- `Close`, to close the batch operation early.
124124

125+
See [using the batch object](#using-the-batch-object) below for what these
126+
methods do and a complete example.
127+
125128
```sql
126129
-- name: DeleteBook :batchexec
127130
DELETE FROM books
@@ -154,6 +157,9 @@ the following methods:
154157
- `Query`, that takes a `func(int, []T, error)` parameter, where `T` is your query's return type
155158
- `Close`, to close the batch operation early.
156159

160+
See [using the batch object](#using-the-batch-object) below for what these
161+
methods do and a complete example.
162+
157163
```sql
158164
-- name: BooksByTitleYear :batchmany
159165
SELECT * FROM books
@@ -190,6 +196,9 @@ the following methods:
190196
- `QueryRow`, that takes a `func(int, T, error)` parameter, where `T` is your query's return type
191197
- `Close`, to close the batch operation early.
192198

199+
See [using the batch object](#using-the-batch-object) below for what these
200+
methods do and a complete example.
201+
193202
```sql
194203
-- name: CreateBook :batchone
195204
INSERT INTO books (
@@ -223,6 +232,79 @@ func (b *CreateBookBatchResults) Close() error {
223232
}
224233
```
225234

235+
## Using the batch object
236+
237+
The batch object returned by a `:batch*` method wraps a single
238+
`pgx.Batch`: one statement is queued per element of the slice argument, and
239+
all of them are sent to PostgreSQL together when the method is called. You
240+
then iterate the results with one of `Exec`, `Query` or `QueryRow` (depending
241+
on the annotation), and finish with `Close`.
242+
243+
The iteration method takes a callback and calls it **once per queued
244+
statement, in order**:
245+
246+
- The `int` argument is the 0-based position of the statement within the
247+
batch, matching the index of the element you passed in.
248+
- A failing statement does not stop the loop. If the third statement of ten
249+
fails, the callback still receives results for the fourth through tenth.
250+
Handle errors inside the callback; returning an error from it has no effect
251+
on iteration.
252+
- `Exec` delivers `func(index int, err error)`.
253+
- `Query` delivers `func(index int, rows []T, err error)` with all rows that
254+
the statement returned.
255+
- `QueryRow` delivers `func(index int, value T, err error)` with the single
256+
row the statement returned. A statement that matched no rows reports an
257+
error, just like a standalone `QueryRow`.
258+
259+
Calling `Close` before or during iteration marks the batch as closed: the
260+
remaining queued statements are not executed, and their callbacks instead
261+
receive `ErrBatchAlreadyClosed` — once per remaining statement, so your
262+
callback always sees the full batch. `Close` is also called automatically
263+
when the iteration method returns, so a batch that you iterate fully does
264+
not require an explicit `Close`.
265+
266+
To stop early on purpose, return early from the callback for the remaining
267+
statements after recording what you need, or `panic` through the iteration
268+
loop and recover around the call site.
269+
270+
Putting that together, a `:batchone` insert looks like this:
271+
272+
```go
273+
res := q.CreateBook(ctx, books)
274+
275+
inserted := make([]Book, len(books))
276+
res.QueryRow(func(i int, b Book, err error) {
277+
if err != nil {
278+
// log and continue: the batch keeps going regardless
279+
return
280+
}
281+
inserted[i] = b
282+
})
283+
// the batch is closed automatically when QueryRow returns
284+
```
285+
286+
And stopping early once something irrecoverable happens:
287+
288+
```go
289+
res := q.DeleteBook(ctx, ids)
290+
291+
res.Exec(func(i int, err error) {
292+
if err != nil {
293+
if errors.Is(err, ErrBatchAlreadyClosed) {
294+
return // we closed the batch ourselves
295+
}
296+
// fatal: abandon the rest of the batch
297+
res.Close()
298+
}
299+
})
300+
```
301+
302+
> [!NOTE]
303+
> `pgx` executes the queued statements in order, but they are sent as one
304+
> network round trip. The batch either way is a single unit from the
305+
> connection's point of view: an error partway through does not roll back
306+
> statements that already ran.
307+
226308
## `:copyfrom`
227309

228310
__NOTE: This command is driver and package specific, see [how to insert](../howto/insert.md#using-copyfrom)

0 commit comments

Comments
 (0)