forked from scylladb/gocql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cassandra_test.go
3128 lines (2639 loc) · 96.7 KB
/
cassandra_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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// +build all cassandra
package gocql
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"math/big"
"net"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode"
inf "gopkg.in/inf.v0"
)
func TestEmptyHosts(t *testing.T) {
cluster := createCluster()
cluster.Hosts = nil
if session, err := cluster.CreateSession(); err == nil {
session.Close()
t.Error("expected err, got nil")
}
}
func TestInvalidPeerEntry(t *testing.T) {
t.Skip("dont mutate system tables, rewrite this to test what we mean to test")
session := createSession(t)
// rack, release_version, schema_version, tokens are all null
query := session.Query("INSERT into system.peers (peer, data_center, host_id, rpc_address) VALUES (?, ?, ?, ?)",
"169.254.235.45",
"datacenter1",
"35c0ec48-5109-40fd-9281-9e9d4add2f1e",
"169.254.235.45",
)
if err := query.Exec(); err != nil {
t.Fatal(err)
}
session.Close()
cluster := createCluster()
cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy())
session = createSessionFromCluster(cluster, t)
defer func() {
session.Query("DELETE from system.peers where peer = ?", "169.254.235.45").Exec()
session.Close()
}()
// check we can perform a query
iter := session.Query("select peer from system.peers").Iter()
var peer string
for iter.Scan(&peer) {
}
if err := iter.Close(); err != nil {
t.Fatal(err)
}
}
//TestUseStatementError checks to make sure the correct error is returned when the user tries to execute a use statement.
func TestUseStatementError(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := session.Query("USE gocql_test").Exec(); err != nil {
if err != ErrUseStmt {
t.Fatalf("expected ErrUseStmt, got " + err.Error())
}
} else {
t.Fatal("expected err, got nil.")
}
}
//TestInvalidKeyspace checks that an invalid keyspace will return promptly and without a flood of connections
func TestInvalidKeyspace(t *testing.T) {
cluster := createCluster()
cluster.Keyspace = "invalidKeyspace"
session, err := cluster.CreateSession()
if err != nil {
if err != ErrNoConnectionsStarted {
t.Fatalf("Expected ErrNoConnections but got %v", err)
}
} else {
session.Close() //Clean up the session
t.Fatal("expected err, got nil.")
}
}
func TestTracing(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.trace (id int primary key)`); err != nil {
t.Fatal("create:", err)
}
buf := &bytes.Buffer{}
trace := &traceWriter{session: session, w: buf}
if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil {
t.Fatal("insert:", err)
} else if buf.Len() == 0 {
t.Fatal("insert: failed to obtain any tracing")
}
trace.mu.Lock()
buf.Reset()
trace.mu.Unlock()
var value int
if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil {
t.Fatal("select:", err)
} else if value != 42 {
t.Fatalf("value: expected %d, got %d", 42, value)
} else if buf.Len() == 0 {
t.Fatal("select: failed to obtain any tracing")
}
// also works from session tracer
session.SetTrace(trace)
trace.mu.Lock()
buf.Reset()
trace.mu.Unlock()
if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Scan(&value); err != nil {
t.Fatal("select:", err)
}
if buf.Len() == 0 {
t.Fatal("select: failed to obtain any tracing")
}
}
func TestObserve(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.observe (id int primary key)`); err != nil {
t.Fatal("create:", err)
}
var (
observedErr error
observedKeyspace string
observedStmt string
)
const keyspace = "gocql_test"
resetObserved := func() {
observedErr = errors.New("placeholder only") // used to distinguish err=nil cases
observedKeyspace = ""
observedStmt = ""
}
observer := funcQueryObserver(func(ctx context.Context, o ObservedQuery) {
observedKeyspace = o.Keyspace
observedStmt = o.Statement
observedErr = o.Err
})
// select before inserted, will error but the reporting is err=nil as the query is valid
resetObserved()
var value int
if err := session.Query(`SELECT id FROM observe WHERE id = ?`, 43).Observer(observer).Scan(&value); err == nil {
t.Fatal("select: expected error")
} else if observedErr != nil {
t.Fatalf("select: observed error expected nil, got %q", observedErr)
} else if observedKeyspace != keyspace {
t.Fatal("select: unexpected observed keyspace", observedKeyspace)
} else if observedStmt != `SELECT id FROM observe WHERE id = ?` {
t.Fatal("select: unexpected observed stmt", observedStmt)
}
resetObserved()
if err := session.Query(`INSERT INTO observe (id) VALUES (?)`, 42).Observer(observer).Exec(); err != nil {
t.Fatal("insert:", err)
} else if observedErr != nil {
t.Fatal("insert:", observedErr)
} else if observedKeyspace != keyspace {
t.Fatal("insert: unexpected observed keyspace", observedKeyspace)
} else if observedStmt != `INSERT INTO observe (id) VALUES (?)` {
t.Fatal("insert: unexpected observed stmt", observedStmt)
}
resetObserved()
value = 0
if err := session.Query(`SELECT id FROM observe WHERE id = ?`, 42).Observer(observer).Scan(&value); err != nil {
t.Fatal("select:", err)
} else if value != 42 {
t.Fatalf("value: expected %d, got %d", 42, value)
} else if observedErr != nil {
t.Fatal("select:", observedErr)
} else if observedKeyspace != keyspace {
t.Fatal("select: unexpected observed keyspace", observedKeyspace)
} else if observedStmt != `SELECT id FROM observe WHERE id = ?` {
t.Fatal("select: unexpected observed stmt", observedStmt)
}
// also works from session observer
resetObserved()
oSession := createSession(t, func(config *ClusterConfig) { config.QueryObserver = observer })
if err := oSession.Query(`SELECT id FROM observe WHERE id = ?`, 42).Scan(&value); err != nil {
t.Fatal("select:", err)
} else if observedErr != nil {
t.Fatal("select:", err)
} else if observedKeyspace != keyspace {
t.Fatal("select: unexpected observed keyspace", observedKeyspace)
} else if observedStmt != `SELECT id FROM observe WHERE id = ?` {
t.Fatal("select: unexpected observed stmt", observedStmt)
}
// reports errors when the query is poorly formed
resetObserved()
value = 0
if err := session.Query(`SELECT id FROM unknown_table WHERE id = ?`, 42).Observer(observer).Scan(&value); err == nil {
t.Fatal("select: expecting error")
} else if observedErr == nil {
t.Fatal("select: expecting observed error")
} else if observedKeyspace != keyspace {
t.Fatal("select: unexpected observed keyspace", observedKeyspace)
} else if observedStmt != `SELECT id FROM unknown_table WHERE id = ?` {
t.Fatal("select: unexpected observed stmt", observedStmt)
}
}
func TestObserve_Pagination(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.observe2 (id int, PRIMARY KEY (id))`); err != nil {
t.Fatal("create:", err)
}
var observedRows int
resetObserved := func() {
observedRows = -1
}
observer := funcQueryObserver(func(ctx context.Context, o ObservedQuery) {
observedRows = o.Rows
})
// insert 100 entries, relevant for pagination
for i := 0; i < 50; i++ {
if err := session.Query(`INSERT INTO observe2 (id) VALUES (?)`, i).Exec(); err != nil {
t.Fatal("insert:", err)
}
}
resetObserved()
// read the 100 entries in paginated entries of size 10. Expecting 5 observations, each with 10 rows
scanner := session.Query(`SELECT id FROM observe2 LIMIT 100`).
Observer(observer).
PageSize(10).
Iter().Scanner()
for i := 0; i < 50; i++ {
if !scanner.Next() {
t.Fatalf("next: should still be true: %d: %v", i, scanner.Err())
}
if i%10 == 0 {
if observedRows != 10 {
t.Fatalf("next: expecting a paginated query with 10 entries, got: %d (%d)", observedRows, i)
}
} else if observedRows != -1 {
t.Fatalf("next: not expecting paginated query (-1 entries), got: %d", observedRows)
}
resetObserved()
}
if scanner.Next() {
t.Fatal("next: no more entries where expected")
}
}
func TestPaging(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("Paging not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, "CREATE TABLE gocql_test.paging (id int primary key)"); err != nil {
t.Fatal("create table:", err)
}
for i := 0; i < 100; i++ {
if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil {
t.Fatal("insert:", err)
}
}
iter := session.Query("SELECT id FROM paging").PageSize(10).Iter()
var id int
count := 0
for iter.Scan(&id) {
count++
}
if err := iter.Close(); err != nil {
t.Fatal("close:", err)
}
if count != 100 {
t.Fatalf("expected %d, got %d", 100, count)
}
}
func TestPagingWithBind(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("Paging not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, "CREATE TABLE gocql_test.paging_bind (id int, val int, primary key(id,val))"); err != nil {
t.Fatal("create table:", err)
}
for i := 0; i < 100; i++ {
if err := session.Query("INSERT INTO paging_bind (id,val) VALUES (?,?)", 1,i).Exec(); err != nil {
t.Fatal("insert:", err)
}
}
q := session.Query("SELECT val FROM paging_bind WHERE id = ? AND val < ?",1, 50).PageSize(10)
iter := q.Iter()
var id int
count := 0
for iter.Scan(&id) {
count++
}
if err := iter.Close(); err != nil {
t.Fatal("close:", err)
}
if count != 50 {
t.Fatalf("expected %d, got %d", 50, count)
}
iter = q.Bind(1, 20).Iter()
count = 0
for iter.Scan(&id) {
count++
}
if count != 20 {
t.Fatalf("expected %d, got %d", 20, count)
}
if err := iter.Close(); err != nil {
t.Fatal("close:", err)
}
}
func TestCAS(t *testing.T) {
cluster := createCluster()
cluster.SerialConsistency = LocalSerial
session := createSessionFromCluster(cluster, t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.cas_table (
title varchar,
revid timeuuid,
last_modified timestamp,
PRIMARY KEY (title, revid)
)`); err != nil {
t.Fatal("create:", err)
}
title, revid, modified := "baz", TimeUUID(), time.Now()
var titleCAS string
var revidCAS UUID
var modifiedCAS time.Time
if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
VALUES (?, ?, ?) IF NOT EXISTS`,
title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatal("insert should have been applied")
}
if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
VALUES (?, ?, ?) IF NOT EXISTS`,
title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatal("insert should not have been applied")
} else if title != titleCAS || revid != revidCAS {
t.Fatalf("expected %s/%v/%v but got %s/%v/%v", title, revid, modified, titleCAS, revidCAS, modifiedCAS)
}
tenSecondsLater := modified.Add(10 * time.Second)
if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
title, revid, tenSecondsLater).ScanCAS(&modifiedCAS); err != nil {
t.Fatal("delete:", err)
} else if applied {
t.Fatal("delete should have not been applied")
}
if modifiedCAS.Unix() != tenSecondsLater.Add(-10*time.Second).Unix() {
t.Fatalf("Was expecting modified CAS to be %v; but was one second later", modifiedCAS.UTC())
}
if _, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
title, revid, tenSecondsLater).ScanCAS(); !strings.HasPrefix(err.Error(), "gocql: not enough columns to scan into") {
t.Fatalf("delete: was expecting count mismatch error but got: %q", err.Error())
}
if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
title, revid, modified).ScanCAS(&modifiedCAS); err != nil {
t.Fatal("delete:", err)
} else if !applied {
t.Fatal("delete should have been applied")
}
if err := session.Query(`TRUNCATE cas_table`).Exec(); err != nil {
t.Fatal("truncate:", err)
}
successBatch := session.NewBatch(LoggedBatch)
successBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title, revid, modified)
if applied, _, err := session.ExecuteBatchCAS(successBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
}
successBatch = session.NewBatch(LoggedBatch)
successBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title+"_foo", revid, modified)
casMap := make(map[string]interface{})
if applied, _, err := session.MapExecuteBatchCAS(successBatch, casMap); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatal("insert should have been applied")
}
failBatch := session.NewBatch(LoggedBatch)
failBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title, revid, modified)
if applied, _, err := session.ExecuteBatchCAS(successBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
}
insertBatch := session.NewBatch(LoggedBatch)
insertBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES ('_foo', 2c3af400-73a4-11e5-9381-29463d90c3f0, DATEOF(NOW()))")
insertBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES ('_foo', 3e4ad2f1-73a4-11e5-9381-29463d90c3f0, DATEOF(NOW()))")
if err := session.ExecuteBatch(insertBatch); err != nil {
t.Fatal("insert:", err)
}
failBatch = session.NewBatch(LoggedBatch)
failBatch.Query("UPDATE cas_table SET last_modified = DATEOF(NOW()) WHERE title='_foo' AND revid=2c3af400-73a4-11e5-9381-29463d90c3f0 IF last_modified=DATEOF(NOW());")
failBatch.Query("UPDATE cas_table SET last_modified = DATEOF(NOW()) WHERE title='_foo' AND revid=3e4ad2f1-73a4-11e5-9381-29463d90c3f0 IF last_modified=DATEOF(NOW());")
if applied, iter, err := session.ExecuteBatchCAS(failBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
} else {
if scan := iter.Scan(&applied, &titleCAS, &revidCAS, &modifiedCAS); scan && applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
} else if !scan {
t.Fatal("should have scanned another row")
}
if err := iter.Close(); err != nil {
t.Fatal("scan:", err)
}
}
}
func TestDurationType(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < 5 {
t.Skip("Duration type is not supported. Please use protocol version >= 4 and cassandra version >= 3.11")
}
if err := createTable(session, `CREATE TABLE gocql_test.duration_table (
k int primary key, v duration
)`); err != nil {
t.Fatal("create:", err)
}
durations := []Duration{
Duration{
Months: 250,
Days: 500,
Nanoseconds: 300010001,
},
Duration{
Months: -250,
Days: -500,
Nanoseconds: -300010001,
},
Duration{
Months: 0,
Days: 128,
Nanoseconds: 127,
},
Duration{
Months: 0x7FFFFFFF,
Days: 0x7FFFFFFF,
Nanoseconds: 0x7FFFFFFFFFFFFFFF,
},
}
for _, durationSend := range durations {
if err := session.Query(`INSERT INTO gocql_test.duration_table (k, v) VALUES (1, ?)`, durationSend).Exec(); err != nil {
t.Fatal(err)
}
var id int
var duration Duration
if err := session.Query(`SELECT k, v FROM gocql_test.duration_table`).Scan(&id, &duration); err != nil {
t.Fatal(err)
}
if duration.Months != durationSend.Months || duration.Days != durationSend.Days || duration.Nanoseconds != durationSend.Nanoseconds {
t.Fatalf("Unexpeted value returned, expected=%v, received=%v", durationSend, duration)
}
}
}
func TestMapScanCAS(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.cas_table2 (
title varchar,
revid timeuuid,
last_modified timestamp,
deleted boolean,
PRIMARY KEY (title, revid)
)`); err != nil {
t.Fatal("create:", err)
}
title, revid, modified, deleted := "baz", TimeUUID(), time.Now(), false
mapCAS := map[string]interface{}{}
if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
VALUES (?, ?, ?, ?) IF NOT EXISTS`,
title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", title, revid, modified)
}
mapCAS = map[string]interface{}{}
if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
VALUES (?, ?, ?, ?) IF NOT EXISTS`,
title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", title, revid, modified)
} else if title != mapCAS["title"] || revid != mapCAS["revid"] || deleted != mapCAS["deleted"] {
t.Fatalf("expected %s/%v/%v/%v but got %s/%v/%v%v", title, revid, modified, false, mapCAS["title"], mapCAS["revid"], mapCAS["last_modified"], mapCAS["deleted"])
}
}
func TestBatch(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.batch_table (id int primary key)`); err != nil {
t.Fatal("create table:", err)
}
batch := session.NewBatch(LoggedBatch)
for i := 0; i < 100; i++ {
batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i)
}
if err := session.ExecuteBatch(batch); err != nil {
t.Fatal("execute batch:", err)
}
count := 0
if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil {
t.Fatal("select count:", err)
} else if count != 100 {
t.Fatalf("count: expected %d, got %d\n", 100, count)
}
}
func TestUnpreparedBatch(t *testing.T) {
t.Skip("FLAKE skipping")
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.batch_unprepared (id int primary key, c counter)`); err != nil {
t.Fatal("create table:", err)
}
var batch *Batch
if session.cfg.ProtoVersion == 2 {
batch = session.NewBatch(CounterBatch)
} else {
batch = session.NewBatch(UnloggedBatch)
}
for i := 0; i < 100; i++ {
batch.Query(`UPDATE batch_unprepared SET c = c + 1 WHERE id = 1`)
}
if err := session.ExecuteBatch(batch); err != nil {
t.Fatal("execute batch:", err)
}
count := 0
if err := session.Query(`SELECT COUNT(*) FROM batch_unprepared`).Scan(&count); err != nil {
t.Fatal("select count:", err)
} else if count != 1 {
t.Fatalf("count: expected %d, got %d\n", 100, count)
}
if err := session.Query(`SELECT c FROM batch_unprepared`).Scan(&count); err != nil {
t.Fatal("select count:", err)
} else if count != 100 {
t.Fatalf("count: expected %d, got %d\n", 100, count)
}
}
// TestBatchLimit tests gocql to make sure batch operations larger than the maximum
// statement limit are not submitted to a cassandra node.
func TestBatchLimit(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.batch_table2 (id int primary key)`); err != nil {
t.Fatal("create table:", err)
}
batch := session.NewBatch(LoggedBatch)
for i := 0; i < 65537; i++ {
batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i)
}
if err := session.ExecuteBatch(batch); err != ErrTooManyStmts {
t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.")
}
}
func TestWhereIn(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.where_in_table (id int, cluster int, primary key (id,cluster))`); err != nil {
t.Fatal("create table:", err)
}
if err := session.Query("INSERT INTO where_in_table (id, cluster) VALUES (?,?)", 100, 200).Exec(); err != nil {
t.Fatal("insert:", err)
}
iter := session.Query("SELECT * FROM where_in_table WHERE id = ? AND cluster IN (?)", 100, 200).Iter()
var id, cluster int
count := 0
for iter.Scan(&id, &cluster) {
count++
}
if id != 100 || cluster != 200 {
t.Fatalf("Was expecting id and cluster to be (100,200) but were (%d,%d)", id, cluster)
}
}
// TestTooManyQueryArgs tests to make sure the library correctly handles the application level bug
// whereby too many query arguments are passed to a query
func TestTooManyQueryArgs(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.too_many_query_args (id int primary key, value int)`); err != nil {
t.Fatal("create table:", err)
}
_, err := session.Query(`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2).Iter().SliceMap()
if err == nil {
t.Fatal("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an error")
}
batch := session.NewBatch(UnloggedBatch)
batch.Query("INSERT INTO too_many_query_args (id, value) VALUES (?, ?)", 1, 2, 3)
err = session.ExecuteBatch(batch)
if err == nil {
t.Fatal("'`INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an error")
}
// TODO: should indicate via an error code that it is an invalid arg?
}
// TestNotEnoughQueryArgs tests to make sure the library correctly handles the application level bug
// whereby not enough query arguments are passed to a query
func TestNotEnoughQueryArgs(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.not_enough_query_args (id int, cluster int, value int, primary key (id, cluster))`); err != nil {
t.Fatal("create table:", err)
}
_, err := session.Query(`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1).Iter().SliceMap()
if err == nil {
t.Fatal("'`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1' should return an error")
}
batch := session.NewBatch(UnloggedBatch)
batch.Query("INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)", 1, 2)
err = session.ExecuteBatch(batch)
if err == nil {
t.Fatal("'`INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an error")
}
}
// TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly
// and prevents an infinite loop of connection retries.
func TestCreateSessionTimeout(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
select {
case <-time.After(2 * time.Second):
t.Error("no startup timeout")
case <-ctx.Done():
}
}()
cluster := createCluster()
cluster.Hosts = []string{"127.0.0.1:1"}
session, err := cluster.CreateSession()
if err == nil {
session.Close()
t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.")
}
}
func TestReconnection(t *testing.T) {
cluster := createCluster()
cluster.ReconnectInterval = 1 * time.Second
session := createSessionFromCluster(cluster, t)
defer session.Close()
h := session.ring.allHosts()[0]
session.handleNodeDown(h.ConnectAddress(), h.Port())
if h.State() != NodeDown {
t.Fatal("Host should be NodeDown but not.")
}
time.Sleep(cluster.ReconnectInterval + h.Version().nodeUpDelay() + 1*time.Second)
if h.State() != NodeUp {
t.Fatal("Host should be NodeUp but not. Failed to reconnect.")
}
}
type FullName struct {
FirstName string
LastName string
}
func (n FullName) MarshalCQL(info TypeInfo) ([]byte, error) {
return []byte(n.FirstName + " " + n.LastName), nil
}
func (n *FullName) UnmarshalCQL(info TypeInfo, data []byte) error {
t := strings.SplitN(string(data), " ", 2)
n.FirstName, n.LastName = t[0], t[1]
return nil
}
func TestMapScanWithRefMap(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_map_ref_table (
testtext text PRIMARY KEY,
testfullname text,
testint int,
)`); err != nil {
t.Fatal("create table:", err)
}
m := make(map[string]interface{})
m["testtext"] = "testtext"
m["testfullname"] = FullName{"John", "Doe"}
m["testint"] = 100
if err := session.Query(`INSERT INTO scan_map_ref_table (testtext, testfullname, testint) values (?,?,?)`,
m["testtext"], m["testfullname"], m["testint"]).Exec(); err != nil {
t.Fatal("insert:", err)
}
var testText string
var testFullName FullName
ret := map[string]interface{}{
"testtext": &testText,
"testfullname": &testFullName,
// testint is not set here.
}
iter := session.Query(`SELECT * FROM scan_map_ref_table`).Iter()
if ok := iter.MapScan(ret); !ok {
t.Fatal("select:", iter.Close())
} else {
if ret["testtext"] != "testtext" {
t.Fatal("returned testtext did not match")
}
f := ret["testfullname"].(FullName)
if f.FirstName != "John" || f.LastName != "Doe" {
t.Fatal("returned testfullname did not match")
}
if ret["testint"] != 100 {
t.Fatal("returned testinit did not match")
}
}
if testText != "testtext" {
t.Fatal("returned testtext did not match")
}
if testFullName.FirstName != "John" || testFullName.LastName != "Doe" {
t.Fatal("returned testfullname did not match")
}
// using MapScan to read a nil int value
intp := new(int64)
ret = map[string]interface{}{
"testint": &intp,
}
if err := session.Query("INSERT INTO scan_map_ref_table(testtext, testint) VALUES(?, ?)", "null-int", nil).Exec(); err != nil {
t.Fatal(err)
}
err := session.Query(`SELECT testint FROM scan_map_ref_table WHERE testtext = ?`, "null-int").MapScan(ret)
if err != nil {
t.Fatal(err)
} else if v := ret["testint"].(*int64); v != nil {
t.Fatalf("testint should be nil got %+#v", v)
}
}
func TestMapScan(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_map_table (
fullname text PRIMARY KEY,
age int,
address inet,
)`); err != nil {
t.Fatal("create table:", err)
}
if err := session.Query(`INSERT INTO scan_map_table (fullname, age, address) values (?,?,?)`,
"Grace Hopper", 31, net.ParseIP("10.0.0.1")).Exec(); err != nil {
t.Fatal("insert:", err)
}
if err := session.Query(`INSERT INTO scan_map_table (fullname, age, address) values (?,?,?)`,
"Ada Lovelace", 30, net.ParseIP("10.0.0.2")).Exec(); err != nil {
t.Fatal("insert:", err)
}
iter := session.Query(`SELECT * FROM scan_map_table`).Iter()
// First iteration
row := make(map[string]interface{})
if !iter.MapScan(row) {
t.Fatal("select:", iter.Close())
}
assertEqual(t, "fullname", "Ada Lovelace", row["fullname"])
assertEqual(t, "age", 30, row["age"])
assertEqual(t, "address", "10.0.0.2", row["address"])
// Second iteration using a new map
row = make(map[string]interface{})
if !iter.MapScan(row) {
t.Fatal("select:", iter.Close())
}
assertEqual(t, "fullname", "Grace Hopper", row["fullname"])
assertEqual(t, "age", 31, row["age"])
assertEqual(t, "address", "10.0.0.1", row["address"])
}
func TestSliceMap(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.slice_map_table (
testuuid timeuuid PRIMARY KEY,
testtimestamp timestamp,
testvarchar varchar,
testbigint bigint,
testblob blob,
testbool boolean,
testfloat float,
testdouble double,
testint int,
testdecimal decimal,
testlist list<text>,
testset set<int>,
testmap map<varchar, varchar>,
testvarint varint,
testinet inet
)`); err != nil {
t.Fatal("create table:", err)
}
m := make(map[string]interface{})
bigInt := new(big.Int)
if _, ok := bigInt.SetString("830169365738487321165427203929228", 10); !ok {
t.Fatal("Failed setting bigint by string")
}
m["testuuid"] = TimeUUID()
m["testvarchar"] = "Test VarChar"
m["testbigint"] = time.Now().Unix()
m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
m["testblob"] = []byte("test blob")
m["testbool"] = true
m["testfloat"] = float32(4.564)
m["testdouble"] = float64(4.815162342)
m["testint"] = 2343
m["testdecimal"] = inf.NewDec(100, 0)
m["testlist"] = []string{"quux", "foo", "bar", "baz", "quux"}
m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
m["testvarint"] = bigInt
m["testinet"] = "213.212.2.19"
sliceMap := []map[string]interface{}{m}
if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testlist, testset, testmap, testvarint, testinet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
m["testuuid"], m["testtimestamp"], m["testvarchar"], m["testbigint"], m["testblob"], m["testbool"], m["testfloat"], m["testdouble"], m["testint"], m["testdecimal"], m["testlist"], m["testset"], m["testmap"], m["testvarint"], m["testinet"]).Exec(); err != nil {
t.Fatal("insert:", err)
}
if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
t.Fatal("select:", retErr)
} else {
matchSliceMap(t, sliceMap, returned[0])
}
// Test for Iter.MapScan()
{
testMap := make(map[string]interface{})
if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
t.Fatal("MapScan failed to work with one row")
}
matchSliceMap(t, sliceMap, testMap)
}
// Test for Query.MapScan()
{
testMap := make(map[string]interface{})
if session.Query(`SELECT * FROM slice_map_table`).MapScan(testMap) != nil {
t.Fatal("MapScan failed to work with one row")
}
matchSliceMap(t, sliceMap, testMap)
}
}
func matchSliceMap(t *testing.T, sliceMap []map[string]interface{}, testMap map[string]interface{}) {
if sliceMap[0]["testuuid"] != testMap["testuuid"] {
t.Fatal("returned testuuid did not match")
}
if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
t.Fatal("returned testtimestamp did not match")
}