-
Notifications
You must be signed in to change notification settings - Fork 112
/
session.rs
2489 lines (2267 loc) · 96.1 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::batch::batch_values;
#[cfg(feature = "cloud")]
use crate::cloud::CloudConfig;
#[allow(deprecated)]
use crate::LegacyQueryResult;
use crate::history;
use crate::history::HistoryListener;
pub use crate::transport::errors::TranslationError;
use crate::transport::errors::{
BadQuery, NewSessionError, ProtocolError, QueryError, UserRequestError,
};
use crate::utils::pretty::{CommaSeparatedDisplayer, CqlValueDisplayer};
use arc_swap::ArcSwapOption;
use async_trait::async_trait;
use futures::future::join_all;
use futures::future::try_join_all;
use itertools::{Either, Itertools};
use scylla_cql::frame::response::result::RawMetadataAndRawRows;
use scylla_cql::frame::response::result::{deser_cql_value, ColumnSpec};
use scylla_cql::frame::response::NonErrorResponse;
use scylla_cql::types::serialize::batch::BatchValues;
use scylla_cql::types::serialize::row::{SerializeRow, SerializedValues};
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt::Display;
use std::future::Future;
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::str::FromStr;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::timeout;
use tracing::{debug, error, trace, trace_span, Instrument};
use uuid::Uuid;
use super::connection::NonErrorQueryResponse;
use super::connection::QueryResponse;
#[cfg(feature = "ssl")]
use super::connection::SslConfig;
use super::errors::TracingProtocolError;
use super::execution_profile::{ExecutionProfile, ExecutionProfileHandle, ExecutionProfileInner};
use super::iterator::QueryPager;
#[cfg(feature = "cloud")]
use super::node::CloudEndpoint;
use super::node::{InternalKnownNode, KnownNode};
use super::partitioner::PartitionerName;
use super::query_result::MaybeFirstRowError;
use super::query_result::RowsError;
use super::topology::UntranslatedPeer;
use super::{NodeRef, SelfIdentity};
use crate::frame::response::result;
use crate::prepared_statement::PreparedStatement;
use crate::query::Query;
use crate::routing::{Shard, Token};
use crate::statement::{Consistency, PageSize, PagingState, PagingStateResponse};
use crate::tracing::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;
#[allow(deprecated)]
use crate::transport::iterator::{LegacyRowIterator, PreparedIteratorConfig};
use crate::transport::load_balancing::{self, RoutingInfo};
use crate::transport::metrics::Metrics;
use crate::transport::node::Node;
use crate::transport::query_result::QueryResult;
use crate::transport::retry_policy::{QueryInfo, RetryDecision, RetrySession};
use crate::transport::speculative_execution;
use crate::transport::Compression;
use crate::{
batch::{Batch, BatchStatement},
statement::StatementConfig,
};
pub use crate::transport::connection_pool::PoolSize;
// This re-export is to preserve backward compatibility.
// Those items are no longer here not to clutter session.rs with legacy things.
#[allow(deprecated)]
pub use crate::transport::legacy_query_result::{IntoTypedRows, TypedRowIter};
use crate::authentication::AuthenticatorProvider;
#[cfg(feature = "ssl")]
use openssl::ssl::SslContext;
mod sealed {
// This is a sealed trait - its whole purpose is to be unnameable.
// This means we need to disable the check.
#[allow(unknown_lints)] // Rust 1.70 (our MSRV) doesn't know this lint
#[allow(unnameable_types)]
pub trait Sealed {}
}
pub(crate) const TABLET_CHANNEL_SIZE: usize = 8192;
const TRACING_QUERY_PAGE_SIZE: i32 = 1024;
/// Translates IP addresses received from ScyllaDB nodes into locally reachable addresses.
///
/// The driver auto-detects new ScyllaDB nodes added to the cluster through server side pushed
/// notifications and through checking the system tables. For each node, the address the driver
/// receives corresponds to the address set as `rpc_address` in the node yaml file. In most
/// cases, this is the correct address to use by the driver and that is what is used by default.
/// However, sometimes the addresses received through this mechanism will either not be reachable
/// directly by the driver or should not be the preferred address to use to reach the node (for
/// instance, the `rpc_address` set on ScyllaDB nodes might be a private IP, but some clients
/// may have to use a public IP, or pass by a router, e.g. through NAT, to reach that node).
/// This interface allows to deal with such cases, by allowing to translate an address as sent
/// by a ScyllaDB node to another address to be used by the driver for connection.
///
/// Please note that the "known nodes" addresses provided while creating the [`Session`]
/// instance are not translated, only IP address retrieved from or sent by Cassandra nodes
/// to the driver are.
#[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(
untranslated_peer.untranslated_address,
)),
}
}
}
#[async_trait]
// Notice: this is inefficient, 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(|reason| {
TranslationError::InvalidAddressInRule {
translated_addr_str,
reason,
}
});
}
}
}
Err(TranslationError::NoRuleForAddress(
untranslated_peer.untranslated_address,
))
}
}
pub trait DeserializationApiKind: sealed::Sealed {}
pub enum CurrentDeserializationApi {}
impl sealed::Sealed for CurrentDeserializationApi {}
impl DeserializationApiKind for CurrentDeserializationApi {}
#[deprecated(
since = "0.15.0",
note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
pub enum LegacyDeserializationApi {}
#[allow(deprecated)]
impl sealed::Sealed for LegacyDeserializationApi {}
#[allow(deprecated)]
impl DeserializationApiKind for LegacyDeserializationApi {}
/// `Session` manages connections to the cluster and allows to perform queries
pub struct GenericSession<DeserializationApi>
where
DeserializationApi: DeserializationApiKind,
{
cluster: Cluster,
default_execution_profile_handle: ExecutionProfileHandle,
schema_agreement_interval: Duration,
metrics: Arc<Metrics>,
schema_agreement_timeout: Duration,
schema_agreement_automatic_waiting: bool,
refresh_metadata_on_auto_schema_agreement: bool,
keyspace_name: Arc<ArcSwapOption<String>>,
tracing_info_fetch_attempts: NonZeroU32,
tracing_info_fetch_interval: Duration,
tracing_info_fetch_consistency: Consistency,
_phantom_deser_api: PhantomData<DeserializationApi>,
}
pub type Session = GenericSession<CurrentDeserializationApi>;
#[allow(deprecated)]
#[deprecated(
since = "0.15.0",
note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
pub type LegacySession = GenericSession<LegacyDeserializationApi>;
/// This implementation deliberately omits some details from Cluster in order
/// to avoid cluttering the print with much information of little usability.
impl<DeserApi> std::fmt::Debug for GenericSession<DeserApi>
where
DeserApi: DeserializationApiKind,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("cluster", &ClusterNeatDebug(&self.cluster))
.field(
"default_execution_profile_handle",
&self.default_execution_profile_handle,
)
.field("schema_agreement_interval", &self.schema_agreement_interval)
.field("metrics", &self.metrics)
.field(
"auto_await_schema_agreement_timeout",
&self.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)]
#[non_exhaustive]
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,
pub tcp_keepalive_interval: Option<Duration>,
pub default_execution_profile_handle: ExecutionProfileHandle,
pub used_keyspace: Option<String>,
pub keyspace_case_sensitive: bool,
/// Provide our Session with TLS
#[cfg(feature = "ssl")]
pub ssl_context: Option<SslContext>,
pub authenticator: Option<Arc<dyn AuthenticatorProvider>>,
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,
/// If empty, fetch all keyspaces
pub keyspaces_to_fetch: Vec<String>,
/// If true, full schema is fetched with every metadata refresh.
pub fetch_schema_metadata: bool,
/// Interval of sending keepalive requests.
/// If `None`, keepalives are never sent, so `Self::keepalive_timeout` has no effect.
pub keepalive_interval: Option<Duration>,
/// Controls after what time of not receiving response to keepalives a connection is closed.
/// If `None`, connections are never closed due to lack of response to a keepalive message.
pub keepalive_timeout: Option<Duration>,
/// How often the driver should ask if schema is in agreement.
pub schema_agreement_interval: Duration,
/// Controls the timeout for waiting for schema agreement.
/// This works both for manual awaiting schema agreement and for
/// automatic waiting after a schema-altering statement is sent.
pub schema_agreement_timeout: Duration,
/// Controls whether schema agreement is automatically awaited
/// after sending a schema-altering statement.
pub schema_agreement_automatic_waiting: bool,
/// 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,
/// The address translator is used to translate addresses received from ScyllaDB nodes
/// (either with cluster metadata or with an event) to addresses that can be used to
/// actually connect to those nodes. This may be needed e.g. when there is NAT
/// between the nodes and the driver.
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 the driver is to connect to ScyllaCloud, there is a config for it.
#[cfg(feature = "cloud")]
pub cloud_config: Option<Arc<CloudConfig>>,
/// If true, the driver will inject a small delay before flushing data
/// to the socket - by rescheduling the task that writes data to the socket.
/// This gives the task an opportunity to collect more write requests
/// and write them in a single syscall, increasing the efficiency.
///
/// However, this optimization may worsen latency if the rate of requests
/// issued by the application is low, but otherwise the application is
/// heavily loaded with other tasks on the same tokio executor.
/// Please do performance measurements before committing to disabling
/// this option.
pub enable_write_coalescing: bool,
/// Number of attempts to fetch [`TracingInfo`]
/// in [`Session::get_tracing_info`]. Tracing info
/// might not be available immediately on queried node - that's why
/// the driver performs a few attempts with sleeps in between.
pub tracing_info_fetch_attempts: NonZeroU32,
/// Delay between attempts to fetch [`TracingInfo`]
/// in [`Session::get_tracing_info`]. Tracing info
/// might not be available immediately on queried node - that's why
/// the driver performs a few attempts with sleeps in between.
pub tracing_info_fetch_interval: Duration,
/// Consistency level of fetching [`TracingInfo`]
/// in [`Session::get_tracing_info`].
pub tracing_info_fetch_consistency: Consistency,
/// Interval between refreshing cluster metadata. This
/// can be configured according to the traffic pattern
/// for e.g: if they do not want unexpected traffic
/// or they expect the topology to change frequently.
pub cluster_metadata_refresh_interval: Duration,
/// Driver and application self-identifying information,
/// to be sent to server in STARTUP message.
pub identity: SelfIdentity<'static>,
}
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,
tcp_keepalive_interval: None,
schema_agreement_interval: Duration::from_millis(200),
default_execution_profile_handle: ExecutionProfile::new_from_inner(Default::default())
.into_handle(),
used_keyspace: None,
keyspace_case_sensitive: false,
#[cfg(feature = "ssl")]
ssl_context: None,
authenticator: None,
connect_timeout: Duration::from_secs(5),
connection_pool_size: Default::default(),
disallow_shard_aware_port: false,
keyspaces_to_fetch: Vec::new(),
fetch_schema_metadata: true,
keepalive_interval: Some(Duration::from_secs(30)),
keepalive_timeout: Some(Duration::from_secs(30)),
schema_agreement_timeout: Duration::from_secs(60),
schema_agreement_automatic_waiting: true,
address_translator: None,
host_filter: None,
refresh_metadata_on_auto_schema_agreement: true,
#[cfg(feature = "cloud")]
cloud_config: None,
enable_write_coalescing: true,
tracing_info_fetch_attempts: NonZeroU32::new(10).unwrap(),
tracing_info_fetch_interval: Duration::from_millis(3),
tracing_info_fetch_consistency: Consistency::One,
cluster_metadata_refresh_interval: Duration::from_secs(60),
identity: SelfIdentity::default(),
}
}
/// 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 IntoIterator<Item = 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: impl IntoIterator<Item = impl Borrow<SocketAddr>>,
) {
for address in node_addrs {
self.add_known_node_addr(*address.borrow());
}
}
}
/// Creates default [`SessionConfig`], same as [`SessionConfig::new`]
impl Default for SessionConfig {
fn default() -> Self {
Self::new()
}
}
pub(crate) enum RunRequestResult<ResT> {
IgnoredWriteError,
Completed(ResT),
}
impl GenericSession<CurrentDeserializationApi> {
/// Sends a request to the database and receives a response.\
/// Performs an unpaged query, i.e. all results are received in a single response.
///
/// This is the easiest way to make a query, but performance is worse than that of prepared queries.
///
/// It is discouraged to use this method with non-empty values argument (`is_empty()` method from `SerializeRow`
/// trait returns false). In such case, query first needs to be prepared (on a single connection), so
/// driver will perform 2 round trips instead of 1. Please use [`Session::execute_unpaged()`] instead.
///
/// As all results come in one response (no paging is done!), the memory footprint and latency may be huge
/// for statements returning rows (i.e. SELECTs)! Prefer this method for non-SELECTs, and for SELECTs
/// it is best to use paged queries:
/// - to receive multiple pages and transparently iterate through them, use [query_iter](Session::query_iter).
/// - to manually receive multiple pages and iterate through them, use [query_single_page](Session::query_single_page).
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/simple.html) for more information
/// # Arguments
/// * `query` - statement to be executed, can be just a `&str` or the [Query] struct.
/// * `values` - values bound to the query, the 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_unpaged(
/// "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.
/// // Keep in mind that all results come in one response (no paging is done!),
/// // so the memory footprint and latency may be huge!
/// // To prevent that, use `Session::query_iter` or `Session::query_single_page`.
/// let query_rows = session
/// .query_unpaged("SELECT a, b FROM ks.tab", &[])
/// .await?
/// .into_rows_result()?;
///
/// for row in query_rows.rows()? {
/// // Parse row as int and text.
/// let (int_val, text_val): (i32, &str) = row?;
/// }
/// # Ok(())
/// # }
/// ```
pub async fn query_unpaged(
&self,
query: impl Into<Query>,
values: impl SerializeRow,
) -> Result<QueryResult, QueryError> {
self.do_query_unpaged(&query.into(), values).await
}
/// Queries a single page from the database, optionally continuing from a saved point.
///
/// It is discouraged to use this method with non-empty values argument (`is_empty()` method from `SerializeRow`
/// trait returns false). In such case, query first needs to be prepared (on a single connection), so
/// driver will perform 2 round trips instead of 1. Please use [`Session::execute_single_page()`] instead.
///
/// # Arguments
///
/// * `query` - statement to be executed
/// * `values` - values bound to the query
/// * `paging_state` - previously received paging state or [PagingState::start()]
///
/// # Example
///
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use std::ops::ControlFlow;
/// use scylla::statement::PagingState;
///
/// // Manual paging in a loop, unprepared statement.
/// let mut paging_state = PagingState::start();
/// loop {
/// let (res, paging_state_response) = session
/// .query_single_page("SELECT a, b, c FROM ks.tbl", &[], paging_state)
/// .await?;
///
/// // Do something with a single page of results.
/// for row in res
/// .into_rows_result()?
/// .rows::<(i32, &str)>()?
/// {
/// let (a, b) = row?;
/// }
///
/// match paging_state_response.into_paging_control_flow() {
/// ControlFlow::Break(()) => {
/// // No more pages to be fetched.
/// break;
/// }
/// ControlFlow::Continue(new_paging_state) => {
/// // Update paging state from the response, so that query
/// // will be resumed from where it ended the last time.
/// paging_state = new_paging_state;
/// }
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn query_single_page(
&self,
query: impl Into<Query>,
values: impl SerializeRow,
paging_state: PagingState,
) -> Result<(QueryResult, PagingStateResponse), QueryError> {
self.do_query_single_page(&query.into(), values, paging_state)
.await
}
/// Run an unprepared 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] passed to the function
///
/// It is discouraged to use this method with non-empty values argument (`is_empty()` method from `SerializeRow`
/// trait returns false). In such case, query first needs to be prepared (on a single connection), so
/// driver will initially perform 2 round trips instead of 1. Please use [`Session::execute_iter()`] instead.
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/paged.html) for more information.
///
/// # Arguments
/// * `query` - statement to be executed, can be just a `&str` or the [Query] struct.
/// * `values` - values bound to the query, the 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?
/// .rows_stream::<(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 SerializeRow,
) -> Result<QueryPager, QueryError> {
self.do_query_iter(query.into(), values).await
}
/// Execute a prepared statement. Requires a [PreparedStatement]
/// generated using [`Session::prepare`](Session::prepare).\
/// Performs an unpaged query, i.e. all results are received in a single response.
///
/// As all results come in one response (no paging is done!), the memory footprint and latency may be huge
/// for statements returning rows (i.e. SELECTs)! Prefer this method for non-SELECTs, and for SELECTs
/// it is best to use paged queries:
/// - to receive multiple pages and transparently iterate through them, use [execute_iter](Session::execute_iter).
/// - to manually receive multiple pages and iterate through them, use [execute_single_page](Session::execute_single_page).
///
/// 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, the 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_unpaged(&prepared, (to_insert,)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn execute_unpaged(
&self,
prepared: &PreparedStatement,
values: impl SerializeRow,
) -> Result<QueryResult, QueryError> {
self.do_execute_unpaged(prepared, values).await
}
/// Executes a prepared statement, restricting results to single page.
/// Optionally continues fetching results from a saved point.
///
/// # Arguments
///
/// * `prepared` - a statement prepared with [prepare](crate::Session::prepare)
/// * `values` - values bound to the query
/// * `paging_state` - continuation based on a paging state received from a previous paged query or None
///
/// # Example
///
/// ```rust
/// # use scylla::Session;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use std::ops::ControlFlow;
/// use scylla::query::Query;
/// use scylla::statement::{PagingState, PagingStateResponse};
///
/// let paged_prepared = session
/// .prepare(
/// Query::new("SELECT a, b FROM ks.tbl")
/// .with_page_size(100.try_into().unwrap()),
/// )
/// .await?;
///
/// // Manual paging in a loop, prepared statement.
/// let mut paging_state = PagingState::start();
/// loop {
/// let (res, paging_state_response) = session
/// .execute_single_page(&paged_prepared, &[], paging_state)
/// .await?;
///
/// // Do something with a single page of results.
/// for row in res
/// .into_rows_result()?
/// .rows::<(i32, &str)>()?
/// {
/// let (a, b) = row?;
/// }
///
/// match paging_state_response.into_paging_control_flow() {
/// ControlFlow::Break(()) => {
/// // No more pages to be fetched.
/// break;
/// }
/// ControlFlow::Continue(new_paging_state) => {
/// // Update paging continuation from the paging state, so that query
/// // will be resumed from where it ended the last time.
/// paging_state = new_paging_state;
/// }
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn execute_single_page(
&self,
prepared: &PreparedStatement,
values: impl SerializeRow,
paging_state: PagingState,
) -> Result<(QueryResult, PagingStateResponse), QueryError> {
self.do_execute_single_page(prepared, values, paging_state)
.await
}
/// 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] 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, the easiest way is to use a tuple of bound values
///
/// # Example
///
/// ```rust
/// # use scylla::Session;
/// # use futures::StreamExt as _;
/// # use std::error::Error;
/// # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
/// use scylla::prepared_statement::PreparedStatement;
/// use scylla::IntoTypedRows;
///
/// // 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?
/// .rows_stream::<(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 SerializeRow,
) -> Result<QueryPager, QueryError> {
self.do_execute_iter(prepared.into(), values).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
///
/// Avoid using non-empty values (`SerializeRow::is_empty()` return false) for simple queries
/// inside the batch. Such queries will first need to be prepared, so the driver will need to
/// send (numer_of_unprepared_queries_with_values + 1) requests instead of 1 request, severly
/// affecting performance.
///
/// See [the book](https://rust-driver.docs.scylladb.com/stable/queries/batch.html) for more information
///
/// # Arguments
/// * `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, ?)");
///
/// // A query with no bound values
/// batch.append_statement("INSERT INTO ks.tab(a, b) VALUES(5, 6)");
///
/// // Batch values is a tuple of 3 tuples containing values for each query
/// let batch_values = ((1_i32, 2_i32), // Tuple with two values for the first query
/// (4_i32,), // Tuple with one value for the second query
/// ()); // Empty tuple/unit for the third query
///
/// // Run the batch
/// session.batch(&batch, batch_values).await?;
/// # Ok(())
/// # }
/// ```
pub async fn batch(
&self,
batch: &Batch,
values: impl BatchValues,
) -> Result<QueryResult, QueryError> {
self.do_batch(batch, values).await
}
/// Creates a new Session instance that shared resources with
/// the current Session but supports the legacy API.
///
/// This method is provided in order to make migration to the new
/// deserialization API easier. For example, if your program in general uses
/// the new API but you still have some modules left that use the old one,
/// you can use this method to create an instance that supports the old API
/// and pass it to the module that you intend to migrate later.
#[deprecated(
since = "0.15.0",
note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
pub fn make_shared_session_with_legacy_api(&self) -> LegacySession {
LegacySession {
cluster: self.cluster.clone(),
default_execution_profile_handle: self.default_execution_profile_handle.clone(),
metrics: self.metrics.clone(),
refresh_metadata_on_auto_schema_agreement: self
.refresh_metadata_on_auto_schema_agreement,
schema_agreement_interval: self.schema_agreement_interval,
keyspace_name: self.keyspace_name.clone(),
schema_agreement_timeout: self.schema_agreement_timeout,
schema_agreement_automatic_waiting: self.schema_agreement_automatic_waiting,
tracing_info_fetch_attempts: self.tracing_info_fetch_attempts,
tracing_info_fetch_interval: self.tracing_info_fetch_interval,
tracing_info_fetch_consistency: self.tracing_info_fetch_consistency,
_phantom_deser_api: PhantomData,
}
}
}
#[deprecated(
since = "0.15.0",
note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
impl GenericSession<LegacyDeserializationApi> {
pub async fn query_unpaged(
&self,
query: impl Into<Query>,
values: impl SerializeRow,
) -> Result<LegacyQueryResult, QueryError> {
Ok(self
.do_query_unpaged(&query.into(), values)
.await?
.into_legacy_result()?)
}
pub async fn query_single_page(
&self,
query: impl Into<Query>,
values: impl SerializeRow,
paging_state: PagingState,
) -> Result<(LegacyQueryResult, PagingStateResponse), QueryError> {
let (result, paging_state_response) = self
.do_query_single_page(&query.into(), values, paging_state)
.await?;
Ok((result.into_legacy_result()?, paging_state_response))
}
pub async fn query_iter(
&self,
query: impl Into<Query>,
values: impl SerializeRow,
) -> Result<LegacyRowIterator, QueryError> {
self.do_query_iter(query.into(), values)
.await
.map(QueryPager::into_legacy)
}
pub async fn execute_unpaged(
&self,
prepared: &PreparedStatement,
values: impl SerializeRow,
) -> Result<LegacyQueryResult, QueryError> {
Ok(self
.do_execute_unpaged(prepared, values)
.await?
.into_legacy_result()?)
}
pub async fn execute_single_page(
&self,
prepared: &PreparedStatement,
values: impl SerializeRow,
paging_state: PagingState,
) -> Result<(LegacyQueryResult, PagingStateResponse), QueryError> {
let (result, paging_state_response) = self
.do_execute_single_page(prepared, values, paging_state)
.await?;
Ok((result.into_legacy_result()?, paging_state_response))
}
pub async fn execute_iter(
&self,
prepared: impl Into<PreparedStatement>,
values: impl SerializeRow,
) -> Result<LegacyRowIterator, QueryError> {
self.do_execute_iter(prepared.into(), values)
.await
.map(QueryPager::into_legacy)
}
pub async fn batch(
&self,
batch: &Batch,
values: impl BatchValues,
) -> Result<LegacyQueryResult, QueryError> {
Ok(self.do_batch(batch, values).await?.into_legacy_result()?)
}
/// Creates a new Session instance that shares resources with
/// the current Session but supports the new API.
///
/// This method is provided in order to make migration to the new
/// deserialization API easier. For example, if your program in general uses
/// the old API but you want to migrate some modules to the new one, you
/// can use this method to create an instance that supports the new API
/// and pass it to the module that you intend to migrate.
///
/// The new session object will use the same connections and cluster
/// metadata.
pub fn make_shared_session_with_new_api(&self) -> Session {
Session {
cluster: self.cluster.clone(),
default_execution_profile_handle: self.default_execution_profile_handle.clone(),
metrics: self.metrics.clone(),
refresh_metadata_on_auto_schema_agreement: self
.refresh_metadata_on_auto_schema_agreement,
schema_agreement_interval: self.schema_agreement_interval,