MCPcopy
hub / github.com/jackc/pgx / ExampleCollectRows

Function ExampleCollectRows

rows_test.go:195–220  ·  view source on GitHub ↗

This example uses CollectRows with a manually written collector function. In most cases RowTo, RowToAddrOf, RowToStructByPos, RowToAddrOfStructByPos, or another generic function would be used.

()

Source from the content-addressed store, hash-verified

193// This example uses CollectRows with a manually written collector function. In most cases RowTo, RowToAddrOf,
194// RowToStructByPos, RowToAddrOfStructByPos, or another generic function would be used.
195func ExampleCollectRows() {
196 ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
197 defer cancel()
198
199 conn, err := pgx.Connect(ctx, os.Getenv("PGX_TEST_DATABASE"))
200 if err != nil {
201 fmt.Printf("Unable to establish connection: %v", err)
202 return
203 }
204
205 rows, _ := conn.Query(ctx, `select n from generate_series(1, 5) n`)
206 numbers, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (int32, error) {
207 var n int32
208 err := row.Scan(&n)
209 return n, err
210 })
211 if err != nil {
212 fmt.Printf("CollectRows error: %v", err)
213 return
214 }
215
216 fmt.Println(numbers)
217
218 // Output:
219 // [1 2 3 4 5]
220}
221
222func TestCollectOneRow(t *testing.T) {
223 defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) {

Callers

nothing calls this directly

Calls 3

QueryMethod · 0.65
ScanMethod · 0.65
ConnectMethod · 0.45

Tested by

no test coverage detected