forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cassandra_test.go
2415 lines (2014 loc) · 74.6 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 integration
package gocql
import (
"bytes"
"golang.org/x/net/context"
"io"
"math"
"math/big"
"net"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode"
"gopkg.in/inf.v0"
)
// TestAuthentication verifies that gocql will work with a host configured to only accept authenticated connections
func TestAuthentication(t *testing.T) {
if *flagProto < 2 {
t.Skip("Authentication is not supported with protocol < 2")
}
if !*flagRunAuthTest {
t.Skip("Authentication is not configured in the target cluster")
}
cluster := createCluster()
cluster.Authenticator = PasswordAuthenticator{
Username: "cassandra",
Password: "cassandra",
}
session, err := cluster.CreateSession()
if err != nil {
t.Fatalf("Authentication error: %s", err)
}
session.Close()
}
//TestRingDiscovery makes sure that you can autodiscover other cluster members when you seed a cluster config with just one node
func TestRingDiscovery(t *testing.T) {
cluster := createCluster()
cluster.Hosts = clusterHosts[:1]
session := createSessionFromCluster(cluster, t)
defer session.Close()
if *clusterSize > 1 {
// wait for autodiscovery to update the pool with the list of known hosts
time.Sleep(*flagAutoWait)
}
session.pool.mu.RLock()
size := len(session.pool.hostConnPools)
session.pool.mu.RUnlock()
if *clusterSize != size {
t.Fatalf("Expected a cluster size of %d, but actual size was %d", *clusterSize, size)
}
}
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) {
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 := NewTraceWriter(session, 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")
}
buf.Reset()
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")
}
}
func TestPaging(t *testing.T) {
if *flagProto == 1 {
t.Skip("Paging not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
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 TestCAS(t *testing.T) {
if *flagProto == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
cluster := createCluster()
cluster.SerialConsistency = LocalSerial
session := createSessionFromCluster(cluster, t)
defer session.Close()
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 TestMapScanCAS(t *testing.T) {
if *flagProto == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
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) {
if *flagProto == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.batch_table (id int primary key)`); err != nil {
t.Fatal("create table:", err)
}
batch := 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) {
if *flagProto == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
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 *flagProto == 2 {
batch = NewBatch(CounterBatch)
} else {
batch = 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) {
if *flagProto == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.batch_table2 (id int primary key)`); err != nil {
t.Fatal("create table:", err)
}
batch := 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) {
if *flagProto == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
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) {
if *flagProto == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
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) {
go func() {
<-time.After(2 * time.Second)
t.Error("no startup timeout")
}()
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.")
}
}
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")
}
}
}
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")
}
if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
t.Fatal("returned testvarchar did not match")
}
if sliceMap[0]["testbigint"] != testMap["testbigint"] {
t.Fatal("returned testbigint did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
t.Fatal("returned testblob did not match")
}
if sliceMap[0]["testbool"] != testMap["testbool"] {
t.Fatal("returned testbool did not match")
}
if sliceMap[0]["testfloat"] != testMap["testfloat"] {
t.Fatal("returned testfloat did not match")
}
if sliceMap[0]["testdouble"] != testMap["testdouble"] {
t.Fatal("returned testdouble did not match")
}
if sliceMap[0]["testinet"] != testMap["testinet"] {
t.Fatal("returned testinet did not match")
}
expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
returnedDecimal := testMap["testdecimal"].(*inf.Dec)
if expectedDecimal.Cmp(returnedDecimal) != 0 {
t.Fatal("returned testdecimal did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testlist"], testMap["testlist"]) {
t.Fatal("returned testlist did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
t.Fatal("returned testset did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
t.Fatal("returned testmap did not match")
}
if sliceMap[0]["testint"] != testMap["testint"] {
t.Fatal("returned testint did not match")
}
}
func TestScanWithNilArguments(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_with_nil_arguments (
foo varchar,
bar int,
PRIMARY KEY (foo, bar)
)`); err != nil {
t.Fatal("create:", err)
}
for i := 1; i <= 20; i++ {
if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)",
"squares", i*i).Exec(); err != nil {
t.Fatal("insert:", err)
}
}
iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter()
var n int
count := 0
for iter.Scan(nil, &n) {
count += n
}
if err := iter.Close(); err != nil {
t.Fatal("close:", err)
}
if count != 2870 {
t.Fatalf("expected %d, got %d", 2870, count)
}
}
func TestScanCASWithNilArguments(t *testing.T) {
if *flagProto == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_cas_with_nil_arguments (
foo varchar,
bar varchar,
PRIMARY KEY (foo, bar)
)`); err != nil {
t.Fatal("create:", err)
}
foo := "baz"
var cas string
if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
VALUES (?, ?) IF NOT EXISTS`,
foo, foo).ScanCAS(nil, nil); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatal("insert should have been applied")
}
if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
VALUES (?, ?) IF NOT EXISTS`,
foo, foo).ScanCAS(&cas, nil); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatal("insert should not have been applied")
} else if foo != cas {
t.Fatalf("expected %v but got %v", foo, cas)
}
if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
VALUES (?, ?) IF NOT EXISTS`,
foo, foo).ScanCAS(nil, &cas); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatal("insert should not have been applied")
} else if foo != cas {
t.Fatalf("expected %v but got %v", foo, cas)
}
}
func TestRebindQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.rebind_query (id int, value text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 23, "quux").Exec(); err != nil {
t.Fatalf("insert into rebind_query failed, err '%v'", err)
}
if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 24, "w00t").Exec(); err != nil {
t.Fatalf("insert into rebind_query failed, err '%v'", err)
}
q := session.Query("SELECT value FROM rebind_query WHERE ID = ?")
q.Bind(23)
iter := q.Iter()
var value string
for iter.Scan(&value) {
}
if value != "quux" {
t.Fatalf("expected %v but got %v", "quux", value)
}
q.Bind(24)
iter = q.Iter()
for iter.Scan(&value) {
}
if value != "w00t" {
t.Fatalf("expected %v but got %v", "quux", value)
}
}
//TestStaticQueryInfo makes sure that the application can manually bind query parameters using the simplest possible static binding strategy
func TestStaticQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.static_query_info (id int, value text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO static_query_info (id, value) VALUES (?, ?)", 113, "foo").Exec(); err != nil {
t.Fatalf("insert into static_query_info failed, err '%v'", err)
}
autobinder := func(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, 1)
values[0] = 113
return values, nil
}
qry := session.Bind("SELECT id, value FROM static_query_info WHERE id = ?", autobinder)
if err := qry.Exec(); err != nil {
t.Fatalf("expose query info failed, error '%v'", err)
}
iter := qry.Iter()
var id int
var value string
iter.Scan(&id, &value)
if err := iter.Close(); err != nil {
t.Fatalf("query with exposed info failed, err '%v'", err)
}
if value != "foo" {
t.Fatalf("Expected value %s, but got %s", "foo", value)
}
}
type ClusteredKeyValue struct {
Id int
Cluster int
Value string
}
func (kv *ClusteredKeyValue) Bind(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, len(q.Args))
for i, info := range q.Args {
fieldName := upcaseInitial(info.Name)
value := reflect.ValueOf(kv)
field := reflect.Indirect(value).FieldByName(fieldName)
values[i] = field.Addr().Interface()
}
return values, nil
}
func upcaseInitial(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
//TestBoundQueryInfo makes sure that the application can manually bind query parameters using the query meta data supplied at runtime
func TestBoundQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.clustered_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
write := &ClusteredKeyValue{Id: 200, Cluster: 300, Value: "baz"}
insert := session.Bind("INSERT INTO clustered_query_info (id, cluster, value) VALUES (?, ?,?)", write.Bind)
if err := insert.Exec(); err != nil {
t.Fatalf("insert into clustered_query_info failed, err '%v'", err)
}
read := &ClusteredKeyValue{Id: 200, Cluster: 300}
qry := session.Bind("SELECT id, cluster, value FROM clustered_query_info WHERE id = ? and cluster = ?", read.Bind)
iter := qry.Iter()
var id, cluster int
var value string
iter.Scan(&id, &cluster, &value)
if err := iter.Close(); err != nil {
t.Fatalf("query with clustered_query_info info failed, err '%v'", err)
}
if value != "baz" {
t.Fatalf("Expected value %s, but got %s", "baz", value)
}
}
//TestBatchQueryInfo makes sure that the application can manually bind query parameters when executing in a batch
func TestBatchQueryInfo(t *testing.T) {
if *flagProto == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.batch_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
write := func(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, 3)
values[0] = 4000
values[1] = 5000
values[2] = "bar"
return values, nil
}
batch := session.NewBatch(LoggedBatch)
batch.Bind("INSERT INTO batch_query_info (id, cluster, value) VALUES (?, ?,?)", write)
if err := session.ExecuteBatch(batch); err != nil {
t.Fatalf("batch insert into batch_query_info failed, err '%v'", err)
}
read := func(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, 2)
values[0] = 4000