Repository navigation
Expand file tree
/
Copy pathexamples_test.go
More file actions
67 lines (58 loc) · 1.62 KB
/
Copy pathexamples_test.go
File metadata and controls
67 lines (58 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package crdbpgx_test
import (
"context"
"log"
"os"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sumup/crdbpgx"
)
func ExampleNewPool() {
cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
pool, err := crdbpgx.NewPool(
context.Background(),
cfg,
crdbpgx.WithName("orders"),
crdbpgx.WithContextPropagationBehaviour(crdbpgx.ContextPropagationOnAcquire),
crdbpgx.WithBalancer(crdbpgx.NewNodeConnectionBalancer(
crdbpgx.WithBalancingInterval(30*time.Second),
crdbpgx.WithBalancingTimeout(10*time.Second),
)),
)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
}
func ExamplePool_InTx() {
transferFunds := func(ctx context.Context, pool *crdbpgx.Pool, accountID string, amount int64) error {
return pool.InTx(ctx, pgx.TxOptions{}, func(db crdbpgx.Runner) error {
_, err := db.Exec(ctx, "UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, accountID)
return err
})
}
_ = transferFunds
}
// The same helper accepts a pool or a transaction through Runner.
func ExampleRunner_Query() {
listIDs := func(ctx context.Context, db crdbpgx.Runner) ([]int64, error) {
return db.Query(ctx, pgx.RowTo[int64],
"SELECT id FROM users WHERE active = @active", pgx.NamedArgs{"active": true})
}
_ = listIDs
}
func ExampleRunner_QueryRow() {
type User struct {
ID int64 `db:"id"`
Name string `db:"name"`
}
getUser := func(ctx context.Context, db crdbpgx.Runner, id int64) (User, error) {
return db.QueryRow(ctx, pgx.RowToStructByName[User],
"SELECT id, name FROM users WHERE id = $1", id)
}
_ = getUser
}