Skip to content
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
55 changes: 27 additions & 28 deletions docs/howto/transactions.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,40 @@
# Using transactions
In the code generated by sqlc, the `WithTx` method allows a `Queries` instance to be associated with a transaction.

For example, with the following SQL structure:

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

`query.sql`
```sql
-- name: GetRecord :one
SELECT * FROM records
WHERE id = $1;
```

The `WithTx` method allows a `Queries` instance to be associated with a transaction.
-- name: UpdateRecord :exec
UPDATE records SET counter = $2
WHERE id = $1;
```

And the generated code from sqlc in `db.go`:
```go
package db
package tutorial

import (
"context"
"database/sql"
)

type Record struct {
ID int
Counter int
}

type DBTX interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}

Expand All @@ -38,43 +46,34 @@ type Queries struct {
db DBTX
}

func (*Queries) WithTx(tx *sql.Tx) *Queries {
return &Queries{db: tx}
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
return &Queries{
db: tx,
}
}

const getRecord = `-- name: GetRecord :one
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, &i.Counter)
return i, err
}
```

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

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