forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cassandra_test.go
2060 lines (1741 loc) · 65.5 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"
"flag"
"fmt"
"log"
"math"
"math/big"
"net"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode"
"gopkg.in/inf.v0"
)
var (
flagCluster = flag.String("cluster", "127.0.0.1", "a comma-separated list of host:port tuples")
flagProto = flag.Int("proto", 2, "protcol version")
flagCQL = flag.String("cql", "3.0.0", "CQL version")
flagRF = flag.Int("rf", 1, "replication factor for test keyspace")
clusterSize = flag.Int("clusterSize", 1, "the expected size of the cluster")
flagRetry = flag.Int("retries", 5, "number of times to retry queries")
flagAutoWait = flag.Duration("autowait", 1000*time.Millisecond, "time to wait for autodiscovery to fill the hosts poll")
flagRunSslTest = flag.Bool("runssl", false, "Set to true to run ssl test")
flagRunAuthTest = flag.Bool("runauth", false, "Set to true to run authentication test")
flagCompressTest = flag.String("compressor", "", "compressor to use")
clusterHosts []string
)
func init() {
flag.Parse()
clusterHosts = strings.Split(*flagCluster, ",")
log.SetFlags(log.Lshortfile | log.LstdFlags)
}
func addSslOptions(cluster *ClusterConfig) *ClusterConfig {
if *flagRunSslTest {
cluster.SslOpts = &SslOptions{
CertPath: "testdata/pki/gocql.crt",
KeyPath: "testdata/pki/gocql.key",
CaPath: "testdata/pki/ca.crt",
EnableHostVerification: false,
}
}
return cluster
}
var initOnce sync.Once
func createTable(s *Session, table string) error {
err := s.Query(table).Consistency(All).Exec()
if *clusterSize > 1 {
// wait for table definition to propogate
time.Sleep(1 * time.Second)
}
return err
}
func createCluster() *ClusterConfig {
cluster := NewCluster(clusterHosts...)
cluster.ProtoVersion = *flagProto
cluster.CQLVersion = *flagCQL
cluster.Timeout = 5 * time.Second
cluster.Consistency = Quorum
if *flagRetry > 0 {
cluster.RetryPolicy = &SimpleRetryPolicy{NumRetries: *flagRetry}
}
switch *flagCompressTest {
case "snappy":
cluster.Compressor = &SnappyCompressor{}
case "":
default:
panic("invalid compressor: " + *flagCompressTest)
}
cluster = addSslOptions(cluster)
return cluster
}
func createKeyspace(tb testing.TB, cluster *ClusterConfig, keyspace string) {
session, err := cluster.CreateSession()
if err != nil {
tb.Fatal("createSession:", err)
}
defer session.Close()
if err = session.Query(`DROP KEYSPACE IF EXISTS ` + keyspace).Exec(); err != nil {
tb.Log("drop keyspace:", err)
}
if err := session.Query(fmt.Sprintf(`CREATE KEYSPACE %s
WITH replication = {
'class' : 'SimpleStrategy',
'replication_factor' : %d
}`, keyspace, *flagRF)).Consistency(All).Exec(); err != nil {
tb.Fatalf("error creating keyspace %s: %v", keyspace, err)
}
tb.Logf("Created keyspace %s", keyspace)
}
func createSessionFromCluster(cluster *ClusterConfig, tb testing.TB) *Session {
// Drop and re-create the keyspace once. Different tests should use their own
// individual tables, but can assume that the table does not exist before.
initOnce.Do(func() {
createKeyspace(tb, cluster, "gocql_test")
})
cluster.Keyspace = "gocql_test"
session, err := cluster.CreateSession()
if err != nil {
tb.Fatal("createSession:", err)
}
return session
}
func createSession(tb testing.TB) *Session {
cluster := createCluster()
return createSessionFromCluster(cluster, tb)
}
// 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]
cluster.DiscoverHosts = true
session, err := cluster.CreateSession()
if err != nil {
t.Fatalf("got error connecting to the cluster %v", err)
}
if *clusterSize > 1 {
// wait for autodiscovery to update the pool with the list of known hosts
time.Sleep(*flagAutoWait)
}
size := len(session.Pool.(*SimplePool).connPool)
if *clusterSize != size {
t.Logf("WARN: Expected a cluster size of %d, but actual size was %d", *clusterSize, size)
}
session.Close()
}
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")
}
}
//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.Error("expected ErrUseStmt, got " + err.Error())
}
} else {
t.Error("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.Errorf("Expected ErrNoConnections but got %v", err)
}
} else {
session.Close() //Clean up the session
t.Error("expected err, got nil.")
}
}
func TestTracing(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE 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.Error("insert:", err)
} else if buf.Len() == 0 {
t.Error("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.Error("select:", err)
} else if value != 42 {
t.Errorf("value: expected %d, got %d", 42, value)
} else if buf.Len() == 0 {
t.Error("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 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")
}
session := createSession(t)
defer session.Close()
session.cfg.SerialConsistency = LocalSerial
if err := createTable(session, `CREATE TABLE 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(); err.Error() != "count mismatch" {
t.Fatalf("delete: was expecting count mismatch error but got %s", err)
}
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")
}
}
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 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.Fatal("insert should have been applied")
}
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.Fatal("insert should not have been applied")
} 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 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 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 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 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 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 ErrQueryArgLength")
}
if err != ErrQueryArgLength {
t.Fatalf("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
}
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 ErrQueryArgLength")
}
if err != ErrQueryArgLength {
t.Fatalf("'INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength, but returned: %s", err)
}
}
// 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 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 ErrQueryArgLength")
}
if err != ErrQueryArgLength {
t.Fatalf("'`SELECT * FROM too_few_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength, but returned: %s", err)
}
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 ErrQueryArgLength")
}
if err != ErrQueryArgLength {
t.Fatalf("'INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
}
}
// 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.")
}
if err != ErrNoConnectionsStarted {
t.Fatalf("expected ErrNoConnectionsStarted, but received %v", err)
}
}
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 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 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 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 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 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 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 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)