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
/
table_test.go
448 lines (403 loc) · 11.5 KB
/
table_test.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
package gocassa
import (
"fmt"
"math/rand"
"strings"
"testing"
"time"
"github.com/gocql/gocql"
"github.com/stretchr/testify/assert"
)
func createIf(cs TableChanger, tes *testing.T) {
err := cs.(TableChanger).Recreate()
if err != nil {
tes.Fatal(err)
}
}
// cqlsh> CREATE TABLE test.customer1 (id text, name text, PRIMARY KEY((id, name)));
func TestTables(t *testing.T) {
res, err := ns.(*k).Tables()
if err != nil {
t.Fatal(err)
}
if len(res) == 0 {
t.Fatal("Not found ", len(res))
}
}
func TestCreateTable(t *testing.T) {
rand.Seed(time.Now().Unix())
name := fmt.Sprintf("customer_%v", rand.Int()%100)
cs := ns.Table(name, Customer{}, Keys{
PartitionKeys: []string{"Id", "Name"},
})
createIf(cs, t)
err := cs.Set(Customer{
Id: "1001",
Name: "Joe",
}).Run()
if err != nil {
t.Fatal(err)
}
res := &[]Customer{}
err = cs.Where(Eq("Id", "1001"), Eq("Name", "Joe")).Read(res).Run()
if err != nil {
t.Fatal(err)
}
if len(*res) != 1 {
t.Fatal("Not found ", len(*res))
}
err = ns.(*k).DropTable(name)
if err != nil {
t.Fatal(err)
}
}
func TestClusteringOrder(t *testing.T) {
options := Options{}.AppendClusteringOrder("Id", DESC)
name := "customer_by_name"
cs := ns.Table(name, Customer{}, Keys{
PartitionKeys: []string{"Name"},
ClusteringColumns: []string{"Id"},
}).WithOptions(options)
createIf(cs, t)
customers := []Customer{
Customer{
Id: "1001",
Name: "Brian",
},
Customer{
Id: "1002",
Name: "Adam",
},
Customer{
Id: "1003",
Name: "Brian",
},
Customer{
Id: "1004",
Name: "Brian",
},
}
for _, c := range customers {
err := cs.Set(c).Run()
if err != nil {
t.Fatal(err)
}
}
res := &[]Customer{}
err := cs.Where(Eq("Name", "Brian")).Read(res).Run()
if err != nil {
t.Fatal(err)
}
expected := []string{"1004", "1003", "1001"}
if len(*res) != len(expected) {
t.Fatal("Expected", len(*res), " results, got", len(*res))
}
for i, id := range expected {
if (*res)[i].Id != id {
t.Fatal("Got result out of order. i:", i, "expected ID:", id, "actual ID:", (*res)[i].Id)
}
}
}
func TestClusteringOrderMultipl(t *testing.T) {
options := Options{}.AppendClusteringOrder("Tag", DESC).AppendClusteringOrder("Id", DESC)
name := "customer_by_name2"
cs := ns.Table(name, Customer2{}, Keys{
PartitionKeys: []string{"Name"},
ClusteringColumns: []string{"Tag", "Id"},
}).WithOptions(options)
createIf(cs, t)
customers := []Customer2{
Customer2{
Id: "1001",
Name: "Brian",
Tag: "B",
},
Customer2{
Id: "1002",
Name: "Adam",
Tag: "A",
},
Customer2{
Id: "1003",
Name: "Brian",
Tag: "A",
},
Customer2{
Id: "1004",
Name: "Brian",
Tag: "B",
},
}
for _, c := range customers {
err := cs.Set(c).Run()
if err != nil {
t.Fatal(err)
}
}
res := &[]Customer2{}
err := cs.Where(Eq("Name", "Brian")).Read(res).Run()
if err != nil {
t.Fatal(err)
}
expected := []struct {
Tag string
Id string
}{
{"B", "1004"},
{"B", "1001"},
{"A", "1003"},
}
if len(*res) != len(expected) {
t.Fatal("Expected", len(*res), " results, got", len(*res))
}
for i, e := range expected {
result := (*res)[i]
if result.Id != e.Id || result.Tag != e.Tag {
t.Fatal("Got result out of order. i:", i, "expected ID:", e.Id, "actual ID:", result.Id, "expected tag:", e.Tag, "actual tag:", result.Tag)
}
}
}
func TestCreateStatement(t *testing.T) {
cs := ns.Table("something", Customer{}, Keys{
PartitionKeys: []string{"Id", "Name"},
})
stmt, err := cs.CreateStatement()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(stmt.Query(), "something") {
t.Fatal(stmt.Query())
}
stmt, err = cs.WithOptions(Options{TableName: "funky"}).CreateStatement()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(stmt.Query(), "funky") {
t.Fatal(stmt.Query())
}
// if clustering order is not specified, it should omit the clustering order by and use the default
if strings.Contains(stmt.Query(), "WITH CLUSTERING ORDER BY") {
t.Fatal(stmt.Query())
}
}
func TestAllowFiltering(t *testing.T) {
name := "allow_filtering"
cs := ns.Table(name, Customer2{}, Keys{
PartitionKeys: []string{"Name"},
ClusteringColumns: []string{"Tag", "Id"},
})
createIf(cs, t)
c2 := Customer2{}
//This shouldn't contain allow filtering
st := cs.Where(Eq("Name", "Brian")).Read(&c2).GenerateStatement()
if strings.Contains(st.Query(), "ALLOW FILTERING") {
t.Error("Allow filtering should be disabled by default")
}
op := Options{AllowFiltering: true}
stAllow := cs.Where(Eq("", "")).Read(&c2).WithOptions(op).GenerateStatement()
if !strings.Contains(stAllow.Query(), "ALLOW FILTERING") {
t.Error("Allow filtering show be included in the statement")
}
}
func TestKeysCreation(t *testing.T) {
cs := ns.Table("composite_keys", Customer{}, Keys{
PartitionKeys: []string{"Id", "Name"},
})
stmt, err := cs.CreateStatement()
if err != nil {
t.Fatal(err)
}
//composite
if !strings.Contains(stmt.Query(), "PRIMARY KEY ((id, name ))") {
t.Fatal(stmt.Query())
}
cs = ns.Table("compound_keys", Customer{}, Keys{
PartitionKeys: []string{"Id", "Name"},
Compound: true,
})
stmt, err = cs.CreateStatement()
if err != nil {
t.Fatal(err)
}
//compound
if !strings.Contains(stmt.Query(), "PRIMARY KEY (id, name )") {
t.Fatal(stmt.Query())
}
cs = ns.Table("clustering_keys", Customer{}, Keys{
PartitionKeys: []string{"Id"},
ClusteringColumns: []string{"Name"},
})
stmt, err = cs.CreateStatement()
if err != nil {
t.Fatal(err)
}
//with columns
if !strings.Contains(stmt.Query(), "PRIMARY KEY ((id), name)") {
t.Fatal(stmt.Query())
}
//compound gets ignored when using clustering columns
cs = ns.Table("clustering_keys", Customer{}, Keys{
PartitionKeys: []string{"Id"},
ClusteringColumns: []string{"Name"},
Compound: true,
})
stmt, err = cs.CreateStatement()
if err != nil {
t.Fatal(err)
}
//with columns
if !strings.Contains(stmt.Query(), "PRIMARY KEY ((id), name)") {
t.Fatal(stmt.Query())
}
}
// Mock QueryExecutor that keeps track of options passed to it
type OptionCheckingQE struct {
stmt Statement
opts *Options
}
func (qe *OptionCheckingQE) QueryWithOptions(opts Options, stmt Statement, scanner Scanner) error {
qe.stmt = stmt
qe.opts.Consistency = opts.Consistency
return nil
}
func (qe *OptionCheckingQE) Query(stmt Statement, scanner Scanner) error {
return qe.QueryWithOptions(Options{}, stmt, scanner)
}
func (qe *OptionCheckingQE) ExecuteWithOptions(opts Options, stmt Statement) error {
qe.stmt = stmt
qe.opts.Consistency = opts.Consistency
return nil
}
func (qe *OptionCheckingQE) Execute(stmt Statement) error {
return qe.ExecuteWithOptions(Options{}, stmt)
}
func (qe *OptionCheckingQE) ExecuteAtomically(stmt []Statement) error {
return nil
}
func (qe *OptionCheckingQE) ExecuteAtomicallyWithOptions(opts Options, stmt []Statement) error {
qe.opts.Consistency = opts.Consistency
return nil
}
func TestQueryWithConsistency(t *testing.T) {
// It's tricky to verify this against a live DB, so mock out the
// query executor and make sure the right options get passed
// through
resultOpts := Options{}
qe := &OptionCheckingQE{opts: &resultOpts}
conn := &connection{q: qe}
ks := conn.KeySpace("some ks")
cs := ks.Table("customerWithConsistency", Customer{}, Keys{PartitionKeys: []string{"Id"}})
res := &[]Customer{}
cons := gocql.Quorum
opts := Options{Consistency: &cons}
q := cs.Where(Eq("Id", 1)).Read(res).WithOptions(opts)
if err := q.Run(); err != nil {
t.Fatal(err)
}
if resultOpts.Consistency == nil {
t.Fatal(fmt.Sprint("Expected consistency:", cons, "got: nil"))
}
if resultOpts.Consistency != nil && *resultOpts.Consistency != cons {
t.Fatal(fmt.Sprint("Expected consistency:", cons, "got:", resultOpts.Consistency))
}
}
func TestExecuteWithConsistency(t *testing.T) {
resultOpts := Options{}
qe := &OptionCheckingQE{opts: &resultOpts}
conn := &connection{q: qe}
ks := conn.KeySpace("some ks")
cs := ks.Table("customerWithConsistency2", Customer{}, Keys{PartitionKeys: []string{"Id"}})
cons := gocql.All
opts := Options{Consistency: &cons}
// This calls Execute() under the covers
err := cs.Set(Customer{
Id: "100",
Name: "Joe",
}).WithOptions(opts).Run()
if err != nil {
t.Fatal(err)
}
if resultOpts.Consistency == nil {
t.Fatal(fmt.Sprint("Expected consistency:", cons, "got: nil"))
}
if resultOpts.Consistency != nil && *resultOpts.Consistency != cons {
t.Fatal(fmt.Sprint("Expected consistency:", cons, "got:", resultOpts.Consistency))
}
}
func TestExecuteWithNullableFields(t *testing.T) {
type UserBasic struct {
Id string
Metadata []byte
}
qe := &OptionCheckingQE{opts: &Options{}}
conn := &connection{q: qe}
ks := conn.KeySpace("user")
cs := ks.Table("user", UserBasic{}, Keys{PartitionKeys: []string{"Id"}}).
WithOptions(Options{TableName: "user_by_id"})
// inserting primary key (ID) only (with a nullable field)
err := cs.Set(UserBasic{Id: "100"}).Run()
assert.NoError(t, err)
assert.Equal(t, "INSERT INTO user.user_by_id (id, metadata) VALUES (?, ?)", qe.stmt.Query())
// upserting with metadata set
err = cs.Set(UserBasic{Id: "100", Metadata: []byte{0x02}}).Run()
assert.NoError(t, err)
assert.Equal(t, "UPDATE user.user_by_id SET metadata = ? WHERE id = ?", qe.stmt.Query())
// upserting with a non-nullable field
type UserWithPhone struct {
Id string
PhoneNumber *string
Metadata []byte
}
cs = ks.Table("user", UserWithPhone{}, Keys{PartitionKeys: []string{"Id"}}).
WithOptions(Options{TableName: "user_by_id"})
err = cs.Set(UserWithPhone{Id: "100", PhoneNumber: nil}).Run()
assert.NoError(t, err)
assert.Equal(t, "UPDATE user.user_by_id SET metadata = ?, phonenumber = ? WHERE id = ?", qe.stmt.Query())
number := "01189998819991197253"
err = cs.Set(UserWithPhone{Id: "100", PhoneNumber: &number}).Run()
assert.NoError(t, err)
assert.Equal(t, "UPDATE user.user_by_id SET metadata = ?, phonenumber = ? WHERE id = ?", qe.stmt.Query())
type UserWithName struct {
Id string
Name string
Metadata []byte
Status map[string]string
}
cs = ks.Table("user", UserWithName{}, Keys{
PartitionKeys: []string{"Id"}, ClusteringColumns: []string{"Name"}}).
WithOptions(Options{TableName: "user_by_id"})
// inserting with all nullable fields not set
err = cs.Set(UserWithName{Id: "100", Name: "Moss"}).Run()
assert.NoError(t, err)
assert.Equal(t, "INSERT INTO user.user_by_id (id, metadata, name, status) VALUES (?, ?, ?, ?)", qe.stmt.Query())
// upserting with a nullable field actually set
err = cs.Set(UserWithName{Id: "100", Name: "Moss", Status: map[string]string{"foo": "bar"}}).Run()
assert.NoError(t, err)
assert.Equal(t, "UPDATE user.user_by_id SET metadata = ?, status = ? WHERE id = ? AND name = ?", qe.stmt.Query())
}
func TestAllFieldValuesAreNullable(t *testing.T) {
// all collection types defined are nullable
assert.True(t, allFieldValuesAreNullable(map[string]interface{}{
"field1": []byte{},
"field2": map[string]string{},
"field3": [0]int{},
}))
// not nullable due to populated byte array
assert.False(t, allFieldValuesAreNullable(map[string]interface{}{
"field1": []byte{0x00},
"field2": map[string]string{},
"field3": [0]int{},
}))
// not nullable due to string
assert.False(t, allFieldValuesAreNullable(map[string]interface{}{
"field1": []byte{},
"field4": "",
}))
// not nullable due to int
assert.False(t, allFieldValuesAreNullable(map[string]interface{}{
"field2": map[string]string{},
"field5": 0,
}))
// the empty field list is nullable
assert.True(t, allFieldValuesAreNullable(map[string]interface{}{}))
}