-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathsession.rs
3084 lines (2614 loc) · 98.5 KB
/
session.rs
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
use crate::utils::DeserializeOwnedValue;
use crate::utils::{
create_new_session_builder, scylla_supports_tablets, setup_tracing, supports_feature,
unique_keyspace_name, PerformDDL,
};
use assert_matches::assert_matches;
use futures::{FutureExt, StreamExt as _, TryStreamExt};
use itertools::Itertools;
use scylla::batch::{Batch, BatchStatement, BatchType};
use scylla::client::caching_session::CachingSession;
use scylla::client::execution_profile::ExecutionProfile;
use scylla::client::session::Session;
use scylla::client::session_builder::SessionBuilder;
use scylla::cluster::metadata::Strategy::NetworkTopologyStrategy;
use scylla::cluster::metadata::{
CollectionType, ColumnKind, ColumnType, NativeType, UserDefinedType,
};
use scylla::errors::{
BadKeyspaceName, DbError, ExecutionError, RequestAttemptError, UseKeyspaceError,
};
use scylla::observability::tracing::TracingInfo;
use scylla::policies::retry::{RequestInfo, RetryDecision, RetryPolicy, RetrySession};
use scylla::prepared_statement::PreparedStatement;
use scylla::query::Query;
use scylla::routing::partitioner::{calculate_token_for_partition_key, PartitionerName};
use scylla::statement::Consistency;
use scylla_cql::frame::request::query::{PagingState, PagingStateResponse};
use scylla_cql::serialize::row::{SerializeRow, SerializedValues};
use scylla_cql::serialize::value::SerializeValue;
use scylla_cql::value::{CqlVarint, Row};
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeSet, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use tokio::net::TcpListener;
use uuid::Uuid;
use scylla::response::query_result::{QueryResult, QueryRowsResult};
#[tokio::test]
async fn test_connection_failure() {
setup_tracing();
// Make sure that Session::create fails when the control connection
// fails to connect.
// Create a dummy server which immediately closes the connection.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (fut, _handle) = async move {
loop {
let _ = listener.accept().await;
}
}
.remote_handle();
tokio::spawn(fut);
let res = SessionBuilder::new().known_node_addr(addr).build().await;
match res {
Ok(_) => panic!("Unexpected success"),
Err(err) => println!("Connection error (it was expected): {:?}", err),
}
}
#[tokio::test]
async fn test_unprepared_statement() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.t (a int, b int, c text, primary key (a, b))",
ks
))
.await
.unwrap();
session
.query_unpaged(
format!("INSERT INTO {}.t (a, b, c) VALUES (1, 2, 'abc')", ks),
&[],
)
.await
.unwrap();
session
.query_unpaged(
format!("INSERT INTO {}.t (a, b, c) VALUES (7, 11, '')", ks),
&[],
)
.await
.unwrap();
session
.query_unpaged(
format!("INSERT INTO {}.t (a, b, c) VALUES (1, 4, 'hello')", ks),
&[],
)
.await
.unwrap();
let query_result = session
.query_unpaged(format!("SELECT a, b, c FROM {}.t", ks), &[])
.await
.unwrap();
let rows = query_result.into_rows_result().unwrap();
let col_specs = rows.column_specs();
assert_eq!(col_specs.get_by_name("a").unwrap().0, 0);
assert_eq!(col_specs.get_by_name("b").unwrap().0, 1);
assert_eq!(col_specs.get_by_name("c").unwrap().0, 2);
assert!(col_specs.get_by_name("d").is_none());
let mut results = rows
.rows::<(i32, i32, String)>()
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
results.sort();
assert_eq!(
results,
vec![
(1, 2, String::from("abc")),
(1, 4, String::from("hello")),
(7, 11, String::from(""))
]
);
let query_result = session
.query_iter(format!("SELECT a, b, c FROM {}.t", ks), &[])
.await
.unwrap();
let specs = query_result.column_specs();
assert_eq!(specs.len(), 3);
for (spec, name) in specs.iter().zip(["a", "b", "c"]) {
assert_eq!(spec.name(), name); // Check column name.
assert_eq!(spec.table_spec().ks_name(), ks);
}
let mut results_from_manual_paging = vec![];
let query = Query::new(format!("SELECT a, b, c FROM {}.t", ks)).with_page_size(1);
let mut paging_state = PagingState::start();
let mut watchdog = 0;
loop {
let (rs_manual, paging_state_response) = session
.query_single_page(query.clone(), &[], paging_state)
.await
.unwrap();
let mut page_results = rs_manual
.into_rows_result()
.unwrap()
.rows::<(i32, i32, String)>()
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
results_from_manual_paging.append(&mut page_results);
match paging_state_response {
PagingStateResponse::HasMorePages { state } => {
paging_state = state;
}
_ if watchdog > 30 => break,
PagingStateResponse::NoMorePages => break,
}
watchdog += 1;
}
assert_eq!(results_from_manual_paging, results);
}
#[tokio::test]
async fn test_counter_batch() {
use scylla::value::Counter;
use scylla_cql::frame::request::batch::BatchType;
setup_tracing();
let session = Arc::new(create_new_session_builder().build().await.unwrap());
let ks = unique_keyspace_name();
// Need to disable tablets in this test because they don't support counters yet.
// (https://github.com/scylladb/scylladb/commit/c70f321c6f581357afdf3fd8b4fe8e5c5bb9736e).
let mut create_ks = format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks);
if scylla_supports_tablets(&session).await {
create_ks += " AND TABLETS = {'enabled': false}"
}
session.ddl(create_ks).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.t_batch (key int PRIMARY KEY, value counter)",
ks
))
.await
.unwrap();
let statement_str = format!("UPDATE {}.t_batch SET value = value + ? WHERE key = ?", ks);
let query = Query::from(statement_str);
let prepared = session.prepare(query.clone()).await.unwrap();
let mut counter_batch = Batch::new(BatchType::Counter);
counter_batch.append_statement(query.clone());
counter_batch.append_statement(prepared.clone());
counter_batch.append_statement(query.clone());
counter_batch.append_statement(prepared.clone());
counter_batch.append_statement(query.clone());
counter_batch.append_statement(prepared.clone());
// Check that we do not get a server error - the driver
// should send a COUNTER batch instead of a LOGGED (default) one.
session
.batch(
&counter_batch,
(
(Counter(1), 1),
(Counter(2), 2),
(Counter(3), 3),
(Counter(4), 4),
(Counter(5), 5),
(Counter(6), 6),
),
)
.await
.unwrap();
}
#[tokio::test]
async fn test_batch() {
setup_tracing();
let session = Arc::new(create_new_session_builder().build().await.unwrap());
let ks = unique_keyspace_name();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.t_batch (a int, b int, c text, primary key (a, b))",
ks
))
.await
.unwrap();
let prepared_statement = session
.prepare(format!(
"INSERT INTO {}.t_batch (a, b, c) VALUES (?, ?, ?)",
ks
))
.await
.unwrap();
// TODO: Add API that supports binding values to statements in batch creation process,
// to avoid problem of statements/values count mismatch
use scylla::batch::Batch;
let mut batch: Batch = Default::default();
batch.append_statement(&format!("INSERT INTO {}.t_batch (a, b, c) VALUES (?, ?, ?)", ks)[..]);
batch.append_statement(&format!("INSERT INTO {}.t_batch (a, b, c) VALUES (7, 11, '')", ks)[..]);
batch.append_statement(prepared_statement.clone());
let four_value: i32 = 4;
let hello_value: String = String::from("hello");
let session_clone = session.clone();
// We're spawning to a separate task here to test that it works even in that case, because in some scenarios
// (specifically if the `BatchValuesIter` associated type is not dropped before await boundaries)
// the implicit auto trait propagation on batch will be such that the returned future is not Send (depending on
// some lifetime for some unknown reason), so can't be spawned on tokio.
// See https://github.com/scylladb/scylla-rust-driver/issues/599 for more details
tokio::spawn(async move {
let values = (
(1_i32, 2_i32, "abc"),
(),
(1_i32, &four_value, hello_value.as_str()),
);
session_clone.batch(&batch, values).await.unwrap();
})
.await
.unwrap();
let mut results: Vec<(i32, i32, String)> = session
.query_unpaged(format!("SELECT a, b, c FROM {}.t_batch", ks), &[])
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(i32, i32, String)>()
.unwrap()
.collect::<Result<_, _>>()
.unwrap();
results.sort();
assert_eq!(
results,
vec![
(1, 2, String::from("abc")),
(1, 4, String::from("hello")),
(7, 11, String::from(""))
]
);
// Test repreparing statement inside a batch
let mut batch: Batch = Default::default();
batch.append_statement(prepared_statement);
let values = ((4_i32, 20_i32, "foobar"),);
// This statement flushes the prepared statement cache
session
.ddl(format!(
"ALTER TABLE {}.t_batch WITH gc_grace_seconds = 42",
ks
))
.await
.unwrap();
session.batch(&batch, values).await.unwrap();
let results: Vec<(i32, i32, String)> = session
.query_unpaged(
format!("SELECT a, b, c FROM {}.t_batch WHERE a = 4", ks),
&[],
)
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(i32, i32, String)>()
.unwrap()
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(results, vec![(4, 20, String::from("foobar"))]);
}
// This is a regression test for #1134.
#[tokio::test]
async fn test_batch_to_multiple_tables() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
session.use_keyspace(&ks, true).await.unwrap();
session
.ddl("CREATE TABLE IF NOT EXISTS t_batch1 (a int, b int, c text, primary key (a, b))")
.await
.unwrap();
session
.ddl("CREATE TABLE IF NOT EXISTS t_batch2 (a int, b int, c text, primary key (a, b))")
.await
.unwrap();
let prepared_statement = session
.prepare(
"
BEGIN BATCH
INSERT INTO t_batch1 (a, b, c) VALUES (?, ?, ?);
INSERT INTO t_batch2 (a, b, c) VALUES (?, ?, ?);
APPLY BATCH;
",
)
.await
.unwrap();
session
.execute_unpaged(&prepared_statement, (1, 2, "ala", 4, 5, "ma"))
.await
.unwrap();
}
#[tokio::test]
async fn test_token_awareness() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
// Need to disable tablets in this test because they make token routing
// work differently, and in this test we want to test the classic token ring
// behavior.
let mut create_ks = format!(
"CREATE KEYSPACE IF NOT EXISTS {ks} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}"
);
if scylla_supports_tablets(&session).await {
create_ks += " AND TABLETS = {'enabled': false}"
}
session.ddl(create_ks).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.t (a text primary key)",
ks
))
.await
.unwrap();
let mut prepared_statement = session
.prepare(format!("INSERT INTO {}.t (a) VALUES (?)", ks))
.await
.unwrap();
prepared_statement.set_tracing(true);
// The default policy should be token aware
for size in 1..50usize {
let key = vec!['a'; size].into_iter().collect::<String>();
let values = (&key,);
// Execute a query and observe tracing info
let res = session
.execute_unpaged(&prepared_statement, values)
.await
.unwrap();
let tracing_info = session
.get_tracing_info(res.tracing_id().as_ref().unwrap())
.await
.unwrap();
// Verify that only one node was involved
assert_eq!(tracing_info.nodes().len(), 1);
// Do the same with execute_iter (it now works with writes)
let iter = session
.execute_iter(prepared_statement.clone(), values)
.await
.unwrap();
let tracing_id = iter.tracing_ids()[0];
let tracing_info = session.get_tracing_info(&tracing_id).await.unwrap();
// Again, verify that only one node was involved
assert_eq!(tracing_info.nodes().len(), 1);
}
}
#[tokio::test]
async fn test_use_keyspace() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.tab (a text primary key)",
ks
))
.await
.unwrap();
session
.query_unpaged(format!("INSERT INTO {}.tab (a) VALUES ('test1')", ks), &[])
.await
.unwrap();
session.use_keyspace(ks.clone(), false).await.unwrap();
session
.query_unpaged("INSERT INTO tab (a) VALUES ('test2')", &[])
.await
.unwrap();
let mut rows: Vec<String> = session
.query_unpaged("SELECT * FROM tab", &[])
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(String,)>()
.unwrap()
.map(|res| res.unwrap().0)
.collect();
rows.sort();
assert_eq!(rows, vec!["test1".to_string(), "test2".to_string()]);
// Test that trying to use nonexisting keyspace fails
assert!(session
.use_keyspace("this_keyspace_does_not_exist_at_all", false)
.await
.is_err());
// Test that invalid keyspaces get rejected
assert!(matches!(
session.use_keyspace("", false).await,
Err(UseKeyspaceError::BadKeyspaceName(BadKeyspaceName::Empty))
));
let long_name: String = ['a'; 49].iter().collect();
assert!(matches!(
session.use_keyspace(long_name, false).await,
Err(UseKeyspaceError::BadKeyspaceName(BadKeyspaceName::TooLong(
_,
_
)))
));
assert!(matches!(
session.use_keyspace("abcd;dfdsf", false).await,
Err(UseKeyspaceError::BadKeyspaceName(
BadKeyspaceName::IllegalCharacter(_, ';')
))
));
// Make sure that use_keyspace on SessionBuiler works
let session2: Session = create_new_session_builder()
.use_keyspace(ks.clone(), false)
.build()
.await
.unwrap();
let mut rows2: Vec<String> = session2
.query_unpaged("SELECT * FROM tab", &[])
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(String,)>()
.unwrap()
.map(|res| res.unwrap().0)
.collect();
rows2.sort();
assert_eq!(rows2, vec!["test1".to_string(), "test2".to_string()]);
}
#[tokio::test]
async fn test_use_keyspace_case_sensitivity() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks_lower = unique_keyspace_name().to_lowercase();
let ks_upper = ks_lower.to_uppercase();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS \"{}\" WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks_lower)).await.unwrap();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS \"{}\" WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks_upper)).await.unwrap();
session
.ddl(format!(
"CREATE TABLE {}.tab (a text primary key)",
ks_lower
))
.await
.unwrap();
session
.ddl(format!(
"CREATE TABLE \"{}\".tab (a text primary key)",
ks_upper
))
.await
.unwrap();
session
.query_unpaged(
format!("INSERT INTO {}.tab (a) VALUES ('lowercase')", ks_lower),
&[],
)
.await
.unwrap();
session
.query_unpaged(
format!("INSERT INTO \"{}\".tab (a) VALUES ('uppercase')", ks_upper),
&[],
)
.await
.unwrap();
// Use uppercase keyspace without case sensitivity
// Should select the lowercase one
session.use_keyspace(ks_upper.clone(), false).await.unwrap();
let rows: Vec<String> = session
.query_unpaged("SELECT * from tab", &[])
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(String,)>()
.unwrap()
.map(|row| row.unwrap().0)
.collect();
assert_eq!(rows, vec!["lowercase".to_string()]);
// Use uppercase keyspace with case sensitivity
// Should select the uppercase one
session.use_keyspace(ks_upper, true).await.unwrap();
let rows: Vec<String> = session
.query_unpaged("SELECT * from tab", &[])
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(String,)>()
.unwrap()
.map(|row| row.unwrap().0)
.collect();
assert_eq!(rows, vec!["uppercase".to_string()]);
}
#[tokio::test]
async fn test_raw_use_keyspace() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.tab (a text primary key)",
ks
))
.await
.unwrap();
session
.query_unpaged(
format!("INSERT INTO {}.tab (a) VALUES ('raw_test')", ks),
&[],
)
.await
.unwrap();
session
.query_unpaged(format!("use \"{}\" ;", ks), &[])
.await
.unwrap();
let rows: Vec<String> = session
.query_unpaged("SELECT * FROM tab", &[])
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows::<(String,)>()
.unwrap()
.map(|res| res.unwrap().0)
.collect();
assert_eq!(rows, vec!["raw_test".to_string()]);
// Check if case sensitivity is correctly detected
assert!(session
.query_unpaged(format!("use \"{}\" ;", ks.to_uppercase()), &[])
.await
.is_err());
assert!(session
.query_unpaged(format!("use {} ;", ks.to_uppercase()), &[])
.await
.is_ok());
}
#[tokio::test]
async fn test_fetch_system_keyspace() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let prepared_statement = session
.prepare("SELECT * FROM system_schema.keyspaces")
.await
.unwrap();
session
.execute_unpaged(&prepared_statement, &[])
.await
.unwrap();
}
// Test that some Database Errors are parsed correctly
#[tokio::test]
async fn test_db_errors() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
// SyntaxError on bad query
assert!(matches!(
session.query_unpaged("gibberish", &[]).await,
Err(ExecutionError::LastAttemptError(
RequestAttemptError::DbError(DbError::SyntaxError, _)
))
));
// AlreadyExists when creating a keyspace for the second time
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
let create_keyspace_res = session.ddl(format!("CREATE KEYSPACE {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await;
let keyspace_exists_error: DbError = match create_keyspace_res {
Err(ExecutionError::LastAttemptError(RequestAttemptError::DbError(e, _))) => e,
_ => panic!("Second CREATE KEYSPACE didn't return an error!"),
};
assert_eq!(
keyspace_exists_error,
DbError::AlreadyExists {
keyspace: ks.clone(),
table: "".to_string()
}
);
// AlreadyExists when creating a table for the second time
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.tab (a text primary key)",
ks
))
.await
.unwrap();
let create_table_res = session
.ddl(format!("CREATE TABLE {}.tab (a text primary key)", ks))
.await;
let create_tab_error: DbError = match create_table_res {
Err(ExecutionError::LastAttemptError(RequestAttemptError::DbError(e, _))) => e,
_ => panic!("Second CREATE TABLE didn't return an error!"),
};
assert_eq!(
create_tab_error,
DbError::AlreadyExists {
keyspace: ks.clone(),
table: "tab".to_string()
}
);
}
#[tokio::test]
async fn test_tracing() {
setup_tracing();
let session = create_new_session_builder().build().await.unwrap();
let ks = unique_keyspace_name();
session.ddl(format!("CREATE KEYSPACE IF NOT EXISTS {} WITH REPLICATION = {{'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}}", ks)).await.unwrap();
session
.ddl(format!(
"CREATE TABLE IF NOT EXISTS {}.tab (a text primary key)",
ks
))
.await
.unwrap();
test_tracing_query(&session, ks.clone()).await;
test_tracing_execute(&session, ks.clone()).await;
test_tracing_prepare(&session, ks.clone()).await;
test_get_tracing_info(&session, ks.clone()).await;
test_tracing_query_iter(&session, ks.clone()).await;
test_tracing_execute_iter(&session, ks.clone()).await;
test_tracing_batch(&session, ks.clone()).await;
}
async fn test_tracing_query(session: &Session, ks: String) {
// A query without tracing enabled has no tracing uuid in result
let untraced_query: Query = Query::new(format!("SELECT * FROM {}.tab", ks));
let untraced_query_result: QueryResult =
session.query_unpaged(untraced_query, &[]).await.unwrap();
assert!(untraced_query_result.tracing_id().is_none());
// A query with tracing enabled has a tracing uuid in result
let mut traced_query: Query = Query::new(format!("SELECT * FROM {}.tab", ks));
traced_query.set_tracing(true);
let traced_query_result: QueryResult = session.query_unpaged(traced_query, &[]).await.unwrap();
assert!(traced_query_result.tracing_id().is_some());
// Querying this uuid from tracing table gives some results
assert_in_tracing_table(session, traced_query_result.tracing_id().unwrap()).await;
}
async fn test_tracing_execute(session: &Session, ks: String) {
// Executing a prepared statement without tracing enabled has no tracing uuid in result
let untraced_prepared = session
.prepare(format!("SELECT * FROM {}.tab", ks))
.await
.unwrap();
let untraced_prepared_result: QueryResult = session
.execute_unpaged(&untraced_prepared, &[])
.await
.unwrap();
assert!(untraced_prepared_result.tracing_id().is_none());
// Executing a prepared statement with tracing enabled has a tracing uuid in result
let mut traced_prepared = session
.prepare(format!("SELECT * FROM {}.tab", ks))
.await
.unwrap();
traced_prepared.set_tracing(true);
let traced_prepared_result: QueryResult = session
.execute_unpaged(&traced_prepared, &[])
.await
.unwrap();
assert!(traced_prepared_result.tracing_id().is_some());
// Querying this uuid from tracing table gives some results
assert_in_tracing_table(session, traced_prepared_result.tracing_id().unwrap()).await;
}
async fn test_tracing_prepare(session: &Session, ks: String) {
// Preparing a statement without tracing enabled has no tracing uuids in result
let untraced_prepared = session
.prepare(format!("SELECT * FROM {}.tab", ks))
.await
.unwrap();
assert!(untraced_prepared.prepare_tracing_ids.is_empty());
// Preparing a statement with tracing enabled has tracing uuids in result
let mut to_prepare_traced = Query::new(format!("SELECT * FROM {}.tab", ks));
to_prepare_traced.set_tracing(true);
let traced_prepared = session.prepare(to_prepare_traced).await.unwrap();
assert!(!traced_prepared.prepare_tracing_ids.is_empty());
// Querying this uuid from tracing table gives some results
for tracing_id in traced_prepared.prepare_tracing_ids {
assert_in_tracing_table(session, tracing_id).await;
}
}
async fn test_get_tracing_info(session: &Session, ks: String) {
// A query with tracing enabled has a tracing uuid in result
let mut traced_query: Query = Query::new(format!("SELECT * FROM {}.tab", ks));
traced_query.set_tracing(true);
let traced_query_result: QueryResult = session.query_unpaged(traced_query, &[]).await.unwrap();
let tracing_id: Uuid = traced_query_result.tracing_id().unwrap();
// Getting tracing info from session using this uuid works
let tracing_info: TracingInfo = session.get_tracing_info(&tracing_id).await.unwrap();
assert!(!tracing_info.events.is_empty());
assert!(!tracing_info.nodes().is_empty());
// Check if the request type matches
assert_eq!(tracing_info.request.as_ref().unwrap(), "Execute CQL3 query");
// Check if we're using Scylla or Cassandra
let is_scylla = session
.get_cluster_state()
.get_nodes_info()
.first()
.unwrap()
.sharder()
.is_some();
if is_scylla {
// For Scylla, duration should be available immediately
assert!(tracing_info.duration.unwrap() > 0);
} else {
// For Cassandra, we might need to wait for the duration
let mut attempts = 0;
let max_attempts = 10;
let mut duration_opt;
while attempts < max_attempts {
duration_opt = session
.get_tracing_info(&tracing_id)
.await
.unwrap()
.duration;
if let Some(duration) = duration_opt {
assert!(duration > 0);
break;
}
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
attempts += 1;
}
if attempts == max_attempts {
panic!("Duration was not available after {} attempts", max_attempts);
}
}
// Verify started_at timestamp is present
assert!(tracing_info.started_at.unwrap().0 > 0);
// Check parameters
assert!(tracing_info
.parameters
.as_ref()
.unwrap()
.contains_key("consistency_level"));
assert!(tracing_info
.parameters
.as_ref()
.unwrap()
.contains_key("query"));
// Check events
for event in &tracing_info.events {
assert!(!event.activity.as_ref().unwrap().is_empty());
assert!(event.source.is_some());
assert!(event.source_elapsed.unwrap() >= 0);
assert!(!event.activity.as_ref().unwrap().is_empty());
}
}
async fn test_tracing_query_iter(session: &Session, ks: String) {
// A query without tracing enabled has no tracing ids
let untraced_query: Query = Query::new(format!("SELECT * FROM {}.tab", ks));
let untraced_query_pager = session.query_iter(untraced_query, &[]).await.unwrap();
assert!(untraced_query_pager.tracing_ids().is_empty());
let untraced_typed_row_iter = untraced_query_pager.rows_stream::<(String,)>().unwrap();
assert!(untraced_typed_row_iter.tracing_ids().is_empty());
// A query with tracing enabled has a tracing ids in result
let mut traced_query: Query = Query::new(format!("SELECT * FROM {}.tab", ks));
traced_query.set_tracing(true);
let traced_query_pager = session.query_iter(traced_query, &[]).await.unwrap();
let traced_typed_row_stream = traced_query_pager.rows_stream::<(String,)>().unwrap();
assert!(!traced_typed_row_stream.tracing_ids().is_empty());
for tracing_id in traced_typed_row_stream.tracing_ids() {
assert_in_tracing_table(session, *tracing_id).await;
}
}
async fn test_tracing_execute_iter(session: &Session, ks: String) {
// A prepared statement without tracing enabled has no tracing ids
let untraced_prepared = session
.prepare(format!("SELECT * FROM {}.tab", ks))
.await
.unwrap();
let untraced_query_pager = session.execute_iter(untraced_prepared, &[]).await.unwrap();
assert!(untraced_query_pager.tracing_ids().is_empty());
let untraced_typed_row_stream = untraced_query_pager.rows_stream::<(String,)>().unwrap();
assert!(untraced_typed_row_stream.tracing_ids().is_empty());
// A prepared statement with tracing enabled has a tracing ids in result
let mut traced_prepared = session
.prepare(format!("SELECT * FROM {}.tab", ks))
.await
.unwrap();
traced_prepared.set_tracing(true);
let traced_query_pager = session.execute_iter(traced_prepared, &[]).await.unwrap();
let traced_typed_row_stream = traced_query_pager.rows_stream::<(String,)>().unwrap();
assert!(!traced_typed_row_stream.tracing_ids().is_empty());
for tracing_id in traced_typed_row_stream.tracing_ids() {
assert_in_tracing_table(session, *tracing_id).await;
}
}
async fn test_tracing_batch(session: &Session, ks: String) {
// A batch without tracing enabled has no tracing id
let mut untraced_batch: Batch = Default::default();
untraced_batch.append_statement(&format!("INSERT INTO {}.tab (a) VALUES('a')", ks)[..]);
let untraced_batch_result: QueryResult = session.batch(&untraced_batch, ((),)).await.unwrap();
assert!(untraced_batch_result.tracing_id().is_none());
// Batch with tracing enabled has a tracing uuid in result
let mut traced_batch: Batch = Default::default();
traced_batch.append_statement(&format!("INSERT INTO {}.tab (a) VALUES('a')", ks)[..]);
traced_batch.set_tracing(true);
let traced_batch_result: QueryResult = session.batch(&traced_batch, ((),)).await.unwrap();
assert!(traced_batch_result.tracing_id().is_some());
assert_in_tracing_table(session, traced_batch_result.tracing_id().unwrap()).await;
}
async fn assert_in_tracing_table(session: &Session, tracing_uuid: Uuid) {
let mut traces_query = Query::new("SELECT * FROM system_traces.sessions WHERE session_id = ?");
traces_query.set_consistency(Consistency::One);
// Tracing info might not be immediately available
// If rows are empty perform 8 retries with a 32ms wait in between
// The reason why we enable so long waiting for TracingInfo is... Cassandra. (Yes, again.)
// In Cassandra Java Driver, the wait time for tracing info is 10 seconds, so here we do the same.
// However, as Scylla usually gets TracingInfo ready really fast (our default interval is hence 3ms),
// we stick to a not-so-much-terribly-long interval here.
for _ in 0..200 {
let rows_num = session
.query_unpaged(traces_query.clone(), (tracing_uuid,))
.await
.unwrap()
.into_rows_result()
.unwrap()
.rows_num();
if rows_num > 0 {
// Ok there was some row for this tracing_uuid
return;
}
// Otherwise retry
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
// If all retries failed panic with an error