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

Function ExampleRowToStructByPos

rows_test.go:558–616  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

556}
557
558func ExampleRowToStructByPos() {
559 ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
560 defer cancel()
561
562 conn, err := pgx.Connect(ctx, os.Getenv("PGX_TEST_DATABASE"))
563 if err != nil {
564 fmt.Printf("Unable to establish connection: %v", err)
565 return
566 }
567
568 if conn.PgConn().ParameterStatus("crdb_version") != "" {
569 // Skip test / example when running on CockroachDB. Since an example can't be skipped fake success instead.
570 fmt.Println(`Cheeseburger: $10
571Fries: $5
572Soft Drink: $3`)
573 return
574 }
575
576 // Setup example schema and data.
577 _, err = conn.Exec(ctx, `
578create temporary table products (
579 id int primary key generated by default as identity,
580 name varchar(100) not null,
581 price int not null
582);
583
584insert into products (name, price) values
585 ('Cheeseburger', 10),
586 ('Double Cheeseburger', 14),
587 ('Fries', 5),
588 ('Soft Drink', 3);
589`)
590 if err != nil {
591 fmt.Printf("Unable to setup example schema and data: %v", err)
592 return
593 }
594
595 type product struct {
596 ID int32
597 Name string
598 Price int32
599 }
600
601 rows, _ := conn.Query(ctx, "select * from products where price < $1 order by price desc", 12)
602 products, err := pgx.CollectRows(rows, pgx.RowToStructByPos[product])
603 if err != nil {
604 fmt.Printf("CollectRows error: %v", err)
605 return
606 }
607
608 for _, p := range products {
609 fmt.Printf("%s: $%d\n", p.Name, p.Price)
610 }
611
612 // Output:
613 // Cheeseburger: $10
614 // Fries: $5
615 // Soft Drink: $3

Callers

nothing calls this directly

Calls 5

ParameterStatusMethod · 0.80
PgConnMethod · 0.80
ExecMethod · 0.65
QueryMethod · 0.65
ConnectMethod · 0.45

Tested by

no test coverage detected