-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransactor.go
More file actions
71 lines (59 loc) · 1.51 KB
/
transactor.go
File metadata and controls
71 lines (59 loc) · 1.51 KB
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
package transactor
import (
"context"
"errors"
"fmt"
"log"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
type Transactor interface {
WithinTransaction(context.Context, func(ctx context.Context) error) error
}
type transactor struct {
conn *pgxpool.Pool
}
func New(conn *pgxpool.Pool) (*transactor, error) {
if conn == nil {
return nil, errors.New("a db connection must be provided")
}
return &transactor{conn}, nil
}
type txKey struct{}
// // injectTx injects transaction to context
func InjectTx(ctx context.Context, tx pgx.Tx) context.Context {
return context.WithValue(ctx, txKey{}, tx)
}
// // extractTx extracts transaction from context
func ExtractTx(ctx context.Context) pgx.Tx {
if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
return tx
}
return nil
}
func (t *transactor) WithinTransaction(ctx context.Context, tFunc func(ctx context.Context) error) error {
tx, err := t.conn.Begin(ctx)
if err != nil {
return fmt.Errorf("begin transaction: %w", err)
}
defer func() {
// finalize transaction on panic, etc.
if errTx := tx.Conn().Close(ctx); errTx != nil {
log.Printf("close transaction: %v", errTx)
}
}()
// run callback
err = tFunc(InjectTx(ctx, tx))
if err != nil {
// if error, rollback
if errRollback := tx.Rollback(ctx); errRollback != nil {
log.Printf("rollback transaction: %v", errRollback)
}
return err
}
// if no error, commit
if errCommit := tx.Commit(ctx); errCommit != nil {
log.Printf("commit transaction: %v", errCommit)
}
return nil
}