1
1
# Using transactions
2
+ In the code generated by sqlc, the ` WithTx ` method allows a ` Queries ` instance to be associated with a transaction.
2
3
4
+ For example, with the following SQL structure:
5
+
6
+ ` schema.sql ` :
3
7
``` sql
4
8
CREATE TABLE records (
5
9
id SERIAL PRIMARY KEY ,
6
10
counter INT NOT NULL
7
11
);
12
+ ```
8
13
14
+ ` query.sql `
15
+ ``` sql
9
16
-- name: GetRecord :one
10
17
SELECT * FROM records
11
18
WHERE id = $1 ;
12
- ```
13
19
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
+ ```
15
24
25
+ And the generated code from sqlc in ` db.go ` :
16
26
``` go
17
- package db
27
+ package tutorial
18
28
19
29
import (
20
30
" context"
21
31
" database/sql"
22
32
)
23
33
24
- type Record struct {
25
- ID int
26
- Counter int
27
- }
28
-
29
34
type 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 )
30
38
QueryRowContext (context.Context , string , ...interface {}) *sql.Row
31
39
}
32
40
@@ -38,43 +46,34 @@ type Queries struct {
38
46
db DBTX
39
47
}
40
48
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
+ }
43
53
}
44
54
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
- }
56
55
```
57
56
58
- With pgx you 'd use it like this for example :
57
+ You 'd use it like this:
59
58
60
59
``` 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 ()
63
62
if err != nil {
64
63
return err
65
64
}
66
65
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)
69
68
if err != nil {
70
69
return err
71
70
}
72
- if err := q .UpdateRecord (ctx, db .UpdateRecordParams {
71
+ if err := qtx .UpdateRecord (ctx, tutorial .UpdateRecordParams {
73
72
ID: r.ID ,
74
73
Counter: r.Counter + 1 ,
75
74
}); err != nil {
76
75
return err
77
76
}
78
77
return tx.Commit ()
79
78
}
80
- ```
79
+ ```
0 commit comments