/
transaction.go
95 lines (80 loc) · 1.82 KB
/
transaction.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
94
95
package repo
import (
"context"
"fmt"
"github.com/bukodi/webauthn-ra/pkg/errlog"
"gorm.io/gorm"
)
type readTxKeyType int
type writeTxKeyType int
const readTxKey readTxKeyType = 1
const writeTxKey writeTxKeyType = 2
type writeTx struct {
writeTx *gorm.DB
}
type ReadCtx struct {
context.Context
db *gorm.DB
}
type WriteCtx struct {
ReadCtx
}
func WriteTx1(ctx context.Context, fn func(ctx context.Context) error) error {
_, ok := ctx.Value(writeTxKey).(*writeTx)
if ok {
return errlog.Handle(ctx, fmt.Errorf("already in a write transaction"))
}
dbTx := dbInstance.Begin()
defer func() {
if r := recover(); r != nil {
dbTx.Rollback()
}
}()
if err := dbTx.Error; err != nil {
return errlog.Handle(ctx, err)
}
var writeTx = writeTx{
writeTx: dbTx,
}
ctx2 := context.WithValue(ctx, writeTxKey, &writeTx)
err := fn(ctx2)
if err != nil {
dbTx.Rollback()
return errlog.Handle(ctx, err)
} else {
return errlog.Handle(ctx, dbTx.Commit().Error)
}
}
func NewWriteTx(ctx context.Context, fn func(ctx context.Context) error) error {
_, ok := ctx.Value(writeTxKey).(*writeTx)
if ok {
return errlog.Handle(ctx, fmt.Errorf("already in a write transaction"))
}
dbTx := dbInstance.Begin()
defer func() {
if r := recover(); r != nil {
dbTx.Rollback()
}
}()
if err := dbTx.Error; err != nil {
return errlog.Handle(ctx, err)
}
var writeTx = writeTx{
writeTx: dbTx,
}
ctx2 := context.WithValue(ctx, writeTxKey, &writeTx)
err := fn(ctx2)
if err != nil {
dbTx.Rollback()
return errlog.Handle(ctx, err)
} else {
return errlog.Handle(ctx, dbTx.Commit().Error)
}
}
func RequiresWriteTx(ctx context.Context) (*gorm.DB, error) {
if writeTx, ok := ctx.Value(writeTxKey).(*writeTx); ok {
return writeTx.writeTx, nil
} else {
return nil, errlog.Handle(ctx, fmt.Errorf("not in a write transaction"))
}
}