File tree Expand file tree Collapse file tree 1 file changed +30
-4
lines changed Expand file tree Collapse file tree 1 file changed +30
-4
lines changed Original file line number Diff line number Diff line change 2
2
3
3
``` sql
4
4
CREATE TABLE records (
5
- id SERIAL PRIMARY KEY
5
+ id SERIAL PRIMARY KEY ,
6
+ counter INT NOT NULL
6
7
);
7
8
8
9
-- name: GetRecord :one
@@ -21,7 +22,8 @@ import (
21
22
)
22
23
23
24
type Record struct {
24
- ID int
25
+ ID int
26
+ Counter int
25
27
}
26
28
27
29
type DBTX interface {
@@ -41,14 +43,38 @@ func (*Queries) WithTx(tx *sql.Tx) *Queries {
41
43
}
42
44
43
45
const getRecord = ` -- name: GetRecord :one
44
- SELECT id FROM records
46
+ SELECT id, counter FROM records
45
47
WHERE id = $1
46
48
`
47
49
48
50
func (q *Queries ) GetRecord (ctx context .Context , id int ) (Record , error ) {
49
51
row := q.db .QueryRowContext (ctx, getRecord, id)
50
52
var i Record
51
- err := row.Scan (&i.ID )
53
+ err := row.Scan (&i.ID , &i. Counter )
52
54
return i, err
53
55
}
54
56
```
57
+
58
+ With pgx you'd use it like this for example:
59
+
60
+ ``` go
61
+ function bumpCounter (ctx context.Context , p *pgx.Conn , id int ) error {
62
+ tx , err := db.Begin (ctx)
63
+ if err != nil {
64
+ return err
65
+ }
66
+ defer tx.Rollback ()
67
+ q := db.New (tx)
68
+ r , err := q.GetRecord (ctx, id)
69
+ if err != nil {
70
+ return err
71
+ }
72
+ if err := q.UpdateRecord (ctx, db.UpdateRecordParams {
73
+ ID: r.ID ,
74
+ Counter: r.Counter +1 ,
75
+ }); err != nil {
76
+ return err
77
+ }
78
+ return tx.Commit ()
79
+ }
80
+ ```
You can’t perform that action at this time.
0 commit comments