forked from capitancambio/gocassa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmock.go
460 lines (374 loc) · 9.06 KB
/
mock.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package gocassa
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/gocql/gocql"
"github.com/google/btree"
)
// MockKeySpace implements the KeySpace interface and constructs in-memory tables.
type mockKeySpace struct {
k
}
type mockOp struct {
options Options
funcs []func(mockOp) error
preflightErr error
}
func newOp(f func(mockOp) error) mockOp {
return mockOp{
funcs: []func(mockOp) error{f},
}
}
func (m mockOp) Add(ops ...Op) Op {
return multiOp{m}.Add(ops...)
}
func (m mockOp) Run() error {
for _, f := range m.funcs {
err := f(m)
if err != nil {
return err
}
}
return nil
}
func (m mockOp) WithOptions(opt Options) Op {
return mockOp{
options: opt,
funcs: m.funcs,
}
}
func (m mockOp) RunAtomically() error {
return m.Run()
}
func (m mockOp) GenerateStatement() (string, []interface{}) {
return "", []interface{}{}
}
func (m mockOp) QueryExecutor() QueryExecutor {
return nil
}
func (m mockOp) Preflight() error {
return m.preflightErr
}
func (ks *mockKeySpace) NewTable(name string, entity interface{}, fields map[string]interface{}, keys Keys) Table {
return &MockTable{
name: name,
entity: entity,
keys: keys,
rows: map[rowKey]*btree.BTree{},
}
}
func NewMockKeySpace() KeySpace {
ks := &mockKeySpace{}
ks.tableFactory = ks
return ks
}
// MockTable implements the Table interface and stores rows in-memory.
type MockTable struct {
// rows is mapping from row key to column group key to column map
name string
rows map[rowKey]*btree.BTree
entity interface{}
keys Keys
options Options
}
type rowKey string
type superColumn struct {
Key *keyPart
Columns map[string]interface{}
}
func (c *superColumn) Less(item btree.Item) bool {
other, ok := item.(*superColumn)
if !ok {
return false
}
return c.Key.Less(other.Key)
}
type gocqlTypeInfo struct {
proto byte
typ gocql.Type
}
func (t gocqlTypeInfo) New() interface{} {
return &gocqlTypeInfo{t.proto, t.typ}
}
func (t gocqlTypeInfo) Type() gocql.Type {
return t.typ
}
func (t gocqlTypeInfo) Version() byte {
return t.proto
}
func (t gocqlTypeInfo) Custom() string {
return ""
}
type keyPart struct {
Key string
Value interface{}
Tail *keyPart
}
func (k *keyPart) Prepend(key string, value interface{}) *keyPart {
return &keyPart{Key: key, Value: value, Tail: k}
}
func (k *keyPart) Less(other *keyPart) bool {
for part, other := k, other; part != nil && other != nil; part, other = part.Tail, other.Tail {
cmp := bytes.Compare(part.Bytes(), other.Bytes())
if cmp == 0 {
continue
}
return cmp < 0
}
return false
}
func (k *keyPart) Bytes() []byte {
typeInfo := &gocqlTypeInfo{
proto: 0x03,
typ: cassaType(k.Value),
}
// FIXME handle err
marshalled, _ := gocql.Marshal(typeInfo, k.Value)
return marshalled
}
func (k *keyPart) RowKey() rowKey {
buf := bytes.Buffer{}
for part := k; part != nil; part = part.Tail {
buf.Write(part.Bytes())
}
return rowKey(buf.String())
}
func (k *keyPart) ToSuperColumn() *superColumn {
return &superColumn{Key: k}
}
func (t *MockTable) zero() interface{} {
return reflect.New(reflect.TypeOf(t.entity)).Interface()
}
func (t *MockTable) keyFromColumnValues(columns map[string]interface{}, keys []string) (*keyPart, error) {
var key *keyPart
for _, column := range keys {
value, ok := columns[column]
if !ok {
return nil, fmt.Errorf("Missing mandatory PRIMARY KEY part %s", column)
}
key = key.Prepend(column, value)
}
return key, nil
}
func (t *MockTable) Name() string {
if len(t.options.TableName) > 0 {
return t.options.TableName
}
return t.name
}
func (t *MockTable) getOrCreateRow(rowKey *keyPart) *btree.BTree {
row := t.rows[rowKey.RowKey()]
if row == nil {
row = btree.New(2)
t.rows[rowKey.RowKey()] = row
}
return row
}
func (t *MockTable) getOrCreateColumnGroup(rowKey, superColumnKey *keyPart) map[string]interface{} {
row := t.getOrCreateRow(rowKey)
scol := superColumnKey.ToSuperColumn()
if row.Has(scol) {
return row.Get(scol).(*superColumn).Columns
}
row.ReplaceOrInsert(scol)
scol.Columns = map[string]interface{}{}
return scol.Columns
}
func (t *MockTable) SetWithOptions(i interface{}, options Options) Op {
return newOp(func(m mockOp) error {
columns, ok := toMap(i)
if !ok {
return errors.New("Can't create: value not understood")
}
rowKey, err := t.keyFromColumnValues(columns, t.keys.PartitionKeys)
if err != nil {
return err
}
superColumnKey, err := t.keyFromColumnValues(columns, t.keys.ClusteringColumns)
if err != nil {
return err
}
superColumn := t.getOrCreateColumnGroup(rowKey, superColumnKey)
for k, v := range columns {
superColumn[k] = v
}
return nil
})
}
func (t *MockTable) Set(i interface{}) Op {
return t.SetWithOptions(i, t.options)
}
func (t *MockTable) Where(relations ...Relation) Filter {
return &MockFilter{
table: t,
relations: relations,
}
}
func (t *MockTable) Create() error {
return nil
}
func (t *MockTable) CreateStatement() (string, error) {
return "", nil
}
func (t *MockTable) Recreate() error {
return nil
}
func (t *MockTable) WithOptions(o Options) Table {
return &MockTable{
name: t.name,
rows: t.rows,
entity: t.entity,
keys: t.keys,
options: t.options.Merge(o),
}
}
// MockFilter implements the Filter interface and works with MockTable.
type MockFilter struct {
table *MockTable
relations []Relation
}
func (f *MockFilter) rowMatch(row map[string]interface{}) bool {
for _, relation := range f.relations {
value := row[relation.key]
if !relation.accept(value) {
return false
}
}
return true
}
func (f *MockFilter) keyRelationMap() map[string]Relation {
result := map[string]Relation{}
for _, relation := range f.relations {
result[relation.key] = relation
}
return result
}
func (f *MockFilter) keysFromRelations(keys []string) ([]*keyPart, error) {
keyRelationMap := f.keyRelationMap()
var rowKey *keyPart
var result []*keyPart
if len(keys) == 0 {
return []*keyPart{nil}, nil
}
for i, key := range keys {
lastKey := i == len(keys)-1
relation, ok := keyRelationMap[key]
if !ok {
return nil, fmt.Errorf("Missing mandatory PRIMARY KEY part %s", key)
}
if relation.op != equality && !(lastKey && relation.op == in) {
return nil, fmt.Errorf("Invalid use of PK %s", key)
}
if !lastKey {
rowKey = rowKey.Prepend(key, relation.terms[0])
} else {
for _, term := range relation.terms {
result = append(result, rowKey.Prepend(relation.key, term))
}
}
}
return result, nil
}
func (f *MockFilter) UpdateWithOptions(m map[string]interface{}, options Options) Op {
return newOp(func(mock mockOp) error {
rowKeys, err := f.keysFromRelations(f.table.keys.PartitionKeys)
if err != nil {
return err
}
for _, rowKey := range rowKeys {
superColumnKeys, err := f.keysFromRelations(f.table.keys.ClusteringColumns)
if err != nil {
return err
}
for _, superColumnKey := range superColumnKeys {
superColumn := f.table.getOrCreateColumnGroup(rowKey, superColumnKey)
for _, keyPart := range []*keyPart{rowKey, superColumnKey} {
for k := keyPart; k != nil; k = k.Tail {
superColumn[k.Key] = k.Value
}
}
for key, value := range m {
superColumn[key] = value
}
}
}
return nil
})
}
func (f *MockFilter) Update(m map[string]interface{}) Op {
return f.UpdateWithOptions(m, Options{})
}
func (f *MockFilter) Delete() Op {
return newOp(func(m mockOp) error {
rowKeys, err := f.keysFromRelations(f.table.keys.PartitionKeys)
if err != nil {
return err
}
for _, rowKey := range rowKeys {
row := f.table.rows[rowKey.RowKey()]
if row == nil {
return nil
}
row.Ascend(func(item btree.Item) bool {
columns := item.(*superColumn).Columns
if f.rowMatch(columns) {
row.Delete(item)
}
return true
})
}
return nil
})
}
func (q *MockFilter) Read(out interface{}) Op {
return newOp(func(m mockOp) error {
rowKeys, err := q.keysFromRelations(q.table.keys.PartitionKeys)
if err != nil {
return err
}
var result []map[string]interface{}
for _, rowKey := range rowKeys {
row := q.table.rows[rowKey.RowKey()]
if row == nil {
continue
}
row.Ascend(func(item btree.Item) bool {
columns := item.(*superColumn).Columns
if q.rowMatch(columns) {
result = append(result, columns)
}
return true
})
}
opt := q.table.options.Merge(m.options)
if opt.Limit > 0 && opt.Limit < len(result) {
result = result[:opt.Limit]
}
return q.assignResult(result, out)
})
}
func (q *MockFilter) assignResult(records interface{}, out interface{}) error {
bytes, err := json.Marshal(records)
if err != nil {
return err
}
return json.Unmarshal(bytes, out)
}
func (q *MockFilter) ReadOne(out interface{}) Op {
return newOp(func(m mockOp) error {
slicePtrVal := reflect.New(reflect.SliceOf(reflect.ValueOf(out).Elem().Type()))
err := q.Read(slicePtrVal.Interface()).Run()
if err != nil {
return err
}
sliceVal := slicePtrVal.Elem()
if sliceVal.Len() < 1 {
return RowNotFoundError{}
}
q.assignResult(sliceVal.Index(0).Interface(), out)
return nil
})
}