From f41a11a287fd01737e590a1ed151840eb284c0b3 Mon Sep 17 00:00:00 2001 From: Piotr Dulikowski Date: Tue, 14 Mar 2023 12:04:02 +0100 Subject: [PATCH] examples: adjust to use the new interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit goes over all unadjusted examples and changes them to use the new deserialization framework. Again, it contains a lot of changes, but they are quite simple. Co-authored-by: Wojciech Przytuła --- examples/Cargo.toml | 1 + examples/allocations.rs | 10 +++----- examples/auth.rs | 2 +- examples/basic.rs | 31 ++++++++++++------------ examples/cloud.rs | 2 +- examples/compare-tokens.rs | 6 ++--- examples/cql-time-types.rs | 23 +++++++++--------- examples/cqlsh-rs.rs | 15 +++++++----- examples/custom_deserialization.rs | 7 ++++-- examples/custom_load_balancing_policy.rs | 6 ++--- examples/execution_profile.rs | 12 ++++----- examples/get_by_name.rs | 23 ++++++++++++------ examples/logging.rs | 4 +-- examples/logging_log.rs | 5 ++-- examples/parallel-prepared.rs | 4 +-- examples/parallel.rs | 4 +-- examples/query_history.rs | 5 ++-- examples/schema_agreement.rs | 9 +++---- examples/select-paging.rs | 11 ++++----- examples/speculative-execution.rs | 6 ++--- examples/tls.rs | 9 +++---- examples/tower.rs | 18 ++++++++------ examples/tracing.rs | 31 ++++++++++++------------ examples/user-defined-type.rs | 11 ++++----- examples/value_list.rs | 16 +++++++----- 25 files changed, 141 insertions(+), 130 deletions(-) diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 5b335fd34f..d050342752 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -19,6 +19,7 @@ scylla = { path = "../scylla", features = [ "num-bigint-04", "bigdecimal-04", ] } +scylla-cql = { path = "../scylla-cql" } tokio = { version = "1.34", features = ["full"] } tracing = { version = "0.1.25", features = ["log"] } tracing-subscriber = { version = "0.3.14", features = ["env-filter"] } diff --git a/examples/allocations.rs b/examples/allocations.rs index f87f7641f5..d10ad9771b 100644 --- a/examples/allocations.rs +++ b/examples/allocations.rs @@ -1,5 +1,6 @@ use anyhow::Result; -use scylla::{statement::prepared_statement::PreparedStatement, LegacySession, SessionBuilder}; +use scylla::transport::session::Session; +use scylla::{statement::prepared_statement::PreparedStatement, SessionBuilder}; use std::io::Write; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; @@ -65,7 +66,7 @@ fn print_stats(stats: &stats_alloc::Stats, reqs: f64) { } async fn measure( - session: Arc, + session: Arc, prepared: Arc, reqs: usize, parallelism: usize, @@ -128,10 +129,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", args.node); - let session: LegacySession = SessionBuilder::new() - .known_node(args.node) - .build_legacy() - .await?; + let session: Session = SessionBuilder::new().known_node(args.node).build().await?; let session = Arc::new(session); session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; diff --git a/examples/auth.rs b/examples/auth.rs index ded1115f35..22fbee0077 100644 --- a/examples/auth.rs +++ b/examples/auth.rs @@ -10,7 +10,7 @@ async fn main() -> Result<()> { let session = SessionBuilder::new() .known_node(uri) .user("cassandra", "cassandra") - .build_legacy() + .build() .await .unwrap(); diff --git a/examples/basic.rs b/examples/basic.rs index ad8570db54..83a4fb079d 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -1,7 +1,7 @@ use anyhow::Result; -use futures::TryStreamExt; -use scylla::macros::FromRow; -use scylla::transport::session::LegacySession; +use scylla::frame::response::result::Row; +use scylla::transport::session::Session; +use scylla::DeserializeRow; use scylla::SessionBuilder; use std::env; @@ -11,7 +11,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; @@ -53,23 +53,24 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT a, b, c FROM examples_ks.basic", &[]) .await? - .into_typed::<(i32, i32, String)>(); + .into_typed::<(i32, i32, String)>()?; while let Some((a, b, c)) = iter.try_next().await? { println!("a, b, c: {}, {}, {}", a, b, c); } - // Or as custom structs that derive FromRow - #[derive(Debug, FromRow)] + // Or as custom structs that derive DeserializeRow + #[allow(unused)] + #[derive(Debug, DeserializeRow)] struct RowData { - _a: i32, - _b: Option, - _c: String, + a: i32, + b: Option, + c: String, } let mut iter = session .query_iter("SELECT a, b, c FROM examples_ks.basic", &[]) .await? - .into_typed::(); + .into_typed::()?; while let Some(row_data) = iter.try_next().await? { println!("row_data: {:?}", row_data); } @@ -77,15 +78,13 @@ async fn main() -> Result<()> { // Or simply as untyped rows let mut iter = session .query_iter("SELECT a, b, c FROM examples_ks.basic", &[]) - .await?; - while let Some(row) = iter.try_next().await? { + .await? + .into_typed::()?; + while let Some(row) = iter.next().await.transpose()? { let a = row.columns[0].as_ref().unwrap().as_int().unwrap(); let b = row.columns[1].as_ref().unwrap().as_int().unwrap(); let c = row.columns[2].as_ref().unwrap().as_text().unwrap(); println!("a, b, c: {}, {}, {}", a, b, c); - - // Alternatively each row can be parsed individually - // let (a2, b2, c2) = row.into_typed::<(i32, i32, String)>() ?; } let metrics = session.get_metrics(); diff --git a/examples/cloud.rs b/examples/cloud.rs index 5859ef12ed..63265e41f8 100644 --- a/examples/cloud.rs +++ b/examples/cloud.rs @@ -12,7 +12,7 @@ async fn main() -> Result<()> { .unwrap_or("examples/config_data.yaml".to_owned()); let session = CloudSessionBuilder::new(Path::new(&config_path)) .unwrap() - .build_legacy() + .build() .await .unwrap(); diff --git a/examples/compare-tokens.rs b/examples/compare-tokens.rs index 4863608fff..946691d89e 100644 --- a/examples/compare-tokens.rs +++ b/examples/compare-tokens.rs @@ -1,7 +1,7 @@ use anyhow::Result; use scylla::routing::Token; use scylla::transport::NodeAddr; -use scylla::{LegacySession, SessionBuilder}; +use scylla::{Session, SessionBuilder}; use std::env; #[tokio::main] @@ -10,7 +10,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; @@ -51,7 +51,7 @@ async fn main() -> Result<()> { (pk,), ) .await? - .single_row_typed::<(i64,)>()?; + .single_row()?; assert_eq!(t, qt); println!("token for {}: {}", pk, t); } diff --git a/examples/cql-time-types.rs b/examples/cql-time-types.rs index 1b9e475d4b..77ddef09f4 100644 --- a/examples/cql-time-types.rs +++ b/examples/cql-time-types.rs @@ -3,10 +3,9 @@ use anyhow::Result; use chrono::{DateTime, NaiveDate, NaiveTime, Utc}; -use futures::{StreamExt, TryStreamExt}; use scylla::frame::response::result::CqlValue; use scylla::frame::value::{CqlDate, CqlTime, CqlTimestamp}; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::SessionBuilder; use std::env; @@ -16,7 +15,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; @@ -44,7 +43,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.dates", &[]) .await? - .into_typed::<(NaiveDate,)>(); + .into_typed::<(NaiveDate,)>()?; while let Some(row_result) = iter.next().await { let (read_date,): (NaiveDate,) = match row_result { Ok(read_date) => read_date, @@ -66,7 +65,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.dates", &[]) .await? - .into_typed::<(time::Date,)>(); + .into_typed::<(time::Date,)>()?; while let Some(row_result) = iter.next().await { let (read_date,): (time::Date,) = match row_result { Ok(read_date) => read_date, @@ -88,7 +87,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.dates", &[]) .await? - .into_typed::<(CqlValue,)>(); + .into_typed::<(CqlValue,)>()?; while let Some(row_result) = iter.next().await { let read_days: u32 = match row_result { Ok((CqlValue::Date(CqlDate(days)),)) => days, @@ -124,7 +123,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.times", &[]) .await? - .into_typed::<(NaiveTime,)>(); + .into_typed::<(NaiveTime,)>()?; while let Some((read_time,)) = iter.try_next().await? { println!("Parsed a time into chrono::NaiveTime: {:?}", read_time); } @@ -139,7 +138,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.times", &[]) .await? - .into_typed::<(time::Time,)>(); + .into_typed::<(time::Time,)>()?; while let Some((read_time,)) = iter.try_next().await? { println!("Parsed a time into time::Time: {:?}", read_time); } @@ -154,7 +153,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.times", &[]) .await? - .into_typed::<(CqlTime,)>(); + .into_typed::<(CqlTime,)>()?; while let Some((read_time,)) = iter.try_next().await? { println!("Read a time as raw nanos: {:?}", read_time); } @@ -185,7 +184,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.timestamps", &[]) .await? - .into_typed::<(DateTime,)>(); + .into_typed::<(DateTime,)>()?; while let Some((read_time,)) = iter.try_next().await? { println!( "Parsed a timestamp into chrono::DateTime: {:?}", @@ -206,7 +205,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.timestamps", &[]) .await? - .into_typed::<(time::OffsetDateTime,)>(); + .into_typed::<(time::OffsetDateTime,)>()?; while let Some((read_time,)) = iter.try_next().await? { println!( "Parsed a timestamp into time::OffsetDateTime: {:?}", @@ -227,7 +226,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT d from examples_ks.timestamps", &[]) .await? - .into_typed::<(CqlTimestamp,)>(); + .into_typed::<(CqlTimestamp,)>()?; while let Some((read_time,)) = iter.try_next().await? { println!("Read a timestamp as raw millis: {:?}", read_time); } diff --git a/examples/cqlsh-rs.rs b/examples/cqlsh-rs.rs index 5473fa740d..080b6fe150 100644 --- a/examples/cqlsh-rs.rs +++ b/examples/cqlsh-rs.rs @@ -3,8 +3,10 @@ use rustyline::completion::{Completer, Pair}; use rustyline::error::ReadlineError; use rustyline::{CompletionType, Config, Context, Editor}; use rustyline_derive::{Helper, Highlighter, Hinter, Validator}; +use scylla::transport::session::Session; use scylla::transport::Compression; -use scylla::{LegacySession, LegacyQueryResult, SessionBuilder}; +use scylla::{QueryResult, SessionBuilder}; +use scylla_cql::frame::response::result::Row; use std::env; #[derive(Helper, Highlighter, Validator, Hinter)] @@ -173,12 +175,13 @@ impl Completer for CqlHelper { } } -fn print_result(result: &LegacyQueryResult) { - if result.rows.is_none() { +fn print_result(result: &QueryResult) { + if !result.is_rows() { println!("OK"); return; } - for row in result.rows.as_ref().unwrap() { + for row in result.rows::().unwrap() { + let row = row.unwrap(); for column in &row.columns { print!("|"); print!( @@ -199,10 +202,10 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new() + let session: Session = SessionBuilder::new() .known_node(uri) .compression(Some(Compression::Lz4)) - .build_legacy() + .build() .await?; let config = Config::builder() diff --git a/examples/custom_deserialization.rs b/examples/custom_deserialization.rs index 7bd694c811..66bc4ad800 100644 --- a/examples/custom_deserialization.rs +++ b/examples/custom_deserialization.rs @@ -2,7 +2,8 @@ use anyhow::Result; use scylla::cql_to_rust::{FromCqlVal, FromCqlValError}; use scylla::frame::response::result::CqlValue; use scylla::macros::impl_from_cql_value_from_method; -use scylla::{LegacySession, SessionBuilder}; +use scylla::transport::session::Session; +use scylla::SessionBuilder; use std::env; #[tokio::main] @@ -11,7 +12,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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 @@ -46,6 +47,7 @@ async fn main() -> Result<()> { (), ) .await? + .into_legacy_result()? .single_row_typed::<(MyType,)>()?; assert_eq!(v, MyType("asdf".to_owned())); @@ -73,6 +75,7 @@ async fn main() -> Result<()> { (), ) .await? + .into_legacy_result()? .single_row_typed::<(MyOtherType,)>()?; assert_eq!(v, MyOtherType("asdf".to_owned())); diff --git a/examples/custom_load_balancing_policy.rs b/examples/custom_load_balancing_policy.rs index e70ed02134..5c279f2331 100644 --- a/examples/custom_load_balancing_policy.rs +++ b/examples/custom_load_balancing_policy.rs @@ -6,7 +6,7 @@ use scylla::{ load_balancing::{LoadBalancingPolicy, RoutingInfo}, routing::Shard, transport::{ClusterData, ExecutionProfile}, - LegacySession, SessionBuilder, + Session, SessionBuilder, }; use std::{env, sync::Arc}; @@ -68,10 +68,10 @@ async fn main() -> Result<()> { .load_balancing_policy(Arc::new(custom_load_balancing)) .build(); - let _session: LegacySession = SessionBuilder::new() + let _session: Session = SessionBuilder::new() .known_node(uri) .default_execution_profile_handle(profile.into_handle()) - .build_legacy() + .build() .await?; Ok(()) diff --git a/examples/execution_profile.rs b/examples/execution_profile.rs index e3d05af59f..b912c2780c 100644 --- a/examples/execution_profile.rs +++ b/examples/execution_profile.rs @@ -4,7 +4,7 @@ use scylla::query::Query; use scylla::retry_policy::{DefaultRetryPolicy, FallthroughRetryPolicy}; use scylla::speculative_execution::PercentileSpeculativeExecutionPolicy; use scylla::statement::{Consistency, SerialConsistency}; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::transport::ExecutionProfile; use scylla::{SessionBuilder, SessionConfig}; use std::env; @@ -42,22 +42,22 @@ async fn main() -> Result<()> { let mut handle2 = profile2.into_handle(); // It is even possible to use multiple sessions interleaved, having them configured with different profiles. - let session1: LegacySession = SessionBuilder::new() + let session1: Session = SessionBuilder::new() .known_node(&uri) .default_execution_profile_handle(handle1.clone()) - .build_legacy() + .build() .await?; - let session2: LegacySession = SessionBuilder::new() + let session2: Session = SessionBuilder::new() .known_node(&uri) .default_execution_profile_handle(handle2.clone()) - .build_legacy() + .build() .await?; // As default execution profile is not provided explicitly, session 3 uses a predefined one. let mut session_3_config = SessionConfig::new(); session_3_config.add_known_node(uri); - let session3: LegacySession = LegacySession::connect(session_3_config).await?; + let session3: Session = Session::connect(session_3_config).await?; session1.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; diff --git a/examples/get_by_name.rs b/examples/get_by_name.rs index a0a21b8556..e80705661c 100644 --- a/examples/get_by_name.rs +++ b/examples/get_by_name.rs @@ -1,6 +1,7 @@ use anyhow::{anyhow, Result}; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::SessionBuilder; +use scylla_cql::frame::response::result::Row; use std::env; #[tokio::main] @@ -10,7 +11,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; @@ -38,15 +39,23 @@ async fn main() -> Result<()> { let query_result = session .query_unpaged("SELECT pk, ck, value FROM examples_ks.get_by_name", &[]) .await?; - let (ck_idx, _) = query_result - .get_column_spec("ck") + let col_specs = query_result + .column_specs() + .ok_or_else(|| anyhow!("Response is not of Rows type"))?; + let (ck_idx, _) = col_specs + .get_by_name("ck") .ok_or_else(|| anyhow!("No ck column found"))?; - let (value_idx, _) = query_result - .get_column_spec("value") + let (value_idx, _) = col_specs + .get_by_name("value") .ok_or_else(|| anyhow!("No value column found"))?; + let rows = query_result + .rows::() + .unwrap() + .collect::, _>>() + .unwrap(); println!("ck | value"); println!("---------------------"); - for row in query_result.rows.ok_or_else(|| anyhow!("no rows found"))? { + for row in rows { println!("{:?} | {:?}", row.columns[ck_idx], row.columns[value_idx]); } diff --git a/examples/logging.rs b/examples/logging.rs index 37e534b8c2..6b090acbcb 100644 --- a/examples/logging.rs +++ b/examples/logging.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::SessionBuilder; use std::env; use tracing::info; @@ -16,7 +16,7 @@ async fn main() -> Result<()> { let uri = env::var("SCYLLA_URI").unwrap_or_else(|_| "127.0.0.1:9042".to_string()); info!("Connecting to {}", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; diff --git a/examples/logging_log.rs b/examples/logging_log.rs index a1f962419c..19465018cc 100644 --- a/examples/logging_log.rs +++ b/examples/logging_log.rs @@ -1,6 +1,5 @@ use anyhow::Result; -use scylla::transport::session::LegacySession; -use scylla::SessionBuilder; +use scylla::{Session, SessionBuilder}; use std::env; use tracing::info; @@ -18,7 +17,7 @@ async fn main() -> Result<()> { let uri = env::var("SCYLLA_URI").unwrap_or_else(|_| "127.0.0.1:9042".to_string()); info!("Connecting to {}", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; diff --git a/examples/parallel-prepared.rs b/examples/parallel-prepared.rs index 531f6d7b4d..167b583944 100644 --- a/examples/parallel-prepared.rs +++ b/examples/parallel-prepared.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use scylla::{LegacySession, SessionBuilder}; +use scylla::{Session, SessionBuilder}; use std::env; use std::sync::Arc; @@ -11,7 +11,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + let session: Session = SessionBuilder::new().known_node(uri).build().await?; let session = Arc::new(session); session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; diff --git a/examples/parallel.rs b/examples/parallel.rs index 5e3f119fbb..716225fb77 100644 --- a/examples/parallel.rs +++ b/examples/parallel.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use scylla::{LegacySession, SessionBuilder}; +use scylla::{Session, SessionBuilder}; use std::env; use std::sync::Arc; @@ -11,7 +11,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + let session: Session = SessionBuilder::new().known_node(uri).build().await?; let session = Arc::new(session); session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; diff --git a/examples/query_history.rs b/examples/query_history.rs index 710f9616d9..826e10bd09 100644 --- a/examples/query_history.rs +++ b/examples/query_history.rs @@ -1,10 +1,9 @@ //! This example shows how to collect history of query execution. use anyhow::Result; -use futures::StreamExt; use scylla::history::{HistoryCollector, StructuredHistory}; use scylla::query::Query; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::SessionBuilder; use std::env; use std::sync::Arc; @@ -15,7 +14,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; diff --git a/examples/schema_agreement.rs b/examples/schema_agreement.rs index 9b9369ac93..3b7a41ed8a 100644 --- a/examples/schema_agreement.rs +++ b/examples/schema_agreement.rs @@ -1,7 +1,6 @@ use anyhow::{bail, Result}; -use futures::TryStreamExt; use scylla::transport::errors::QueryError; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::SessionBuilder; use std::env; use std::time::Duration; @@ -13,10 +12,10 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new() + let session: Session = SessionBuilder::new() .known_node(uri) .schema_agreement_interval(Duration::from_secs(1)) // check every second for schema agreement if not agreed first check - .build_legacy() + .build() .await?; let schema_version = session.await_schema_agreement().await?; @@ -70,7 +69,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT a, b, c FROM examples_ks.schema_agreement", &[]) .await? - .into_typed::<(i32, i32, String)>(); + .into_typed::<(i32, i32, String)>()?; while let Some((a, b, c)) = iter.try_next().await? { println!("a, b, c: {}, {}, {}", a, b, c); } diff --git a/examples/select-paging.rs b/examples/select-paging.rs index f9027675a0..5ab61c7f92 100644 --- a/examples/select-paging.rs +++ b/examples/select-paging.rs @@ -1,7 +1,6 @@ use anyhow::Result; -use futures::stream::StreamExt; use scylla::statement::PagingState; -use scylla::{query::Query, LegacySession, SessionBuilder}; +use scylla::{query::Query, Session, SessionBuilder}; use std::env; use std::ops::ControlFlow; @@ -11,7 +10,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; @@ -35,7 +34,7 @@ async fn main() -> Result<()> { let mut rows_stream = session .query_iter("SELECT a, b, c FROM examples_ks.select_paging", &[]) .await? - .into_typed::<(i32, i32, String)>(); + .into_typed::<(i32, i32, String)>()?; while let Some(next_row_res) = rows_stream.next().await { let (a, b, c) = next_row_res?; @@ -54,7 +53,7 @@ async fn main() -> Result<()> { println!( "Paging state: {:#?} ({} rows)", paging_state_response, - res.rows_num()?, + res.rows_num().expect("Got non-Rows response!"), ); match paging_state_response.into_paging_control_flow() { @@ -84,7 +83,7 @@ async fn main() -> Result<()> { println!( "Paging state from the prepared statement execution: {:#?} ({} rows)", paging_state_response, - res.rows_num()?, + res.rows_num().expect("Got non-Rows response!"), ); match paging_state_response.into_paging_control_flow() { diff --git a/examples/speculative-execution.rs b/examples/speculative-execution.rs index c53285cac6..e6c64e3ad7 100644 --- a/examples/speculative-execution.rs +++ b/examples/speculative-execution.rs @@ -1,6 +1,6 @@ use scylla::{ speculative_execution::PercentileSpeculativeExecutionPolicy, - transport::execution_profile::ExecutionProfile, LegacySession, SessionBuilder, + transport::execution_profile::ExecutionProfile, Session, SessionBuilder, }; use anyhow::Result; @@ -20,10 +20,10 @@ async fn main() -> Result<()> { .speculative_execution_policy(Some(Arc::new(speculative))) .build(); - let session: LegacySession = SessionBuilder::new() + let session: Session = SessionBuilder::new() .known_node(uri) .default_execution_profile_handle(speculative_profile.into_handle()) - .build_legacy() + .build() .await?; session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; diff --git a/examples/tls.rs b/examples/tls.rs index 1bb354e569..3cb22b2493 100644 --- a/examples/tls.rs +++ b/examples/tls.rs @@ -1,6 +1,5 @@ use anyhow::Result; -use futures::TryStreamExt; -use scylla::transport::session::LegacySession; +use scylla::transport::session::Session; use scylla::SessionBuilder; use std::env; use std::fs; @@ -44,10 +43,10 @@ async fn main() -> Result<()> { context_builder.set_ca_file(ca_dir.as_path())?; context_builder.set_verify(SslVerifyMode::PEER); - let session: LegacySession = SessionBuilder::new() + let session: Session = SessionBuilder::new() .known_node(uri) .ssl_context(Some(context_builder.build())) - .build_legacy() + .build() .await?; session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; @@ -90,7 +89,7 @@ async fn main() -> Result<()> { let mut iter = session .query_iter("SELECT a, b, c FROM examples_ks.tls", &[]) .await? - .into_typed::<(i32, i32, String)>(); + .into_typed::<(i32, i32, String)>()?; while let Some((a, b, c)) = iter.try_next().await? { println!("a, b, c: {}, {}, {}", a, b, c); } diff --git a/examples/tower.rs b/examples/tower.rs index 0b6085e002..245cf478b5 100644 --- a/examples/tower.rs +++ b/examples/tower.rs @@ -1,3 +1,5 @@ +use scylla::transport::session::Session; +use scylla_cql::frame::response::result::Row; use std::env; use std::future::Future; use std::pin::Pin; @@ -7,12 +9,12 @@ use std::task::Poll; use tower::Service; struct SessionService { - session: Arc, + session: Arc, } // A trivial service implementation for sending parameterless simple string requests to Scylla. impl Service for SessionService { - type Response = scylla::LegacyQueryResult; + type Response = scylla::QueryResult; type Error = scylla::transport::errors::QueryError; type Future = Pin>>>; @@ -35,7 +37,7 @@ async fn main() -> anyhow::Result<()> { session: Arc::new( scylla::SessionBuilder::new() .known_node(uri) - .build_legacy() + .build() .await?, ), }; @@ -56,14 +58,14 @@ async fn main() -> anyhow::Result<()> { println!( "Tables:\n{}", - resp.rows()? - .into_iter() - .map(|r| format!( + resp.rows::()? + .map(|r| r.map(|r| format!( "\t{}.{}", print_text(&r.columns[0]), print_text(&r.columns[1]) - )) - .collect::>() + ))) + .collect::, _>>() + .unwrap() .join("\n") ); Ok(()) diff --git a/examples/tracing.rs b/examples/tracing.rs index 435e356c7a..f417917b14 100644 --- a/examples/tracing.rs +++ b/examples/tracing.rs @@ -2,15 +2,14 @@ // query() prepare() execute() batch() query_iter() and execute_iter() can be traced use anyhow::{anyhow, Result}; -use futures::StreamExt; use scylla::batch::Batch; use scylla::statement::{ prepared_statement::PreparedStatement, query::Query, Consistency, SerialConsistency, }; use scylla::tracing::TracingInfo; -use scylla::transport::iterator::LegacyRowIterator; -use scylla::LegacyQueryResult; -use scylla::{LegacySession, SessionBuilder}; +use scylla::transport::iterator::RawIterator; +use scylla::QueryResult; +use scylla::{Session, SessionBuilder}; use std::env; use std::num::NonZeroU32; use std::time::Duration; @@ -21,9 +20,9 @@ async fn main() -> Result<()> { let uri = env::var("SCYLLA_URI").unwrap_or_else(|_| "127.0.0.1:9042".to_string()); println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new() + let session: Session = SessionBuilder::new() .known_node(uri.as_str()) - .build_legacy() + .build() .await?; session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; @@ -42,9 +41,9 @@ async fn main() -> Result<()> { query.set_serial_consistency(Some(SerialConsistency::LocalSerial)); // QueryResult will contain a tracing_id which can be used to query tracing information - let query_result: LegacyQueryResult = session.query_unpaged(query.clone(), &[]).await?; + let query_result: QueryResult = session.query_unpaged(query.clone(), &[]).await?; let query_tracing_id: Uuid = query_result - .tracing_id + .tracing_id() .ok_or_else(|| anyhow!("Tracing id is None!"))?; // Get tracing information for this query and print it @@ -79,14 +78,14 @@ async fn main() -> Result<()> { // To trace execution of a prepared statement tracing must be enabled for it prepared.set_tracing(true); - let execute_result: LegacyQueryResult = session.execute_unpaged(&prepared, &[]).await?; - println!("Execute tracing id: {:?}", execute_result.tracing_id); + let execute_result: QueryResult = session.execute_unpaged(&prepared, &[]).await?; + println!("Execute tracing id: {:?}", execute_result.tracing_id()); // PAGED QUERY_ITER EXECUTE_ITER // It's also possible to trace paged queries like query_iter or execute_iter // After iterating through all rows iterator.get_tracing_ids() will give tracing ids // for all page queries - let mut row_iterator: LegacyRowIterator = session.query_iter(query, &[]).await?; + let mut row_iterator: RawIterator = session.query_iter(query, &[]).await?; while let Some(_row) = row_iterator.next().await { // Receive rows @@ -95,7 +94,7 @@ async fn main() -> Result<()> { // Now print tracing ids for all page queries: println!( "Paged row iterator tracing ids: {:?}\n", - row_iterator.get_tracing_ids() + row_iterator.tracing_ids() ); // BATCH @@ -105,19 +104,19 @@ async fn main() -> Result<()> { batch.set_tracing(true); // Run the batch and print its tracing_id - let batch_result: LegacyQueryResult = session.batch(&batch, ((),)).await?; - println!("Batch tracing id: {:?}\n", batch_result.tracing_id); + let batch_result: QueryResult = session.batch(&batch, ((),)).await?; + println!("Batch tracing id: {:?}\n", batch_result.tracing_id()); // CUSTOM // Session configuration allows specifying custom settings for querying tracing info. // Tracing info might not immediately be available on queried node // so the driver performs a few attempts with sleeps in between. - let session: LegacySession = SessionBuilder::new() + let session: Session = SessionBuilder::new() .known_node(uri) .tracing_info_fetch_attempts(NonZeroU32::new(8).unwrap()) .tracing_info_fetch_interval(Duration::from_millis(100)) .tracing_info_fetch_consistency(Consistency::One) - .build_legacy() + .build() .await?; let _custom_info: TracingInfo = session.get_tracing_info(&query_tracing_id).await?; diff --git a/examples/user-defined-type.rs b/examples/user-defined-type.rs index 9e01586a7a..719a7d8d63 100644 --- a/examples/user-defined-type.rs +++ b/examples/user-defined-type.rs @@ -1,7 +1,6 @@ use anyhow::Result; -use futures::TryStreamExt; -use scylla::macros::FromUserType; -use scylla::{LegacySession, SerializeValue, SessionBuilder}; +use scylla::macros::DeserializeValue; +use scylla::{SerializeValue, Session, SessionBuilder}; use std::env; #[tokio::main] @@ -10,7 +9,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + 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?; @@ -30,7 +29,7 @@ async fn main() -> Result<()> { // Define custom struct that matches User Defined Type created earlier // wrapping field in Option will gracefully handle null field values - #[derive(Debug, FromUserType, SerializeValue)] + #[derive(Debug, DeserializeValue, SerializeValue)] struct MyType { int_val: i32, text_val: Option, @@ -56,7 +55,7 @@ async fn main() -> Result<()> { &[], ) .await? - .into_typed::<(MyType,)>(); + .into_typed::<(MyType,)>()?; while let Some((my_val,)) = iter.try_next().await? { println!("{:?}", my_val); } diff --git a/examples/value_list.rs b/examples/value_list.rs index ce997b70e2..59c556eab1 100644 --- a/examples/value_list.rs +++ b/examples/value_list.rs @@ -1,5 +1,6 @@ use anyhow::Result; -use scylla::{LegacySession, SessionBuilder}; +use futures::StreamExt; +use scylla::{Session, SessionBuilder}; use std::env; #[tokio::main] @@ -8,7 +9,7 @@ async fn main() -> Result<()> { println!("Connecting to {} ...", uri); - let session: LegacySession = SessionBuilder::new().known_node(uri).build_legacy().await?; + let session: Session = SessionBuilder::new().known_node(uri).build().await.unwrap(); session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?; @@ -56,11 +57,14 @@ async fn main() -> Result<()> { ) .await?; - let q = session - .query_unpaged("SELECT * FROM examples_ks.my_type", &[]) - .await?; + let iter = session + .query_iter("SELECT * FROM examples_ks.my_type", &[]) + .await? + .into_typed::<(i32, String)>()? + .into_stream(); - println!("Q: {:?}", q.rows); + let rows = iter.collect::>().await; + println!("Q: {:?}", rows); Ok(()) }