forked from scylladb/scylla-rust-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.rs
1778 lines (1606 loc) · 66.8 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
//! `Session` is the main object used in the driver.\
//! It manages all connections to the cluster and allows to perform queries.
use crate::frame::types::LegacyConsistency;
use crate::history;
use crate::history::HistoryListener;
use async_trait::async_trait;
use bytes::Bytes;
use futures::future::join_all;
use futures::future::try_join_all;
use scylla_cql::frame::response::NonErrorResponse;
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::lookup_host;
use tokio::time::timeout;
use tracing::{debug, error, trace, trace_span, Instrument};
use uuid::Uuid;
use super::connection::NonErrorQueryResponse;
use super::connection::QueryResponse;
use super::errors::{BadQuery, NewSessionError, QueryError};
use super::topology::UntranslatedPeer;
use crate::cql_to_rust::FromRow;
use crate::frame::response::cql_to_rust::FromRowError;
use crate::frame::response::result;
use crate::frame::value::{
BatchValues, BatchValuesFirstSerialized, BatchValuesIterator, SerializedValues, ValueList,
};
use crate::prepared_statement::{PartitionKeyError, PreparedStatement};
use crate::query::Query;
use crate::routing::Token;
use crate::statement::{Consistency, SerialConsistency};
use crate::tracing::{GetTracingConfig, TracingEvent, TracingInfo};
use crate::transport::cluster::{Cluster, ClusterData, ClusterNeatDebug};
use crate::transport::connection::{Connection, ConnectionConfig, VerifiedKeyspaceName};
use crate::transport::connection_pool::PoolConfig;
use crate::transport::host_filter::HostFilter;
use crate::transport::iterator::{PreparedIteratorConfig, RowIterator};
use crate::transport::load_balancing::{
LoadBalancingPolicy, RoundRobinPolicy, Statement, TokenAwarePolicy,
};
use crate::transport::metrics::Metrics;
use crate::transport::node::Node;
use crate::transport::query_result::QueryResult;
use crate::transport::retry_policy::{
DefaultRetryPolicy, QueryInfo, RetryDecision, RetryPolicy, RetrySession,
};
use crate::transport::speculative_execution;
use crate::transport::speculative_execution::SpeculativeExecutionPolicy;
use crate::transport::Compression;
use crate::{
batch::{Batch, BatchStatement},
statement::StatementConfig,
};
pub use crate::transport::connection_pool::PoolSize;
#[cfg(feature = "ssl")]
use openssl::ssl::SslContext;
#[derive(Debug, Copy, Clone)]
pub enum TranslationError {
NoRuleForAddress,
InvalidAddressInRule,
}
#[async_trait]
pub trait AddressTranslator: Send + Sync {
async fn translate_address(
&self,
untranslated_peer: &UntranslatedPeer,
) -> Result<SocketAddr, TranslationError>;
}
#[async_trait]
impl AddressTranslator for HashMap<SocketAddr, SocketAddr> {
async fn translate_address(
&self,
untranslated_peer: &UntranslatedPeer,
) -> Result<SocketAddr, TranslationError> {
match self.get(&untranslated_peer.untranslated_address) {
Some(&translated_addr) => Ok(translated_addr),
None => Err(TranslationError::NoRuleForAddress),
}
}
}
#[async_trait]
// Notice: this is unefficient, but what else can we do with such poor representation as str?
// After all, the cluster size is small enough to make this irrelevant.
impl AddressTranslator for HashMap<&'static str, &'static str> {
async fn translate_address(
&self,
untranslated_peer: &UntranslatedPeer,
) -> Result<SocketAddr, TranslationError> {
for (&rule_addr_str, &translated_addr_str) in self.iter() {
if let Ok(rule_addr) = SocketAddr::from_str(rule_addr_str) {
if rule_addr == untranslated_peer.untranslated_address {
return SocketAddr::from_str(translated_addr_str)
.map_err(|_| TranslationError::InvalidAddressInRule);
}
}
}
Err(TranslationError::NoRuleForAddress)
}
}
/// `Session` manages connections to the cluster and allows to perform queries
pub struct Session {
cluster: Cluster,
load_balancer: Arc<dyn LoadBalancingPolicy>,
schema_agreement_interval: Duration,
retry_policy: Box<dyn RetryPolicy>,
speculative_execution_policy: Option<Arc<dyn SpeculativeExecutionPolicy>>,
metrics: Arc<Metrics>,
default_consistency: Consistency,
auto_await_schema_agreement_timeout: Option<Duration>,
request_timeout: Option<Duration>,
refresh_metadata_on_auto_schema_agreement: bool,
}
/// This implementation deliberately omits some details from Cluster in order
/// to avoid cluttering the print with much information of little usability.
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("cluster", &ClusterNeatDebug(&self.cluster))
.field("load_balancer", &self.load_balancer)
.field("schema_agreement_interval", &self.schema_agreement_interval)
.field("retry_policy", &self.retry_policy)
.field(
"speculative_execution_policy",
&self.speculative_execution_policy,
)
.field("metrics", &self.metrics)
.field("default_consistency", &self.default_consistency)
.field(
"auto_await_schema_agreement_timeout",
&self.auto_await_schema_agreement_timeout,
)
.finish()
}
}
/// Configuration options for [`Session`].
/// Can be created manually, but usually it's easier to use
/// [SessionBuilder](super::session_builder::SessionBuilder)
#[derive(Clone)]
pub struct SessionConfig {
/// List of database servers known on Session startup.
/// Session will connect to these nodes to retrieve information about other nodes in the cluster.
/// Each node can be represented as a hostname or an IP address.
pub known_nodes: Vec<KnownNode>,
/// Preferred compression algorithm to use on connections.
/// If it's not supported by database server Session will fall back to no compression.
pub compression: Option<Compression>,
pub tcp_nodelay: bool,
/// Load balancing policy used by Session
pub load_balancing: Arc<dyn LoadBalancingPolicy>,
pub used_keyspace: Option<String>,
pub keyspace_case_sensitive: bool,
pub retry_policy: Box<dyn RetryPolicy>,
pub speculative_execution_policy: Option<Arc<dyn SpeculativeExecutionPolicy>>,
/// Provide our Session with TLS
#[cfg(feature = "ssl")]
pub ssl_context: Option<SslContext>,
pub auth_username: Option<String>,
pub auth_password: Option<String>,
pub schema_agreement_interval: Duration,
pub connect_timeout: Duration,
/// Size of the per-node connection pool, i.e. how many connections the driver should keep to each node.
/// The default is `PerShard(1)`, which is the recommended setting for Scylla clusters.
pub connection_pool_size: PoolSize,
/// If true, prevents the driver from connecting to the shard-aware port, even if the node supports it.
/// Generally, this options is best left as default (false).
pub disallow_shard_aware_port: bool,
pub default_consistency: Consistency,
/// If true, full schema is fetched with every metadata refresh.
pub fetch_schema_metadata: bool,
/// Interval of sending keepalive requests
pub keepalive_interval: Option<Duration>,
/// Controls the timeout for the automatic wait for schema agreement after sending a schema-altering statement.
/// If `None`, the automatic schema agreement is disabled.
pub auto_await_schema_agreement_timeout: Option<Duration>,
/// Controls the client-side timeout for queries.
/// If `None`, the queries have no timeout (the driver will block indefinitely).
pub request_timeout: Option<Duration>,
pub address_translator: Option<Arc<dyn AddressTranslator>>,
/// The host filter decides whether any connections should be opened
/// to the node or not. The driver will also avoid filtered out nodes when
/// re-establishing the control connection.
pub host_filter: Option<Arc<dyn HostFilter>>,
/// If true, full schema metadata is fetched after successfully reaching a schema agreement.
/// It is true by default but can be disabled if successive schema-altering statements should be performed.
pub refresh_metadata_on_auto_schema_agreement: bool,
}
/// Describes database server known on Session startup.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum KnownNode {
Hostname(String),
Address(SocketAddr),
}
impl SessionConfig {
/// Creates a [`SessionConfig`] with default configuration
/// # Default configuration
/// * Compression: None
/// * Load balancing policy: Token-aware Round-robin
///
/// # Example
/// ```
/// # use scylla::SessionConfig;
/// let config = SessionConfig::new();
/// ```
pub fn new() -> Self {
SessionConfig {
known_nodes: Vec::new(),
compression: None,
tcp_nodelay: true,
schema_agreement_interval: Duration::from_millis(200),
load_balancing: Arc::new(TokenAwarePolicy::new(Box::new(RoundRobinPolicy::new()))),
used_keyspace: None,
keyspace_case_sensitive: false,
retry_policy: Box::new(DefaultRetryPolicy),
speculative_execution_policy: None,
#[cfg(feature = "ssl")]
ssl_context: None,
auth_username: None,
auth_password: None,
connect_timeout: Duration::from_secs(5),
connection_pool_size: Default::default(),
disallow_shard_aware_port: false,
default_consistency: Consistency::LocalQuorum,
fetch_schema_metadata: true,
keepalive_interval: None,
auto_await_schema_agreement_timeout: Some(std::time::Duration::from_secs(60)),
request_timeout: Some(Duration::from_secs(30)),
address_translator: None,
host_filter: None,
refresh_metadata_on_auto_schema_agreement: true,
}
}
/// Adds a known database server with a hostname.
/// If the port is not explicitly specified, 9042 is used as default
/// # Example
/// ```
/// # use scylla::SessionConfig;
/// let mut config = SessionConfig::new();
/// config.add_known_node("127.0.0.1");
/// config.add_known_node("db1.example.com:9042");
/// ```
pub fn add_known_node(&mut self, hostname: impl AsRef<str>) {
self.known_nodes
.push(KnownNode::Hostname(hostname.as_ref().to_string()));
}
/// Adds a known database server with an IP address
/// # Example
/// ```
/// # use scylla::SessionConfig;
/// # use std::net::{SocketAddr, IpAddr, Ipv4Addr};
/// let mut config = SessionConfig::new();
/// config.add_known_node_addr(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 9042));
/// ```
pub fn add_known_node_addr(&mut self, node_addr: SocketAddr) {
self.known_nodes.push(KnownNode::Address(node_addr));
}
/// Adds a list of known database server with hostnames.
/// If the port is not explicitly specified, 9042 is used as default
/// # Example
/// ```
/// # use scylla::SessionConfig;
/// # use std::net::{SocketAddr, IpAddr, Ipv4Addr};
/// let mut config = SessionConfig::new();
/// config.add_known_nodes(&["127.0.0.1:9042", "db1.example.com"]);
/// ```
pub fn add_known_nodes(&mut self, hostnames: &[impl AsRef<str>]) {
for hostname in hostnames {
self.add_known_node(hostname);
}
}
/// Adds a list of known database servers with IP addresses
/// # Example
/// ```
/// # use scylla::SessionConfig;
/// # use std::net::{SocketAddr, IpAddr, Ipv4Addr};
/// let addr1 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(172, 17, 0, 3)), 9042);
/// let addr2 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(172, 17, 0, 4)), 9042);
///
/// let mut config = SessionConfig::new();
/// config.add_known_nodes_addr(&[addr1, addr2]);
/// ```
pub fn add_known_nodes_addr(&mut self, node_addrs: &[SocketAddr]) {
for address in node_addrs {
self.add_known_node_addr(*address);
}
}
/// Creates a PoolConfig which can be used to create NodeConnectionPools
fn get_pool_config(&self) -> PoolConfig {
PoolConfig {
connection_config: self.get_connection_config(),
pool_size: self.connection_pool_size.clone(),
can_use_shard_aware_port: !self.disallow_shard_aware_port,
keepalive_interval: self.keepalive_interval,
}
}
/// Makes a config that should be used in Connection
fn get_connection_config(&self) -> ConnectionConfig {
ConnectionConfig {
compression: self.compression,
tcp_nodelay: self.tcp_nodelay,
#[cfg(feature = "ssl")]
ssl_context: self.ssl_context.clone(),
auth_username: self.auth_username.to_owned(),
auth_password: self.auth_password.to_owned(),
connect_timeout: self.connect_timeout,
event_sender: None,
default_consistency: self.default_consistency,
}
}
}
/// Creates default [`SessionConfig`], same as [`SessionConfig::new`]
impl Default for SessionConfig {
fn default() -> Self {
Self::new()
}
}
/// Trait used to implement `Vec<result::Row>::into_typed<RowT>`
// This is the only way to add custom method to Vec
pub trait IntoTypedRows {
fn into_typed<RowT: FromRow>(self) -> TypedRowIter<RowT>;
}
// Adds method Vec<result::Row>::into_typed<RowT>(self)
// It transforms the Vec into iterator mapping to custom row type
impl IntoTypedRows for Vec<result::Row> {
fn into_typed<RowT: FromRow>(self) -> TypedRowIter<RowT> {
TypedRowIter {
row_iter: self.into_iter(),
phantom_data: Default::default(),
}
}
}
/// Iterator over rows parsed as the given type\
/// Returned by `rows.into_typed::<(...)>()`
pub struct TypedRowIter<RowT: FromRow> {
row_iter: std::vec::IntoIter<result::Row>,
phantom_data: std::marker::PhantomData<RowT>,
}
impl<RowT: FromRow> Iterator for TypedRowIter<RowT> {
type Item = Result<RowT, FromRowError>;
fn next(&mut self) -> Option<Self::Item> {
self.row_iter.next().map(RowT::from_row)
}
}
pub enum RunQueryResult<ResT> {
IgnoredWriteError,
Completed(ResT),
}
/// Represents a CQL session, which can be used to communicate
/// with the database
impl Session {
// because it's more convenient
/// Estabilishes a CQL session with the database
///
/// Usually it's easier to use [SessionBuilder](crate::transport::session_builder::SessionBuilder)
/// instead of calling `Session::connect` directly
/// # Arguments
/// * `config` - Connection configuration - known nodes, Compression, etc.
/// Must contain at least one known node.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # async fn check_only_compiles() -> Result<(), Box<dyn Error>> {
/// use scylla::{Session, SessionConfig};
/// use scylla::transport::session::KnownNode;
///
/// let mut config = SessionConfig::new();
/// config.known_nodes.push(KnownNode::Hostname("127.0.0.1:9042".to_string()));
///
/// let session: Session = Session::connect(config).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect(config: SessionConfig) -> Result<Session, NewSessionError> {
// Ensure there is at least one known node
if config.known_nodes.is_empty() {
return Err(NewSessionError::EmptyKnownNodesList);
}
// Find IP addresses of all known nodes passed in the config
let mut node_addresses: Vec<SocketAddr> = Vec::with_capacity(config.known_nodes.len());
let mut to_resolve: Vec<&str> = Vec::new();
for node in &config.known_nodes {
match node {
KnownNode::Hostname(hostname) => to_resolve.push(hostname),
KnownNode::Address(address) => node_addresses.push(*address),
};
}
let resolve_futures = to_resolve.into_iter().map(resolve_hostname);
let resolved: Vec<SocketAddr> = futures::future::try_join_all(resolve_futures).await?;
node_addresses.extend(resolved);
let cluster = Cluster::new(
&node_addresses,
config.get_pool_config(),
config.fetch_schema_metadata,
&config.address_translator,
&config.host_filter,
)
.await?;
let session = Session {
cluster,
load_balancer: config.load_balancing,
retry_policy: config.retry_policy,
schema_agreement_interval: config.schema_agreement_interval,
speculative_execution_policy: config.speculative_execution_policy,
metrics: Arc::new(Metrics::new()),
default_consistency: config.default_consistency,
auto_await_schema_agreement_timeout: config.auto_await_schema_agreement_timeout,
request_timeout: config.request_timeout,
refresh_metadata_on_auto_schema_agreement: config
.refresh_metadata_on_auto_schema_agreement,
};
if let Some(keyspace_name) = config.used_keyspace {
session
.use_keyspace(keyspace_name, config.keyspace_case_sensitive)
.await?;
}
Ok(session)
}
/// Sends a query to the database and receives a response.\
/// Returns only a single page of results, to receive multiple pages use [query_iter](Session::query_iter)
///
/// This is the easiest way to make a query, but performance is worse than that of prepared queries.
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/simple.html) for more information
/// # Arguments
/// * `query` - query to perform, can be just a `&str` or the [Query](crate::query::Query) struct.
/// * `values` - values bound to the query, easiest way is to use a tuple of bound values
///
/// # Examples
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// // Insert an int and text into a table
/// session
/// .query(
/// "INSERT INTO ks.tab (a, b) VALUES(?, ?)",
/// (2_i32, "some text")
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::IntoTypedRows;
///
/// // Read rows containing an int and text
/// let rows_opt = session
/// .query("SELECT a, b FROM ks.tab", &[])
/// .await?
/// .rows;
///
/// if let Some(rows) = rows_opt {
/// for row in rows.into_typed::<(i32, String)>() {
/// // Parse row as int and text \
/// let (int_val, text_val): (i32, String) = row?;
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn query(
&self,
query: impl Into<Query>,
values: impl ValueList,
) -> Result<QueryResult, QueryError> {
self.query_paged(query, values, None).await
}
/// Queries the database with a custom paging state.
/// # Arguments
///
/// * `query` - query to be performed
/// * `values` - values bound to the query
/// * `paging_state` - previously received paging state or None
pub async fn query_paged(
&self,
query: impl Into<Query>,
values: impl ValueList,
paging_state: Option<Bytes>,
) -> Result<QueryResult, QueryError> {
let query: Query = query.into();
let serialized_values = values.serialized()?;
let span = trace_span!("Request", query = query.contents.as_str());
let run_query_result = self
.run_query(
Statement::default(),
&query.config,
|node: Arc<Node>| async move { node.random_connection().await },
|connection: Arc<Connection>, consistency: Consistency| {
// Needed to avoid moving query and values into async move block
let query_ref = &query;
let values_ref = &serialized_values;
let paging_state_ref = &paging_state;
async move {
connection
.query_with_consistency(
query_ref,
values_ref,
consistency,
paging_state_ref.clone(),
)
.await
.and_then(QueryResponse::into_non_error_query_response)
}
},
)
.instrument(span)
.await?;
let response = match run_query_result {
RunQueryResult::IgnoredWriteError => NonErrorQueryResponse {
response: NonErrorResponse::Result(result::Result::Void),
tracing_id: None,
warnings: Vec::new(),
},
RunQueryResult::Completed(response) => response,
};
self.handle_set_keyspace_response(&response).await?;
self.handle_auto_await_schema_agreement(&query.contents, &response)
.await?;
response.into_query_result()
}
async fn handle_set_keyspace_response(
&self,
response: &NonErrorQueryResponse,
) -> Result<(), QueryError> {
if let Some(set_keyspace) = response.as_set_keyspace() {
debug!(
"Detected USE KEYSPACE query, setting session's keyspace to {}",
set_keyspace.keyspace_name
);
self.use_keyspace(set_keyspace.keyspace_name.clone(), true)
.await?;
}
Ok(())
}
async fn handle_auto_await_schema_agreement(
&self,
contents: &str,
response: &NonErrorQueryResponse,
) -> Result<(), QueryError> {
if let Some(timeout) = self.auto_await_schema_agreement_timeout {
if response.as_schema_change().is_some()
&& !self.await_timed_schema_agreement(timeout).await?
{
// TODO: The TimeoutError should allow to provide more context.
// For now, print an error to the logs
error!(
"Failed to reach schema agreement after a schema-altering statement: {}",
contents,
);
return Err(QueryError::TimeoutError);
}
if self.refresh_metadata_on_auto_schema_agreement
&& response.as_schema_change().is_some()
{
self.refresh_metadata().await?;
}
}
Ok(())
}
/// Run a simple query with paging\
/// This method will query all pages of the result\
///
/// Returns an async iterator (stream) over all received rows\
/// Page size can be specified in the [Query](crate::query::Query) passed to the function
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/paged.html) for more information
///
/// # Arguments
/// * `query` - query to perform, can be just a `&str` or the [Query](crate::query::Query) struct.
/// * `values` - values bound to the query, easiest way is to use a tuple of bound values
///
/// # Example
///
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::IntoTypedRows;
/// use futures::stream::StreamExt;
///
/// let mut rows_stream = session
/// .query_iter("SELECT a, b FROM ks.t", &[])
/// .await?
/// .into_typed::<(i32, i32)>();
///
/// while let Some(next_row_res) = rows_stream.next().await {
/// let (a, b): (i32, i32) = next_row_res?;
/// println!("a, b: {}, {}", a, b);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn query_iter(
&self,
query: impl Into<Query>,
values: impl ValueList,
) -> Result<RowIterator, QueryError> {
let query: Query = query.into();
let serialized_values = values.serialized()?;
let retry_session = match &query.config.retry_policy {
Some(policy) => policy.new_session(),
None => self.retry_policy.new_session(),
};
let span = trace_span!("Request", query = query.contents.as_str());
RowIterator::new_for_query(
query,
serialized_values.into_owned(),
self.default_consistency,
retry_session,
self.load_balancer.clone(),
self.cluster.get_data(),
self.metrics.clone(),
)
.instrument(span)
.await
}
/// Prepares a statement on the server side and returns a prepared statement,
/// which can later be used to perform more efficient queries
///
/// Prepared queries are much faster than simple queries:
/// * Database doesn't need to parse the query
/// * They are properly load balanced using token aware routing
///
/// > ***Warning***\
/// > For token/shard aware load balancing to work properly, all partition key values
/// > must be sent as bound values
/// > (see [performance section](https://rust-driver.docs.scylladb.com/stable/queries/prepared.html#performance))
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/prepared.html) for more information
///
/// # Arguments
/// * `query` - query to prepare, can be just a `&str` or the [Query](crate::query::Query) struct.
///
/// # Example
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::prepared_statement::PreparedStatement;
///
/// // Prepare the query for later execution
/// let prepared: PreparedStatement = session
/// .prepare("INSERT INTO ks.tab (a) VALUES(?)")
/// .await?;
///
/// // Run the prepared query with some values, just like a simple query
/// let to_insert: i32 = 12345;
/// session.execute(&prepared, (to_insert,)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn prepare(&self, query: impl Into<Query>) -> Result<PreparedStatement, QueryError> {
let query = query.into();
let connections = self.cluster.get_working_connections().await?;
// Prepare statements on all connections concurrently
let handles = connections.iter().map(|c| c.prepare(&query));
let mut results = join_all(handles).await;
// If at least one prepare was successful prepare returns Ok
// Find first result that is Ok, or Err if all failed
let mut first_ok: Option<Result<PreparedStatement, QueryError>> = None;
while let Some(res) = results.pop() {
let is_ok: bool = res.is_ok();
first_ok = Some(res);
if is_ok {
break;
}
}
let mut prepared: PreparedStatement = first_ok.unwrap()?;
// Validate prepared ids equality
for statement in results.into_iter().flatten() {
if prepared.get_id() != statement.get_id() {
return Err(QueryError::ProtocolError(
"Prepared statement Ids differ, all should be equal",
));
}
// Collect all tracing ids from prepare() queries in the final result
prepared
.prepare_tracing_ids
.extend(statement.prepare_tracing_ids);
}
prepared.set_partitioner_name(
self.extract_partitioner_name(&prepared, &self.cluster.get_data()),
);
Ok(prepared)
}
fn extract_partitioner_name<'a>(
&self,
prepared: &PreparedStatement,
cluster_data: &'a ClusterData,
) -> Option<&'a str> {
cluster_data
.keyspaces
.get(prepared.get_keyspace_name()?)?
.tables
.get(prepared.get_table_name()?)?
.partitioner
.as_deref()
}
/// Execute a prepared query. Requires a [PreparedStatement](crate::prepared_statement::PreparedStatement)
/// generated using [`Session::prepare`](Session::prepare)\
/// Returns only a single page of results, to receive multiple pages use [execute_iter](Session::execute_iter)
///
/// Prepared queries are much faster than simple queries:
/// * Database doesn't need to parse the query
/// * They are properly load balanced using token aware routing
///
/// > ***Warning***\
/// > For token/shard aware load balancing to work properly, all partition key values
/// > must be sent as bound values
/// > (see [performance section](https://rust-driver.docs.scylladb.com/stable/queries/prepared.html#performance))
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/prepared.html) for more information
///
/// # Arguments
/// * `prepared` - the prepared statement to execute, generated using [`Session::prepare`](Session::prepare)
/// * `values` - values bound to the query, easiest way is to use a tuple of bound values
///
/// # Example
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::prepared_statement::PreparedStatement;
///
/// // Prepare the query for later execution
/// let prepared: PreparedStatement = session
/// .prepare("INSERT INTO ks.tab (a) VALUES(?)")
/// .await?;
///
/// // Run the prepared query with some values, just like a simple query
/// let to_insert: i32 = 12345;
/// session.execute(&prepared, (to_insert,)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn execute(
&self,
prepared: &PreparedStatement,
values: impl ValueList,
) -> Result<QueryResult, QueryError> {
self.execute_paged(prepared, values, None).await
}
/// Executes a previously prepared statement with previously received paging state
/// # Arguments
///
/// * `prepared` - a statement prepared with [prepare](crate::transport::session::Session::prepare)
/// * `values` - values bound to the query
/// * `paging_state` - paging state from the previous query or None
pub async fn execute_paged(
&self,
prepared: &PreparedStatement,
values: impl ValueList,
paging_state: Option<Bytes>,
) -> Result<QueryResult, QueryError> {
let serialized_values = values.serialized()?;
let values_ref = &serialized_values;
let paging_state_ref = &paging_state;
let token = self.calculate_token(prepared, &serialized_values)?;
let statement_info = Statement {
token,
keyspace: prepared.get_keyspace_name(),
};
let span = trace_span!(
"Request",
prepared_id = format!("{:X}", prepared.get_id()).as_str()
);
let run_query_result: RunQueryResult<NonErrorQueryResponse> = self
.run_query(
statement_info,
&prepared.config,
|node: Arc<Node>| async move {
match token {
Some(token) => node.connection_for_token(token).await,
None => node.random_connection().await,
}
},
|connection: Arc<Connection>, consistency: Consistency| async move {
connection
.execute_with_consistency(
prepared,
values_ref,
consistency,
paging_state_ref.clone(),
)
.await
.and_then(QueryResponse::into_non_error_query_response)
},
)
.instrument(span)
.await?;
let response = match run_query_result {
RunQueryResult::IgnoredWriteError => NonErrorQueryResponse {
response: NonErrorResponse::Result(result::Result::Void),
tracing_id: None,
warnings: Vec::new(),
},
RunQueryResult::Completed(response) => response,
};
self.handle_set_keyspace_response(&response).await?;
self.handle_auto_await_schema_agreement(prepared.get_statement(), &response)
.await?;
response.into_query_result()
}
/// Run a prepared query with paging\
/// This method will query all pages of the result\
///
/// Returns an async iterator (stream) over all received rows\
/// Page size can be specified in the [PreparedStatement](crate::prepared_statement::PreparedStatement)
/// passed to the function
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/paged.html) for more information
///
/// # Arguments
/// * `prepared` - the prepared statement to execute, generated using [`Session::prepare`](Session::prepare)
/// * `values` - values bound to the query, easiest way is to use a tuple of bound values
///
/// # Example
///
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::prepared_statement::PreparedStatement;
/// use scylla::IntoTypedRows;
/// use futures::stream::StreamExt;
///
/// // Prepare the query for later execution
/// let prepared: PreparedStatement = session
/// .prepare("SELECT a, b FROM ks.t")
/// .await?;
///
/// // Execute the query and receive all pages
/// let mut rows_stream = session
/// .execute_iter(prepared, &[])
/// .await?
/// .into_typed::<(i32, i32)>();
///
/// while let Some(next_row_res) = rows_stream.next().await {
/// let (a, b): (i32, i32) = next_row_res?;
/// println!("a, b: {}, {}", a, b);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn execute_iter(
&self,
prepared: impl Into<PreparedStatement>,
values: impl ValueList,
) -> Result<RowIterator, QueryError> {
let prepared = prepared.into();
let serialized_values = values.serialized()?;
let token = self.calculate_token(&prepared, &serialized_values)?;
let retry_session = match &prepared.config.retry_policy {
Some(policy) => policy.new_session(),
None => self.retry_policy.new_session(),
};
let span = trace_span!(
"Request",
prepared_id = format!("{:X}", prepared.get_id()).as_str()
);
RowIterator::new_for_prepared_statement(PreparedIteratorConfig {
prepared,
values: serialized_values.into_owned(),
default_consistency: self.default_consistency,
token,
retry_session,
load_balancer: self.load_balancer.clone(),
cluster_data: self.cluster.get_data(),
metrics: self.metrics.clone(),
})
.instrument(span)
.await
}
/// Perform a batch query\
/// Batch contains many `simple` or `prepared` queries which are executed at once\
/// Batch doesn't return any rows
///
/// Batch values must contain values for each of the queries
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/batch.html) for more information
///
/// # Arguments
/// * `batch` - [Batch](crate::batch::Batch) to be performed
/// * `values` - List of values for each query, it's the easiest to use a tuple of tuples
///
/// # Example
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::batch::Batch;
///
/// let mut batch: Batch = Default::default();
///
/// // A query with two bound values
/// batch.append_statement("INSERT INTO ks.tab(a, b) VALUES(?, ?)");
///
/// // A query with one bound value
/// batch.append_statement("INSERT INTO ks.tab(a, b) VALUES(3, ?)");
///