-
Notifications
You must be signed in to change notification settings - Fork 19
/
batch.go
108 lines (82 loc) · 2.56 KB
/
batch.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
package gockle
import (
"github.com/gocql/gocql"
"github.com/maraino/go-mock"
)
// ColumnApplied is the name of a special column that has a bool that indicates
// whether a conditional statement was applied.
const ColumnApplied = "[applied]"
// Batch is an ordered collection of CQL queries.
type Batch interface {
// Add adds the query for statement and arguments.
Add(statement string, arguments ...interface{})
// Exec executes the queries in the order they were added.
Exec() error
// ExecTx executes the queries in the order they were added. It returns a slice
// of maps from columns to values, the maps corresponding to all the conditional
// queries, and ordered in the same relative order. The special column
// ColumnApplied has a bool that indicates whether the conditional statement was
// applied. If a conditional statement was not applied, the current values for
// the columns are put into the map.
ExecTx() ([]map[string]interface{}, error)
}
var (
_ Batch = BatchMock{}
_ Batch = batch{}
)
// BatchKind is the kind of Batch. The choice of kind mostly affects performance.
type BatchKind byte
// Kinds of batches.
const (
// BatchLogged queries are atomic. Queries are only isolated within a single
// partition.
BatchLogged BatchKind = 0
// BatchUnlogged queries are not atomic. Atomic queries spanning multiple partitions cost performance.
BatchUnlogged BatchKind = 1
// BatchCounter queries update counters and are not idempotent.
BatchCounter BatchKind = 2
)
// BatchMock is a mock Batch. See github.com/maraino/go-mock.
type BatchMock struct {
mock.Mock
}
// Add implements Batch.
func (m BatchMock) Add(statement string, arguments ...interface{}) {
m.Called(statement, arguments)
}
// Exec implements Batch.
func (m BatchMock) Exec() error {
return m.Called().Error(0)
}
// ExecTx implements Batch.
func (m BatchMock) ExecTx() ([]map[string]interface{}, error) {
var r = m.Called()
return r.Get(0).([]map[string]interface{}), r.Error(1)
}
type batch struct {
b *gocql.Batch
s *gocql.Session
}
func (b batch) Add(statement string, arguments ...interface{}) {
b.b.Query(statement, arguments...)
}
func (b batch) Exec() error {
return b.s.ExecuteBatch(b.b)
}
func (b batch) ExecTx() ([]map[string]interface{}, error) {
var m = map[string]interface{}{}
var a, i, err = b.s.MapExecuteBatchCAS(b.b, m)
if err != nil {
return nil, err
}
s, err := i.SliceMap()
if err != nil {
return nil, err
}
if err := i.Close(); err != nil {
return nil, err
}
m[ColumnApplied] = a
s = append([]map[string]interface{}{m}, s...)
return s, nil
}