This repository has been archived by the owner on Sep 9, 2024. It is now read-only.
forked from gocassa/gocassa
-
Notifications
You must be signed in to change notification settings - Fork 13
/
multiop.go
115 lines (97 loc) · 2.05 KB
/
multiop.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package gocassa
import "context"
type multiOp []Op
func Noop() Op {
return multiOp(nil)
}
func (mo multiOp) Run() error {
if err := mo.Preflight(); err != nil {
return err
}
for _, op := range mo {
if err := op.Run(); err != nil {
return err
}
}
return nil
}
func (mo multiOp) RunWithContext(ctx context.Context) error {
return mo.WithOptions(Options{Context: ctx}).Run()
}
func (mo multiOp) runLoggedBatch() error {
if len(mo) == 0 {
return nil
}
if err := mo.Preflight(); err != nil {
return err
}
stmts := make([]Statement, len(mo))
for i, op := range mo {
s := op.GenerateStatement()
stmts[i] = s
}
qe := mo.QueryExecutor()
return qe.ExecuteAtomicallyWithOptions(mo.Options(), stmts)
}
func (mo multiOp) RunLoggedBatchWithContext(ctx context.Context) error {
return mo.WithOptions(Options{Context: ctx}).RunAtomically()
}
func (mo multiOp) RunAtomically() error {
return mo.runLoggedBatch()
}
func (mo multiOp) RunAtomicallyWithContext(ctx context.Context) error {
return mo.RunLoggedBatchWithContext(ctx)
}
func (mo multiOp) GenerateStatement() Statement {
return noOpStatement{}
}
func (mo multiOp) QueryExecutor() QueryExecutor {
if len(mo) == 0 {
return nil
}
return mo[0].QueryExecutor()
}
func (mo multiOp) Add(ops_ ...Op) Op {
if len(ops_) == 0 {
return mo
} else if len(mo) == 0 {
switch len(ops_) {
case 1:
return ops_[0]
default:
return ops_[0].Add(ops_[1:]...)
}
}
for _, op := range ops_ {
// If any multiOps were passed, flatten them out
switch op := op.(type) {
case multiOp:
mo = append(mo, op...)
default:
mo = append(mo, op)
}
}
return mo
}
func (mo multiOp) Options() Options {
var opts Options
for _, op := range mo {
opts = opts.Merge(op.Options())
}
return opts
}
func (mo multiOp) WithOptions(opts Options) Op {
result := make(multiOp, len(mo))
for i, op := range mo {
result[i] = op.WithOptions(opts)
}
return result
}
func (mo multiOp) Preflight() error {
for _, op := range mo {
if err := op.Preflight(); err != nil {
return err
}
}
return nil
}