pub struct Session { /* private fields */ }
Expand description
Session
manages connections to the cluster and allows to perform queries
Implementations
sourceimpl Session
impl Session
Represents a CQL session, which can be used to communicate with the database
sourcepub async fn connect(config: SessionConfig) -> Result<Session, NewSessionError>
pub async fn connect(config: SessionConfig) -> Result<Session, NewSessionError>
Estabilishes a CQL session with the database
Usually it’s easier to use SessionBuilder
instead of calling Session::connect
directly
Arguments
config
- Connection configuration - known nodes, Compression, etc. Must contain at least one known node.
Example
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?;
sourcepub async fn query(
&self,
query: impl Into<Query>,
values: impl ValueList
) -> Result<QueryResult, QueryError>
pub async fn query(
&self,
query: impl Into<Query>,
values: impl ValueList
) -> Result<QueryResult, QueryError>
Sends a query to the database and receives a response.
Returns only a single page of results, to receive multiple pages use query_iter
This is the easiest way to make a query, but performance is worse than that of prepared queries.
See the book for more information
Arguments
query
- query to perform, can be just a&str
or the Query struct.values
- values bound to the query, easiest way is to use a tuple of bound values
Examples
// Insert an int and text into a table
session
.query(
"INSERT INTO ks.tab (a, b) VALUES(?, ?)",
(2_i32, "some text")
)
.await?;
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?;
}
}
sourcepub async fn query_paged(
&self,
query: impl Into<Query>,
values: impl ValueList,
paging_state: Option<Bytes>
) -> Result<QueryResult, QueryError>
pub async fn query_paged(
&self,
query: impl Into<Query>,
values: impl ValueList,
paging_state: Option<Bytes>
) -> Result<QueryResult, QueryError>
Queries the database with a custom paging state.
Arguments
query
- query to be performedvalues
- values bound to the querypaging_state
- previously received paging state or None
sourcepub async fn query_iter(
&self,
query: impl Into<Query>,
values: impl ValueList
) -> Result<RowIterator, QueryError>
pub async fn query_iter(
&self,
query: impl Into<Query>,
values: impl ValueList
) -> Result<RowIterator, QueryError>
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 passed to the function
See the book for more information
Arguments
query
- query to perform, can be just a&str
or the Query struct.values
- values bound to the query, easiest way is to use a tuple of bound values
Example
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);
}
sourcepub async fn prepare(
&self,
query: impl Into<Query>
) -> Result<PreparedStatement, QueryError>
pub async fn prepare(
&self,
query: impl Into<Query>
) -> Result<PreparedStatement, QueryError>
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)
See the book for more information
Arguments
query
- query to prepare, can be just a&str
or the Query struct.
Example
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?;
sourcepub async fn execute(
&self,
prepared: &PreparedStatement,
values: impl ValueList
) -> Result<QueryResult, QueryError>
pub async fn execute(
&self,
prepared: &PreparedStatement,
values: impl ValueList
) -> Result<QueryResult, QueryError>
Execute a prepared query. Requires a PreparedStatement
generated using Session::prepare
Returns only a single page of results, to receive multiple pages use 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)
See the book for more information
Arguments
prepared
- the prepared statement to execute, generated usingSession::prepare
values
- values bound to the query, easiest way is to use a tuple of bound values
Example
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?;
sourcepub async fn execute_paged(
&self,
prepared: &PreparedStatement,
values: impl ValueList,
paging_state: Option<Bytes>
) -> Result<QueryResult, QueryError>
pub async fn execute_paged(
&self,
prepared: &PreparedStatement,
values: impl ValueList,
paging_state: Option<Bytes>
) -> Result<QueryResult, QueryError>
sourcepub async fn execute_iter(
&self,
prepared: impl Into<PreparedStatement>,
values: impl ValueList
) -> Result<RowIterator, QueryError>
pub async fn execute_iter(
&self,
prepared: impl Into<PreparedStatement>,
values: impl ValueList
) -> Result<RowIterator, QueryError>
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 for more information
Arguments
prepared
- the prepared statement to execute, generated usingSession::prepare
values
- values bound to the query, easiest way is to use a tuple of bound values
Example
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);
}
sourcepub async fn batch(
&self,
batch: &Batch,
values: impl BatchValues
) -> Result<BatchResult, QueryError>
pub async fn batch(
&self,
batch: &Batch,
values: impl BatchValues
) -> Result<BatchResult, QueryError>
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 for more information
Arguments
batch
- Batch to be performedvalues
- List of values for each query, it’s the easiest to use a tuple of tuples
Example
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?;
sourcepub async fn use_keyspace(
&self,
keyspace_name: impl Into<String>,
case_sensitive: bool
) -> Result<(), QueryError>
pub async fn use_keyspace(
&self,
keyspace_name: impl Into<String>,
case_sensitive: bool
) -> Result<(), QueryError>
Sends USE <keyspace_name>
request on all connections
This allows to write SELECT * FROM table
instead of SELECT * FROM keyspace.table
Note that even failed use_keyspace
can change currently used keyspace - the request is sent on all connections and
can overwrite previously used keyspace.
Call only one use_keyspace
at a time.
Trying to do two use_keyspace
requests simultaneously with different names
can end with some connections using one keyspace and the rest using the other.
See the book for more information
Arguments
keyspace_name
- keyspace name to use, keyspace names can have up to 48 alphanumeric characters and contain underscorescase_sensitive
- if set to true the generated query will put keyspace name in quotes
Example
session
.query("INSERT INTO my_keyspace.tab (a) VALUES ('test1')", &[])
.await?;
session.use_keyspace("my_keyspace", false).await?;
// Now we can omit keyspace name in the query
session
.query("INSERT INTO tab (a) VALUES ('test2')", &[])
.await?;
sourcepub async fn refresh_metadata(&self) -> Result<(), QueryError>
pub async fn refresh_metadata(&self) -> Result<(), QueryError>
Manually trigger a metadata refresh
The driver will fetch current nodes in the cluster and update its metadata
Normally this is not needed, the driver should automatically detect all metadata changes in the cluster
sourcepub fn get_metrics(&self) -> Arc<Metrics>
pub fn get_metrics(&self) -> Arc<Metrics>
Access metrics collected by the driver
Driver collects various metrics like number of queries or query latencies.
They can be read using this method
sourcepub fn get_cluster_data(&self) -> Arc<ClusterData>
pub fn get_cluster_data(&self) -> Arc<ClusterData>
Access cluster data collected by the driver
Driver collects various information about network topology or schema.
They can be read using this method
sourcepub async fn get_tracing_info(
&self,
tracing_id: &Uuid
) -> Result<TracingInfo, QueryError>
pub async fn get_tracing_info(
&self,
tracing_id: &Uuid
) -> Result<TracingInfo, QueryError>
Get TracingInfo
of a traced query performed earlier
See the book for more information about query tracing
sourcepub async fn get_tracing_info_custom(
&self,
tracing_id: &Uuid,
config: &GetTracingConfig
) -> Result<TracingInfo, QueryError>
pub async fn get_tracing_info_custom(
&self,
tracing_id: &Uuid,
config: &GetTracingConfig
) -> Result<TracingInfo, QueryError>
Queries tracing info with custom retry settings.
Tracing info might not be available immediately on queried node -
that’s why the driver performs a few attempts with sleeps in between.
GetTracingConfig
allows to specify a custom querying strategy.
pub async fn await_schema_agreement(&self) -> Result<(), QueryError>
pub async fn await_timed_schema_agreement(
&self,
timeout_duration: Duration
) -> Result<bool, QueryError>
pub async fn check_schema_agreement(&self) -> Result<bool, QueryError>
pub async fn fetch_schema_version(&self) -> Result<Uuid, QueryError>
Auto Trait Implementations
impl !RefUnwindSafe for Session
impl Send for Session
impl Sync for Session
impl Unpin for Session
impl !UnwindSafe for Session
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more