11# Using transactions
2+ In the code generated by sqlc, the ` WithTx ` method allows a ` Queries ` instance to be associated with a transaction.
23
4+ For example, with the following SQL structure:
5+
6+ ` schema.sql ` :
37``` sql
48CREATE TABLE records (
59 id SERIAL PRIMARY KEY ,
610 counter INT NOT NULL
711);
12+ ```
813
14+ ` query.sql `
15+ ``` sql
916-- name: GetRecord :one
1017SELECT * FROM records
1118WHERE id = $1 ;
12- ```
1319
14- The ` WithTx ` method allows a ` Queries ` instance to be associated with a transaction.
20+ -- name: UpdateRecord :exec
21+ UPDATE records SET counter = $2
22+ WHERE id = $1 ;
23+ ```
1524
25+ And the generated code from sqlc in ` db.go ` :
1626``` go
17- package db
27+ package tutorial
1828
1929import (
2030 " context"
2131 " database/sql"
2232)
2333
24- type Record struct {
25- ID int
26- Counter int
27- }
28-
2934type DBTX interface {
35+ ExecContext (context.Context , string , ...interface {}) (sql.Result , error )
36+ PrepareContext (context.Context , string ) (*sql.Stmt , error )
37+ QueryContext (context.Context , string , ...interface {}) (*sql.Rows , error )
3038 QueryRowContext (context.Context , string , ...interface {}) *sql.Row
3139}
3240
@@ -38,43 +46,34 @@ type Queries struct {
3846 db DBTX
3947}
4048
41- func (*Queries ) WithTx (tx *sql .Tx ) *Queries {
42- return &Queries{db: tx}
49+ func (q *Queries ) WithTx (tx *sql .Tx ) *Queries {
50+ return &Queries{
51+ db: tx,
52+ }
4353}
4454
45- const getRecord = ` -- name: GetRecord :one
46- SELECT id, counter FROM records
47- WHERE id = $1
48- `
49-
50- func (q *Queries ) GetRecord (ctx context .Context , id int ) (Record , error ) {
51- row := q.db .QueryRowContext (ctx, getRecord, id)
52- var i Record
53- err := row.Scan (&i.ID , &i.Counter )
54- return i, err
55- }
5655```
5756
58- With pgx you 'd use it like this for example :
57+ You 'd use it like this:
5958
6059``` go
61- func bumpCounter (ctx context .Context , p * pgx . Conn , id int ) error {
62- tx , err := db.Begin (ctx )
60+ func bumpCounter (ctx context .Context , db * sql . DB , queries * tutorial . Queries , id int32 ) error {
61+ tx , err := db.Begin ()
6362 if err != nil {
6463 return err
6564 }
6665 defer tx.Rollback ()
67- q := db. New (tx)
68- r , err := q .GetRecord (ctx, id)
66+ qtx := queries. WithTx (tx)
67+ r , err := qtx .GetRecord (ctx, id)
6968 if err != nil {
7069 return err
7170 }
72- if err := q .UpdateRecord (ctx, db .UpdateRecordParams {
71+ if err := qtx .UpdateRecord (ctx, tutorial .UpdateRecordParams {
7372 ID: r.ID ,
7473 Counter: r.Counter + 1 ,
7574 }); err != nil {
7675 return err
7776 }
7877 return tx.Commit ()
7978}
80- ```
79+ ```
0 commit comments