Skip to content

Commit a353d74

Browse files
authored
feat(docs): how-to use transactions with pgx (#3557)
1 parent c582986 commit a353d74

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

docs/howto/transactions.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ func (q *Queries) WithTx(tx *sql.Tx) *Queries {
5757
You'd use it like this:
5858

5959
```go
60+
// Using `github/lib/pq` as the driver.
6061
func bumpCounter(ctx context.Context, db *sql.DB, queries *tutorial.Queries, id int32) error {
6162
tx, err := db.Begin()
6263
if err != nil {
@@ -76,4 +77,25 @@ func bumpCounter(ctx context.Context, db *sql.DB, queries *tutorial.Queries, id
7677
}
7778
return tx.Commit()
7879
}
80+
81+
// Using `github.com/jackc/pgx/v5` as the driver.
82+
func bumpCounter(ctx context.Context, db *pgx.Conn, queries *tutorial.Queries, id int32) error {
83+
tx, err := db.Begin(ctx)
84+
if err != nil {
85+
return err
86+
}
87+
defer tx.Rollback(ctx)
88+
qtx := queries.WithTx(tx)
89+
r, err := qtx.GetRecord(ctx, id)
90+
if err != nil {
91+
return err
92+
}
93+
if err := qtx.UpdateRecord(ctx, tutorial.UpdateRecordParams{
94+
ID: r.ID,
95+
Counter: r.Counter + 1,
96+
}); err != nil {
97+
return err
98+
}
99+
return tx.Commit(ctx)
100+
}
79101
```

0 commit comments

Comments
 (0)