()
| 739 | } |
| 740 | |
| 741 | func ExampleRowToStructByName() { |
| 742 | ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) |
| 743 | defer cancel() |
| 744 | |
| 745 | conn, err := pgx.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) |
| 746 | if err != nil { |
| 747 | fmt.Printf("Unable to establish connection: %v", err) |
| 748 | return |
| 749 | } |
| 750 | |
| 751 | if conn.PgConn().ParameterStatus("crdb_version") != "" { |
| 752 | // Skip test / example when running on CockroachDB. Since an example can't be skipped fake success instead. |
| 753 | fmt.Println(`Cheeseburger: $10 |
| 754 | Fries: $5 |
| 755 | Soft Drink: $3`) |
| 756 | return |
| 757 | } |
| 758 | |
| 759 | // Setup example schema and data. |
| 760 | _, err = conn.Exec(ctx, ` |
| 761 | create temporary table products ( |
| 762 | id int primary key generated by default as identity, |
| 763 | name varchar(100) not null, |
| 764 | price int not null |
| 765 | ); |
| 766 | |
| 767 | insert into products (name, price) values |
| 768 | ('Cheeseburger', 10), |
| 769 | ('Double Cheeseburger', 14), |
| 770 | ('Fries', 5), |
| 771 | ('Soft Drink', 3); |
| 772 | `) |
| 773 | if err != nil { |
| 774 | fmt.Printf("Unable to setup example schema and data: %v", err) |
| 775 | return |
| 776 | } |
| 777 | |
| 778 | type product struct { |
| 779 | ID int32 |
| 780 | Name string |
| 781 | Price int32 |
| 782 | } |
| 783 | |
| 784 | rows, _ := conn.Query(ctx, "select * from products where price < $1 order by price desc", 12) |
| 785 | products, err := pgx.CollectRows(rows, pgx.RowToStructByName[product]) |
| 786 | if err != nil { |
| 787 | fmt.Printf("CollectRows error: %v", err) |
| 788 | return |
| 789 | } |
| 790 | |
| 791 | for _, p := range products { |
| 792 | fmt.Printf("%s: $%d\n", p.Name, p.Price) |
| 793 | } |
| 794 | |
| 795 | // Output: |
| 796 | // Cheeseburger: $10 |
| 797 | // Fries: $5 |
| 798 | // Soft Drink: $3 |
nothing calls this directly
no test coverage detected