Skip to content

Commit 7728d2d

Browse files
committed
docs: explain scanning array_agg (and other PG arrays) into Go slices
Users hitting a query that uses `array_agg` (or any PG array-returning expression) and who try to scan its result into a struct field often see "unable to assign to *[]int64" and assume the feature is missing. The two-step recipe from #1900 — scan the array scalar into a slice with `QueryRow` / slice-typed `Scan`, and compose slice fields into structs via `CollectRows` / `RowToStructByName` — is the canonical answer but isn't currently discoverable from the package docs. Add a short paragraph with both forms to the PostgreSQL Data Types section of `doc.go` so `go doc pgx` / pkg.go.dev surface the recipe. Closes #1900 Signed-off-by: Ali <alliasgher123@gmail.com>
1 parent 0aeabbc commit 7728d2d

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

doc.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,27 @@ pgx uses the [pgtype] package to converting Go values to and from PostgreSQL val
7474
directly and is customizable and extendable. User defined data types such as enums, domains, and composite types may
7575
require type registration. See that package's documentation for details.
7676
77+
PostgreSQL arrays (including results from set-returning aggregates such as array_agg)
78+
can be scanned directly into a matching Go slice. For scalar columns, pass the slice
79+
as the scan destination:
80+
81+
var ids []int64
82+
err := conn.QueryRow(ctx, "select array_agg(id) from things").Scan(&ids)
83+
84+
For a column that is part of a row, combine the slice with the usual row-to-struct
85+
helpers. A struct field of slice type will pick up the array_agg column when
86+
collected via [CollectRows] and [RowToStructByName] (or
87+
[RowToAddrOfStructByPos]):
88+
89+
type ThingEntry struct {
90+
GroupID int64
91+
ThingIDs []int64 `db:"thing_ids"`
92+
}
93+
94+
rows, _ := conn.Query(ctx,
95+
"select group_id, array_agg(thing_id) as thing_ids from things group by group_id")
96+
entries, err := pgx.CollectRows(rows, pgx.RowToStructByName[ThingEntry])
97+
7798
Transactions
7899
79100
Transactions are started by calling [Conn.Begin].

0 commit comments

Comments
 (0)