-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.go
More file actions
74 lines (61 loc) · 1.64 KB
/
transaction.go
File metadata and controls
74 lines (61 loc) · 1.64 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
72
73
74
package norm
import (
"context"
"github.com/jackc/pgx/v5"
)
type TxOptions struct{}
type TxManager interface {
WithTransaction(ctx context.Context, fn func(tx Transaction) error) error
BeginTx(ctx context.Context, opts *TxOptions) (Transaction, error)
}
type Transaction interface {
Commit(ctx context.Context) error
Rollback(ctx context.Context) error
Repository() Repository[map[string]any]
Exec() dbExecuter
Query() *QueryBuilder
}
type txManager struct{ kn *KintsNorm }
func (kn *KintsNorm) Tx() TxManager { return &txManager{kn: kn} }
type txImpl struct {
kn *KintsNorm
tx pgx.Tx
}
func (m *txManager) WithTransaction(ctx context.Context, fn func(tx Transaction) error) error {
txx, err := m.BeginTx(ctx, &TxOptions{})
if err != nil {
return err
}
if err := fn(txx); err != nil {
_ = txx.Rollback(ctx)
return err
}
return txx.Commit(ctx)
}
func (m *txManager) BeginTx(ctx context.Context, opts *TxOptions) (Transaction, error) {
tx, err := m.kn.pool.Begin(ctx)
if err != nil {
return nil, err
}
return &txImpl{kn: m.kn, tx: tx}, nil
}
func (t *txImpl) Commit(ctx context.Context) error { return t.tx.Commit(ctx) }
func (t *txImpl) Rollback(ctx context.Context) error { return t.tx.Rollback(ctx) }
func (t *txImpl) Repository() Repository[map[string]any] {
return NewRepositoryWithExecutor[map[string]any](t.kn, t.tx)
}
func (t *txImpl) Exec() dbExecuter {
if t.kn.breaker != nil {
return breakerExecuter{kn: t.kn, exec: t.tx}
}
return t.tx
}
func (t *txImpl) Query() *QueryBuilder {
qb := t.kn.Query()
if t.kn.breaker != nil {
qb.exec = breakerExecuter{kn: t.kn, exec: t.tx}
} else {
qb.exec = t.tx
}
return qb
}