This repository has been archived by the owner on Nov 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
95 lines (76 loc) · 1.97 KB
/
executor.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 layer
import (
"context"
"github.com/pkg/errors"
"github.com/volatiletech/sqlboiler/v4/boil"
)
type BoilExecutor interface {
boil.ContextBeginner
boil.ContextExecutor
}
type contextKey struct {
KeyName string
}
var (
ExecutorKey = contextKey{
KeyName: "executor",
}
TransactorKey = contextKey{
KeyName: "transactor",
}
ErrCreateTransaction = errors.New("creating transaction failed")
ErrContextIsNil = errors.New("context is nil")
ErrTransactorIsExists = errors.New("transactor is exists")
)
func GetExecutor(ctx context.Context, executor BoilExecutor) (context.Context, boil.ContextExecutor) {
if ctx != nil {
executor, exists := ctx.Value(ExecutorKey).(boil.ContextExecutor)
if exists {
return ctx, executor
}
}
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, ExecutorKey, executor), executor
}
func GetTransactor(ctx context.Context) (context.Context, boil.ContextTransactor) {
if ctx != nil {
transactor, exists := ctx.Value(TransactorKey).(boil.ContextTransactor)
if exists {
return ctx, transactor
}
}
if ctx == nil {
ctx = context.TODO()
}
return ctx, nil
}
func CreateTransaction(ctx context.Context, beginner boil.ContextBeginner) (context.Context, boil.ContextTransactor, error) {
if ctx == nil {
return context.TODO(), nil, ErrContextIsNil
}
transactor, exists := ctx.Value(TransactorKey).(boil.ContextTransactor)
if exists {
return ctx, transactor, ErrTransactorIsExists
}
tx, err := beginner.BeginTx(ctx, nil)
if err != nil {
return nil, nil, errors.Wrap(err, "creating transaction failed")
}
ctx = context.WithValue(ctx, ExecutorKey, tx)
ctx = context.WithValue(ctx, TransactorKey, tx)
return ctx, tx, nil
}
func ExecuteTransaction(transactor boil.ContextTransactor, err *error) {
var errTr error
if *err == nil {
errTr = transactor.Commit()
}
if errTr != nil {
errTr = transactor.Rollback()
if errTr != nil {
*err = errors.Wrap(errTr, "rollback failed")
}
}
}