### cqlsh example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/usekeyspace.md Example of using USE keyspace in cqlsh. ```sql cqlsh> SELECT * FROM my_keyspace.table; a | b | -------+-------+ 12345 | 54321 | (1 rows) cqlsh> USE my_keyspace; cqlsh:my_keyspace> SELECT * FROM table; a | b | -------+-------+ 12345 | 54321 | (1 rows) ``` -------------------------------- ### Case sensitivity example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/usekeyspace.md Example demonstrating how case sensitivity affects keyspace selection. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { // lowercase name without case sensitivity will use my_keyspace session.use_keyspace("my_keyspace", false).await?; // lowercase name with case sensitivity will use my_keyspace session.use_keyspace("my_keyspace", true).await?; // uppercase name without case sensitivity will use my_keyspace session.use_keyspace("MY_KEYSPACE", false).await?; // uppercase name with case sensitivity will use MY_KEYSPACE session.use_keyspace("MY_KEYSPACE", true).await?; # Ok(()) # } ``` -------------------------------- ### Running Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/README.md Command to run the basic example program if a ScyllaDB server is running. ```sh SCYLLA_URI="127.0.0.1:9042" cargo run --example basic ``` -------------------------------- ### Running the tracing subscriber example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/logging/logging.md Command to run the logging example with RUST_LOG set to info. ```shell RUST_LOG=info cargo run ``` -------------------------------- ### Install mdbook Source: https://github.com/scylladb/scylla-rust-driver/blob/main/CONTRIBUTING.md Install the mdbook tool for building the documentation book. ```shell cargo install mdbook ``` -------------------------------- ### Accessing tables from other keyspaces Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/usekeyspace.md Example of accessing tables from other keyspaces even after using a specific keyspace. ```sql cqlsh:my_keyspace> SELECT * FROM other_keyspace.other_table; ``` -------------------------------- ### Unprepared statement example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/unprepared.md This example demonstrates how to insert a value using an unprepared statement. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn unprepared_statement_example(session: &Session) -> Result<(), Box> { // Insert a value into the table let to_insert: i32 = 12345; session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (to_insert,)) .await?; # Ok(()) # } ``` -------------------------------- ### Install scylla-ccm using uv Source: https://github.com/scylladb/scylla-rust-driver/blob/main/CONTRIBUTING.md Command to install scylla-ccm using uv. ```bash uv tool install git+https://github.com/scylladb/scylla-ccm.git ``` -------------------------------- ### Enabling Snappy Compression Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/connecting/compression.md An example demonstrating how to enable Snappy compression when building a ScyllaDB session using the Scylla Rust Driver. ```rust # extern crate scylla; # extern crate tokio; use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use scylla::client::Compression; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { let uri = std::env::var("SCYLLA_URI") .unwrap_or_else(|_| "172.42.0.2:9042".to_string()); let session: Session = SessionBuilder::new() .known_node(uri) .compression(Some(Compression::Snappy)) .build() .await?; Ok(()) } ``` -------------------------------- ### Using Session::use_keyspace in Rust Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/usekeyspace.md Example of using Session::use_keyspace in the Rust driver. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { session .query_unpaged("INSERT INTO my_keyspace.tab (a) VALUES ('test1')", &[]) .await?; session.use_keyspace("my_keyspace", false).await?; // Now we can omit keyspace name in the statement session .query_unpaged("INSERT INTO tab (a) VALUES ('test2')", &[]) .await?; # Ok(()) # } ``` -------------------------------- ### Set Example (HashSet) Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/collections.md Demonstrates inserting and reading a set of integers using `HashSet`. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use std::collections::HashSet; // Insert a set of ints into the table let my_set: HashSet = vec![1, 2, 3, 4, 5].into_iter().collect(); session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (&my_set,)) .await?; // Read a set of ints from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(HashSet,)>()?; while let Some((set_value,)) = iter.try_next().await? { println!("{:?}", set_value); } # Ok(()) # } ``` -------------------------------- ### Preparing a batch Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/batch.md This example shows how to prepare all statements within a batch at once, which can be more efficient than preparing them individually. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use scylla::statement::batch::Batch; // Create a batch statement with unprepared statements let mut batch: Batch = Default::default(); batch.append_statement("INSERT INTO ks.simple_unprepared1 VALUES(?, ?)"); batch.append_statement("INSERT INTO ks.simple_unprepared2 VALUES(?, ?)"); // Prepare all statements in the batch at once let prepared_batch: Batch = session.prepare_batch(&batch).await?; // Specify bound values to use with each statement let batch_values = ((1_i32, 2_i32), (3_i32, 4_i32)); // Run the prepared batch session.batch(&prepared_batch, batch_values).await?; # Ok(()) # } ``` -------------------------------- ### Custom Authentication Implementation Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/connecting/authentication.md Example demonstrating how to implement and use custom authentication by defining AuthenticatorSession and AuthenticatorProvider, and then configuring SessionBuilder. ```rust # extern crate scylla; # extern crate scylla_cql; # extern crate tokio; # extern crate bytes; # extern crate async_trait; # use std::error::Error; # use std::sync::Arc; use bytes::{BufMut, BytesMut}; use async_trait::async_trait; use scylla::authentication::{AuthError, AuthenticatorProvider, AuthenticatorSession}; struct CustomAuthenticator; #[async_trait] impl AuthenticatorSession for CustomAuthenticator { // to handle an authentication challenge initiated by the server. // The information contained in the token parameter is authentication protocol specific. // It may be NULL or empty. async fn evaluate_challenge( &mut self, _token: Option<&[u8]>, ) -> Result>, AuthError> { Err("Challenges are not expected".to_string()) } // to handle the success phase of exchange. The token parameters contain information that may be used to finalize the request. async fn success(&mut self, _token: Option<&[u8]>) -> Result<(), AuthError> { Ok(()) } } struct CustomAuthenticatorProvider; #[async_trait] impl AuthenticatorProvider for CustomAuthenticatorProvider { async fn start_authentication_session( &self, _name: &str, ) -> Result<(Option>, Box), AuthError> { let mut response = BytesMut::new(); let cred = "\0cassandra\0cassandra"; let cred_length = 20; response.put_i32(cred_length); response.put_slice(cred.as_bytes()); Ok((Some(response.to_vec()), Box::new(CustomAuthenticator))) } } async fn authentication_example() -> Result<(), Box> { use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; let _session: Session = SessionBuilder::new() .known_node("127.0.0.1:9042") .authenticator_provider(Arc::new(CustomAuthenticatorProvider)) .build() .await?; Ok(()) } ``` -------------------------------- ### Run doctests for the book Source: https://github.com/scylladb/scylla-rust-driver/blob/main/CONTRIBUTING.md Run code examples in the book as doctests in the scylla crate, including all features. ```bash cargo test --doc -p scylla --all-features ``` -------------------------------- ### Set Example (BTreeSet) Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/collections.md Demonstrates inserting and reading a set of integers using `BTreeSet`. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use std::collections::BTreeSet; // Insert a set of ints into the table let my_set: BTreeSet = vec![1, 2, 3, 4, 5].into_iter().collect(); session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (&my_set,)) .await?; // Read a set of ints from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(BTreeSet,)>()?; while let Some((set_value,)) = iter.try_next().await? { println!("{:?}", set_value); } # Ok(()) # } ``` -------------------------------- ### Release Notes Template Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/MAINTENANCE.md A template for writing release notes, including placeholders for statistics and a list of changes. ```markdown The ScyllaDB team is pleased to announce ScyllaDB Rust Driver X.Y.Z, an asynchronous CQL driver for Rust, optimized for ScyllaDB, but also compatible with Apache Cassandra! Some interesting statistics: - over 2.103k downloads on crates! - over 556 GitHub stars! ``` -------------------------------- ### Basic Usage Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/README.md Demonstrates how to connect to a ScyllaDB instance, query data, and process results using streams. ```rust use futures::TryStreamExt; let uri = "127.0.0.1:9042"; let session: Session = SessionBuilder::new().known_node(uri).build().await?; let query_pager = session.query_iter("SELECT a, b, c FROM ks.t", &[]).await?; let mut stream = query_pager.rows_stream::<(i32, i32, String)>()?; while let Some((a, b, c)) = stream.try_next().await? { println!("a, b, c: {}, {}, {}", a, b, c); } ``` -------------------------------- ### Querying rows from the table and printing them Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/unprepared.md This example shows how to query rows from a table and print them, demonstrating the use of `query_unpaged` and handling the result. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { // NOTE: using unpaged queries (SELECTs) is discouraged in general. // Query results may be so big that it is not preferable to fetch them all at once. // Even with small results, if there are a lot of tombstones, then there can be similar bad consequences. // However, `query_unpaged` will return all results in one, possibly giant, piece // (unless a timeout occurs due to high load incurred by the cluster). // This: // - increases latency, // - has large memory footprint, // - puts high load on the cluster, // - is more likely to time out (because big work takes more time than little work, // and returning one large piece of data is more work than returning one chunk of data). // To sum up, **for SELECTs** (especially those that may return a lot of data) // **prefer paged queries**, e.g. with `Session::query_iter()`. // Query rows from the table and print them let result = session.query_unpaged("SELECT a FROM ks.tab", &[]) .await?; let mut iter = result.rows::<(i32,)>()?; while let Some(read_row) = iter.next().transpose()? { println!("Read a value from row: {}", read_row.0); } # Ok(()) # } ``` -------------------------------- ### Map Example (HashMap) Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/collections.md Demonstrates inserting and reading a map of strings to integers using `HashMap`. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use std::collections::HashMap; // Insert a map of text and int into the table let mut my_map: HashMap = HashMap::new(); my_map.insert("abcd".to_string(), 16); session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (&my_map,)) .await?; // Read a map from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(HashMap,)>()?; while let Some((map_value,)) = iter.try_next().await? { println!("{:?}", map_value); } # Ok(()) # } ``` -------------------------------- ### Set Example (Vec) Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/collections.md Demonstrates inserting and reading a set of integers using `Vec`. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; // Insert a set of ints into the table let my_set: Vec = vec![1, 2, 3, 4, 5]; session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (&my_set,)) .await?; // Read a set of ints from the table let mut stream = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(Vec,)>()?; while let Some((set_value,)) = stream.try_next().await? { println!("{:?}", set_value); } # Ok(()) # } ``` -------------------------------- ### Uuid Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/uuid.md Demonstrates inserting and reading UUID values into and from a ScyllaDB table using the `uuid::Uuid` type. ```rust # extern crate scylla; # extern crate uuid; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use uuid::Uuid; // Insert some uuid into the table let to_insert: Uuid = Uuid::parse_str("8e14e760-7fa8-11eb-bc66-000000000001")?; session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (to_insert,))?; // Read uuid from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await?; .rows_stream::<(Uuid,)>()?; while let Some((uuid_value,)) = iter.try_next().await? { println!("{:?}", uuid_value); } # Ok(()) # } ``` -------------------------------- ### Counter Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/counter.md Demonstrates how to add to a counter value and read counter values from a table using the ScyllaDB Rust driver. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use scylla::value::Counter; // Add to counter value let to_add: Counter = Counter(100); session .query_unpaged("UPDATE keyspace.table SET c = c + ? WHERE pk = 15", (to_add,)) .await?; // Read counter from the table let mut stream = session.query_iter("SELECT c FROM keyspace.table", &[]) .await?; .rows_stream::<(Counter,)>()?; while let Some((counter_value,)) = stream.try_next().await? { let counter_int_value: i64 = counter_value.0; println!("{}", counter_int_value); } # Ok(()) # } ``` -------------------------------- ### Map Example (BTreeMap) Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/collections.md Demonstrates inserting and reading a map of strings to integers using `BTreeMap`. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use std::collections::BTreeMap; // Insert a map of text and int into the table let mut my_map: BTreeMap = BTreeMap::new(); my_map.insert("abcd".to_string(), 16); session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (&my_map,)) .await?; // Read a map from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(BTreeMap,)>()?; while let Some((map_value,)) = iter.try_next().await? { println!("{:?}", map_value); } # Ok(()) # } ``` -------------------------------- ### Basic DefaultPolicy configuration Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/load-balancing/default-policy.md Example demonstrating the creation of a DefaultPolicy with preferred datacenter, token awareness enabled, and datacenter failover permitted. ```rust # extern crate scylla; # fn test_if_compiles() { use scylla::policies::load_balancing::DefaultPolicy; let default_policy = DefaultPolicy::builder() .prefer_datacenter("dc1".to_string()) .token_aware(true) .permit_dc_failover(true) .build(); # } ``` -------------------------------- ### Tracing a prepared statement Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/tracing/basic.md This example demonstrates how to prepare a statement, enable tracing for it, execute the prepared statement, and then fetch the tracing details using the obtained tracing ID. ```rust # extern crate scylla; # extern crate uuid; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use scylla::statement::prepared::PreparedStatement; use scylla::response::query_result::QueryResult; use scylla::observability::tracing::TracingInfo; use uuid::Uuid; // Prepare the statement let mut prepared: PreparedStatement = session .prepare("SELECT a FROM ks.tab") .await?; // Enable tracing for the prepared statement prepared.set_tracing(true); let res: QueryResult = session.execute_unpaged(&prepared, &[]).await?; let tracing_id: Option = res.tracing_id(); if let Some(id) = tracing_id { // Query tracing info from system_traces.sessions and system_traces.events let tracing_info: TracingInfo = session.get_tracing_info(&id).await?; println!("tracing_info: {:#?}", tracing_info); } # Ok(()) # } ``` -------------------------------- ### Simple ScyllaDB Query Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/quickstart/example.md A Rust program that connects to a ScyllaDB cluster, creates a keyspace and table, inserts a value, and then queries and prints the inserted value. ```rust # extern crate scylla; # extern crate tokio; # extern crate futures; use futures::TryStreamExt; use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Create a new Session which connects to node at 127.0.0.1:9042 // (or SCYLLA_URI if specified) let uri = std::env::var("SCYLLA_URI") .unwrap_or_else(|_| "172.42.0.2:9042".to_string()); let session: Session = SessionBuilder::new() .known_node(uri) .build() .await?; // Create an example keyspace and table session .query_unpaged( "CREATE KEYSPACE IF NOT EXISTS ks WITH REPLICATION = \" {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[], ) .await?; session .query_unpaged( "CREATE TABLE IF NOT EXISTS ks.extab (a int primary key)", &[], ) .await?; // Insert a value into the table let to_insert: i32 = 12345; session .query_unpaged("INSERT INTO ks.extab (a) VALUES(?)", (to_insert,)) .await?; // Query rows from the table and print them let mut iter = session.query_iter("SELECT a FROM ks.extab", &[]) .await? .rows_stream::<(i32,)>()?; while let Some(read_row) = iter.try_next().await? { println!("Read a value from row: {}", read_row.0); } Ok(()) } ``` -------------------------------- ### Start a ScyllaDB cluster Source: https://github.com/scylladb/scylla-rust-driver/blob/main/CONTRIBUTING.md Command to start a ScyllaDB cluster without running any tests. ```bash make up ``` -------------------------------- ### Build the book Source: https://github.com/scylladb/scylla-rust-driver/blob/main/CONTRIBUTING.md Build the documentation book. The HTML output will be in the docs/book directory. ```bash mdbook build docs ``` -------------------------------- ### Basic main.rs structure Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/quickstart/create-project.md A minimal Rust code structure for a ScyllaDB project. ```rust # extern crate scylla; # extern crate tokio; use scylla::client::session::Session; #[tokio::main] async fn main() { println!("Hello scylla!"); } ``` -------------------------------- ### Percentile Speculative Execution Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/speculative-execution/percentile.md Example of how to configure and use the PercentileSpeculativeExecutionPolicy in a ScyllaDB Rust Driver Session. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles() -> Result<(), Box> { use std::{sync::Arc, time::Duration}; use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use scylla::{ policies::speculative_execution::PercentileSpeculativeExecutionPolicy, client::execution_profile::ExecutionProfile, }; let policy = PercentileSpeculativeExecutionPolicy { max_retry_count: 3, percentile: 99.0, }; let handle = ExecutionProfile::builder() .speculative_execution_policy(Some(Arc::new(policy))) .build() .into_handle(); let session: Session = SessionBuilder::new() .known_node("127.0.0.1:9042") .default_execution_profile_handle(handle) .build() .await?; # Ok(()) # } ``` -------------------------------- ### Monotonic Timestamp Generator Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/timestamp-generators.md Example demonstrating how to use MonotonicTimestampGenerator with SessionBuilder to automatically generate monotonic timestamps for statements. ```rust # extern crate scylla; # use std::error::Error; # async fn check_only_compiles() -> Result<(), Box> { use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use scylla::policies::timestamp_generator::MonotonicTimestampGenerator; use scylla::statement::unprepared::Statement; use std::sync::Arc; let session: Session = SessionBuilder::new() .known_node("127.0.0.1:9042") .timestamp_generator(Arc::new(MonotonicTimestampGenerator::new())) .build() .await?; // This statement will have a timestamp generated // by the monotonic timestamp generator let my_statement: Statement = Statement::new("INSERT INTO ks.tab (a) VALUES(?)"); let to_insert: i32 = 12345; session.query_unpaged(my_statement, (to_insert,)).await?; # Ok(()) # } ``` -------------------------------- ### Owned Types Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/scylla/src/deserialize/README.md Illustrates how owned types, which do not borrow from the serialized response and fully own their data, should implement the respective traits for all lifetimes. This example shows the signature for implementing traits for owned types. ```rust # use scylla_cql::frame::response::result::{NativeType, ColumnType}; # use scylla_cql::deserialize::{DeserializationError, FrameSlice, TypeCheckError}; ``` -------------------------------- ### Duration Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/duration.md Demonstrates inserting and reading Duration values using the ScyllaDB Rust driver. ```rust extern crate scylla; extern crate futures; use scylla::client::session::Session; use std::error::Error; async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; use scylla::value::CqlDuration; // Insert some duration into the table let to_insert: CqlDuration = CqlDuration { months: 1, days: 2, nanoseconds: 3 }; session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (to_insert,)) .await?; // Read duration from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(CqlDuration,)>()?; while let Some((duration_value,)) = iter.try_next().await? { println!("{:?}", duration_value); } Ok(()) } ``` -------------------------------- ### Serve the book locally Source: https://github.com/scylladb/scylla-rust-driver/blob/main/CONTRIBUTING.md Serve the documentation book on a local HTTP server with automatic refresh on changes. ```bash mdbook serve docs ``` -------------------------------- ### To use in `Session` Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/retry-policy/downgrading-consistency.md This example shows how to configure the `DowngradingConsistencyRetryPolicy` for a `Session` using an `ExecutionProfile`. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # use std::sync::Arc; # async fn check_only_compiles() -> Result<(), Box> { use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use scylla::client::execution_profile::ExecutionProfile; use scylla::policies::retry::DowngradingConsistencyRetryPolicy; let handle = ExecutionProfile::builder() .retry_policy(Arc::new(DowngradingConsistencyRetryPolicy::new())) .build() .into_handle(); let session: Session = SessionBuilder::new() .known_node("127.0.0.1:9042") .default_execution_profile_handle(handle) .build() .await?; # Ok(()) # } ``` -------------------------------- ### Manual Paging with a PreparedStatement Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/paged.md This example shows how to fetch a single page using a `PreparedStatement` and manage the paging state. It also highlights the performance benefit of using prepared statements. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use scylla::statement::unprepared::Statement; use scylla::response::{PagingState, PagingStateResponse}; use std::ops::ControlFlow; let paged_prepared = session .prepare(Statement::new("SELECT a, b, c FROM ks.t").with_page_size(7)) .await?; let mut paging_state = PagingState::start(); loop { let (res, paging_state_response) = session .execute_single_page(&paged_prepared, &[], paging_state) .await?; let rows_res = res.into_rows_result()?; println!( "Paging state response from the prepared statement execution: {:#?} ({} rows)", paging_state_response, rows_res.rows_num(), ); 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(()) # } ``` -------------------------------- ### Enabling log feature on tracing crate Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/logging/logging.md Example of how to enable the 'log' feature for the tracing crate in Cargo.toml. ```toml tracing = { version = "0.1.40" , features = ["log"] } ``` -------------------------------- ### Using tracing subscriber Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/logging/logging.md Example of setting up a tracing subscriber to view logs from the ScyllaDB Rust driver. ```rust # extern crate scylla; # extern crate tokio; # extern crate tracing; # extern crate tracing_subscriber; # use std::error::Error; # use scylla::client::session::Session; # use scylla::client::session_builder::SessionBuilder; use tracing::info; #[tokio::main] async fn main() -> Result<(), Box> { // Install global collector configured based on RUST_LOG env var // This collector will receive logs from the driver tracing_subscriber::fmt::init(); let uri = std::env::var("SCYLLA_URI") .unwrap_or_else(|_| "172.42.0.2:9042".to_string()); info!("Connecting to {}", uri); let session: Session = SessionBuilder::new().known_node(uri).build().await?; session .query_unpaged( "CREATE KEYSPACE IF NOT EXISTS ks WITH REPLICATION = \" {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[], ) .await?; // This query should generate a warning message session.query_unpaged("USE ks", &[]).await?; Ok(()) } ``` -------------------------------- ### ExecutionProfile Options Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/execution-profiles/maximal-example.md This Rust code snippet demonstrates how to build an `ExecutionProfile` with various options, including consistency levels, timeouts, retry policies, load balancing policies, and speculative execution policies. It also shows how to associate this profile with a query. ```rust # extern crate scylla; # use std::error::Error; # async fn check_only_compiles() -> Result<(), Box> { use scylla::statement::unprepared::Statement; use scylla::policies::speculative_execution::SimpleSpeculativeExecutionPolicy; use scylla::statement::{Consistency, SerialConsistency}; use scylla::client::execution_profile::ExecutionProfile; use scylla::policies::load_balancing::DefaultPolicy; use scylla::policies::retry::FallthroughRetryPolicy; use std::{sync::Arc, time::Duration}; let profile = ExecutionProfile::builder() .consistency(Consistency::All) .serial_consistency(Some(SerialConsistency::Serial)) .request_timeout(Some(Duration::from_secs(30))) .retry_policy(Arc::new(FallthroughRetryPolicy::new())) .load_balancing_policy(Arc::new(DefaultPolicy::default())) .speculative_execution_policy( Some( Arc::new( SimpleSpeculativeExecutionPolicy { max_retry_count: 3, retry_interval: Duration::from_millis(100), } ) ) ) .build(); let mut query = Statement::from("SELECT * FROM ks.table"); query.set_execution_profile_handle(Some(profile.into_handle())); # Ok(()) # } ``` -------------------------------- ### List Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/collections.md Demonstrates inserting and reading a list of integers using `Vec`. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use futures::TryStreamExt; // Insert a list of ints into the table let my_list: Vec = vec![1, 2, 3, 4, 5]; session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (&my_list,)) .await?; // Read a list of ints from the table let mut stream = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(Vec,)>()?; while let Some((list_value,)) = stream.try_next().await? { println!("{:?}", list_value); } # Ok(()) # } ``` -------------------------------- ### Basic DeserializeValue Implementation Source: https://github.com/scylladb/scylla-rust-driver/blob/main/scylla/src/deserialize/README.md An example of implementing DeserializeValue for a simple Vec type. ```rust # use scylla_cql::deserialize::value::DeserializeValue; use thiserror::Error; struct MyVec(Vec); #[derive(Debug, Error)] enum MyDeserError { #[error("Expected bytes")] ExpectedBytes, #[error("Expected non-null")] ExpectedNonNull, } impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for MyVec { fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> { if let ColumnType::Native(NativeType::Blob) = typ { return Ok(()); } Err(TypeCheckError::new(MyDeserError::ExpectedBytes)) } fn deserialize( _typ: &'metadata ColumnType<'metadata>, v: Option>, ) -> Result { v.ok_or_else(|| DeserializationError::new(MyDeserError::ExpectedNonNull)) .map(|v| Self(v.as_slice().to_vec())) } } ``` -------------------------------- ### DowngradingConsistencyRetryPolicy Example Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/retry-policy/downgrading-consistency.md This code snippet shows how to create an ExecutionProfile with a DowngradingConsistencyRetryPolicy and apply it to a PreparedStatement. ```rust use std::error::Error; use std::sync::Arc; use scylla::statement::prepared::PreparedStatement; use scylla::client::execution_profile::ExecutionProfile; use scylla::policies::retry::DowngradingConsistencyRetryPolicy; use scylla::Session; async fn check_only_compiles(session: &Session) -> Result<(), Box> { use scylla::statement::prepared::PreparedStatement; use scylla::client::execution_profile::ExecutionProfile; use scylla::policies::retry::DowngradingConsistencyRetryPolicy; let handle = ExecutionProfile::builder() .retry_policy(Arc::new(DowngradingConsistencyRetryPolicy::new())) .build() .into_handle(); // Create PreparedStatement manually and set the retry policy let mut prepared: PreparedStatement = session .prepare("INSERT INTO ks.tab (a) VALUES(?)") .await?; prepared.set_execution_profile_handle(Some(handle)); // Execute the statement using this retry policy let to_insert: i32 = 12345; session.execute_unpaged(&prepared, (to_insert,)).await?; Ok(()) } ``` -------------------------------- ### Using log collector with env_logger Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/logging/logging.md Example of setting up env_logger to collect tracing events when the 'log' feature is enabled. ```rust # extern crate scylla; # extern crate tokio; # extern crate tracing; # extern crate env_logger; # use std::error::Error; # use scylla::client::session::Session; # use scylla::client::session_builder::SessionBuilder; use tracing::info; #[tokio::main] async fn main() -> Result<(), Box> { // Setup `log` collector that uses RUST_LOG env variable to configure // verbosity. env_logger::init(); let uri = std::env::var("SCYLLA_URI").unwrap_or_else(|_| "172.42.0.2:9042".to_string()); info!("Connecting to {}", uri); let session: Session = SessionBuilder::new().known_node(uri).build().await?; session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; session.query_unpaged("USE examples_ks", &[]).await?; Ok(()) } ``` -------------------------------- ### Using Session::query_* to send raw use keyspace statement Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/statements/usekeyspace.md Example of sending a raw use keyspace statement using Session::query_*. ```rust # extern crate scylla; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { session.query_unpaged("USE my_keyspace", &[]).await?; # Ok(()) # } ``` -------------------------------- ### CqlTime Usage Source: https://github.com/scylladb/scylla-rust-driver/blob/main/docs/source/data-types/time.md Example of inserting and reading a CqlTime value from ScyllaDB. ```rust # extern crate scylla; # extern crate futures; # use scylla::client::session::Session; # use std::error::Error; # async fn check_only_compiles(session: &Session) -> Result<(), Box> { use scylla::value::CqlTime; use futures::TryStreamExt; // 64 seconds since midnight let to_insert = CqlTime(64 * 1_000_000_000); // Insert time into the table session .query_unpaged("INSERT INTO keyspace.table (a) VALUES(?)", (to_insert,)) .await?; // Read time from the table let mut iter = session.query_iter("SELECT a FROM keyspace.table", &[]) .await? .rows_stream::<(CqlTime,)>()?; while let Some((value,)) = iter.try_next().await? { // ... } # Ok(()) # } ```