Skip to content

Commit

Permalink
feat(docs): how-to use transactions with pgx (sqlc-dev#3557)
Browse files Browse the repository at this point in the history
  • Loading branch information
pedro-tiple authored Aug 23, 2024
1 parent c582986 commit a353d74
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions docs/howto/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func (q *Queries) WithTx(tx *sql.Tx) *Queries {
You'd use it like this:

```go
// Using `github/lib/pq` as the driver.
func bumpCounter(ctx context.Context, db *sql.DB, queries *tutorial.Queries, id int32) error {
tx, err := db.Begin()
if err != nil {
Expand All @@ -76,4 +77,25 @@ func bumpCounter(ctx context.Context, db *sql.DB, queries *tutorial.Queries, id
}
return tx.Commit()
}

// Using `github.com/jackc/pgx/v5` as the driver.
func bumpCounter(ctx context.Context, db *pgx.Conn, queries *tutorial.Queries, id int32) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
qtx := queries.WithTx(tx)
r, err := qtx.GetRecord(ctx, id)
if err != nil {
return err
}
if err := qtx.UpdateRecord(ctx, tutorial.UpdateRecordParams{
ID: r.ID,
Counter: r.Counter + 1,
}); err != nil {
return err
}
return tx.Commit(ctx)
}
```

0 comments on commit a353d74

Please sign in to comment.