Skip to content

Commit 0b4a1ad

Browse files
authored
Merge pull request #2539 from alliasgher/docs/1900-array-agg-slice
docs: explain scanning array_agg (and other PG arrays) into Go slices
2 parents 53941bc + 7728d2d commit 0b4a1ad

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)