generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
conn.go
61 lines (50 loc) · 1.09 KB
/
conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package sql
import (
"context"
"github.com/jackc/pgx/v5"
)
type DBI interface {
DBTX
Begin(ctx context.Context) (pgx.Tx, error)
}
type DB struct {
conn DBI
*Queries
}
func NewDB(conn DBI) *DB {
return &DB{conn: conn, Queries: New(conn)}
}
func (d *DB) Conn() DBI { return d.conn }
func (d *DB) Begin(ctx context.Context) (*Tx, error) {
tx, err := d.conn.Begin(ctx)
if err != nil {
return nil, err
}
return &Tx{tx: tx, Queries: New(tx)}, nil
}
type Tx struct {
tx pgx.Tx
*Queries
}
func (t *Tx) Commit(ctx context.Context) error {
return t.tx.Commit(ctx)
}
func (t *Tx) Rollback(ctx context.Context) error {
return t.tx.Rollback(ctx)
}
// CommitOrRollback can be used in a defer statement to commit or rollback a
// transaction depending on whether the enclosing function returned an error.
//
// func myFunc() (err error) {
// tx, err := db.Begin(ctx)
// if err != nil { return err }
// defer tx.CommitOrRollback(ctx, &err)
// ...
// }
func (t *Tx) CommitOrRollback(ctx context.Context, err *error) {
if *err != nil {
_ = t.Rollback(ctx)
} else {
*err = t.Commit(ctx)
}
}