Skip to content

docs: Add some more example code for running transactions #1583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions docs/howto/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

```sql
CREATE TABLE records (
id SERIAL PRIMARY KEY
id SERIAL PRIMARY KEY,
counter INT NOT NULL
);

-- name: GetRecord :one
Expand All @@ -21,7 +22,8 @@ import (
)

type Record struct {
ID int
ID int
Counter int
}

type DBTX interface {
Expand All @@ -41,14 +43,38 @@ func (*Queries) WithTx(tx *sql.Tx) *Queries {
}

const getRecord = `-- name: GetRecord :one
SELECT id FROM records
SELECT id, counter FROM records
WHERE id = $1
`

func (q *Queries) GetRecord(ctx context.Context, id int) (Record, error) {
row := q.db.QueryRowContext(ctx, getRecord, id)
var i Record
err := row.Scan(&i.ID)
err := row.Scan(&i.ID, &i.Counter)
return i, err
}
```

With pgx you'd use it like this for example:

```go
function bumpCounter(ctx context.Context, p *pgx.Conn, id int) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
q := db.New(tx)
r, err := q.GetRecord(ctx, id)
if err != nil {
return err
}
if err := q.UpdateRecord(ctx, db.UpdateRecordParams{
ID: r.ID,
Counter: r.Counter+1,
}); err != nil {
return err
}
return tx.Commit()
}
```