generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
conn.go
93 lines (79 loc) · 1.98 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package sql
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
)
type DBI interface {
Querier
Conn() ConnI
Begin(ctx context.Context) (*Tx, error)
}
type ConnI interface {
DBTX
Begin(ctx context.Context) (pgx.Tx, error)
}
type DB struct {
conn ConnI
*Queries
}
func NewDB(conn ConnI) *DB {
return &DB{conn: conn, Queries: New(conn)}
}
func (d *DB) Conn() ConnI { 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
savepoints []string
*Queries
}
func (t *Tx) Conn() ConnI { return t.tx }
func (t *Tx) Begin(ctx context.Context) (*Tx, error) {
savepoint := fmt.Sprintf("savepoint_%d", len(t.savepoints))
t.savepoints = append(t.savepoints, savepoint)
_, err := t.tx.Exec(ctx, `SAVEPOINT `+savepoint)
if err != nil {
return nil, err
}
return &Tx{tx: t.tx, savepoints: t.savepoints, Queries: t.Queries}, nil
}
func (t *Tx) Commit(ctx context.Context) error {
if len(t.savepoints) == 0 {
return t.tx.Commit(ctx)
}
savepoint := t.savepoints[len(t.savepoints)-1]
t.savepoints = t.savepoints[:len(t.savepoints)-1]
_, err := t.tx.Exec(ctx, `RELEASE SAVEPOINT `+savepoint)
return err
}
func (t *Tx) Rollback(ctx context.Context) error {
if len(t.savepoints) == 0 {
return t.tx.Rollback(ctx)
}
savepoint := t.savepoints[len(t.savepoints)-1]
t.savepoints = t.savepoints[:len(t.savepoints)-1]
_, err := t.tx.Exec(ctx, `ROLLBACK TO SAVEPOINT `+savepoint)
return err
}
// 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)
}
}