Skip to content

Commit 138b1c9

Browse files
committed
Add documentation for the :iter query annotation
1 parent 289098b commit 138b1c9

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

‎docs/reference/query-annotations.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,49 @@ func (q *Queries) InsertAuthor(ctx context.Context, name string) (int64, error)
7777
}
7878
```
7979

80+
## `:iter`
81+
82+
The generated method will return an [iter.Seq](https://pkg.go.dev/iter#Seq) that
83+
streams records as they are scanned, together with a function that eventually
84+
reports the query's error. This needs Go 1.23 or later.
85+
86+
```sql
87+
-- name: ListAuthors :iter
88+
SELECT * FROM authors
89+
ORDER BY name;
90+
```
91+
92+
```go
93+
func (q *Queries) ListAuthors(ctx context.Context) (iter.Seq[Author], func() error) {
94+
// ...
95+
}
96+
```
97+
98+
To consume, you can range over the `iter.Seq`:
99+
100+
```go
101+
authors, ferr := q.ListAuthors(ctx)
102+
for author := range authors {
103+
// ...
104+
}
105+
if err := ferr(); err != nil {
106+
// ...
107+
}
108+
```
109+
110+
The query starts only when the iterator is ranged over, not when the method is
111+
called. When `q` runs on a single connection or transaction, it must not be
112+
used inside the `for` loop, as the query is still reading from it. Once the
113+
loop ends, by running out of rows or by `break`, the rows are closed and the
114+
connection is released.
115+
116+
The function returned alongside the iterator reports any error from running the
117+
query or scanning its rows, so call it after the loop.
118+
119+
The iterator is single-use: it runs its query once, which matters for a
120+
`DELETE ... RETURNING` or `INSERT ... RETURNING`. Ranging over it a second
121+
time yields nothing, and the returned function then reports an error.
122+
80123
## `:many`
81124

82125
The generated method will return a slice of records via

0 commit comments

Comments
 (0)