Skip to main content

scylla/
lib.rs

1//! Async Rust driver for the [ScyllaDB](https://scylladb.com) database written in Rust.
2//! Although optimized for ScyllaDB, the driver is also compatible with [Apache Cassandra®](https://cassandra.apache.org/).
3//!
4//! # Documentation book
5//! The best source to learn about this driver is the [documentation book](https://rust-driver.docs.scylladb.com/).\
6//! This page contains mainly API documentation.
7//!
8//! # Other documentation
9//! * [Documentation book](https://rust-driver.docs.scylladb.com/)
10//! * [Examples](https://github.com/scylladb/scylla-rust-driver/tree/main/examples)
11//! * [ScyllaDB documentation](https://docs.scylladb.com)
12//! * [Cassandra® documentation](https://cassandra.apache.org/doc/latest/)
13//!
14//! # Driver overview
15//! ### Connecting
16//! All driver activity revolves around the [Session](crate::client::session::Session).\
17//! `Session` is created by specifying a few known nodes and connecting to them:
18//!
19//! ```rust,no_run
20//! use scylla::client::session::Session;
21//! use scylla::client::session_builder::SessionBuilder;
22//! use std::error::Error;
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), Box<dyn Error>> {
26//!    let session: Session = SessionBuilder::new()
27//!         .known_node("127.0.0.1:9042")
28//!         .known_node("1.2.3.4:9876")
29//!         .build()
30//!         .await?;
31//!
32//!    Ok(())
33//! }
34//! ```
35//! `Session` is usually created using the [SessionBuilder](crate::client::session_builder::SessionBuilder).\
36//! All configuration options for a `Session` can be specified while building.
37//!
38//! ### Making queries
39//! After successfully connecting to the cluster we can make queries.\
40//! The driver supports multiple query types:
41//! * [Simple](crate::client::session::Session::query_unpaged)
42//! * [Simple paged](crate::client::session::Session::query_iter)
43//! * [Prepared](crate::client::session::Session::execute_unpaged) (need to be [prepared](crate::client::session::Session::prepare) before use)
44//! * [Prepared paged](crate::client::session::Session::execute_iter)
45//! * [Batch](crate::client::session::Session::batch)
46//!
47//! To specify options for a single query, create the corresponding object and configure it:
48//! * For simple: [`Statement`](crate::statement::unprepared::Statement)
49//! * For prepared: [`PreparedStatement`](crate::statement::prepared::PreparedStatement)
50//! * For batch: [`Batch`](crate::statement::batch::Batch)
51//!
52//! The easiest way to specify bound values in a query is using a tuple:
53//! ```rust
54//! # use scylla::client::session::Session;
55//! # use std::error::Error;
56//! # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
57//! // Insert an int and text into the table
58//! session
59//!     .query_unpaged(
60//!         "INSERT INTO ks.tab (a, b) VALUES(?, ?)",
61//!         (2_i32, "some text")
62//!     )
63//!     .await?;
64//! # Ok(())
65//! # }
66//! ```
67//! But the driver will accept anything implementing the trait [SerializeRow].
68//!
69//! ### Receiving results
70//! The easiest way to read rows returned by a query is to cast each row to a tuple of values:
71//!
72//! ```rust
73//! # use scylla::client::session::Session;
74//! # use std::error::Error;
75//! # async fn check_only_compiles(session: &Session) -> Result<(), Box<dyn Error>> {
76//!
77//! // Read rows containing an int and text.
78//! // Keep in mind that all results come in one response (no paging is done!),
79//! // so the memory footprint and latency may be huge!
80//! // To prevent that, use `Session::query_iter` or `Session::query_single_page`.
81//! let query_rows = session
82//!     .query_unpaged("SELECT a, b FROM ks.tab", &[])
83//!     .await?
84//!     .into_rows_result()?;
85//!
86//! for row in query_rows.rows()? {
87//!     // Parse row as int and text \
88//!     let (int_val, text_val): (i32, &str) = row?;
89//! }
90//! # Ok(())
91//! # }
92//! ```
93//! See the [book](https://rust-driver.docs.scylladb.com/stable/statements/result.html) for more receiving methods.
94//!
95//! # Feature flags
96//! The driver has several optional features that can be enabled or disabled in `Cargo.toml`.
97//! Refer to [scylla/Cargo.toml](https://docs.rs/crate/scylla/latest/source/Cargo.toml.orig)
98//! for the list of available features and their descriptions.
99
100#![cfg_attr(docsrs, feature(doc_cfg))]
101
102#[doc(hidden)]
103pub mod _macro_internal {
104    pub use scylla_cql::_macro_internal::*;
105}
106
107pub use scylla_cql::{DeserializeRow, DeserializeValue, SerializeRow, SerializeValue};
108
109pub mod value {
110    //! Defines CQL values of various types and their representations,
111    //! as well as conversion between them and other types.
112
113    // Every `pub` item is re-exported here, apart from `deser_cql_value`.
114    pub use scylla_cql::value::{
115        Counter, CqlDate, CqlDecimal, CqlDecimalBorrowed, CqlDuration, CqlTime, CqlTimestamp,
116        CqlTimeuuid, CqlValue, CqlVarint, CqlVarintBorrowed, Emptiable, MaybeEmpty, MaybeUnset,
117        Row, Unset, ValueOverflow,
118    };
119}
120
121pub mod frame {
122    //! Abstractions of the CQL wire protocol.
123
124    pub use scylla_cql::frame::{Authenticator, Compression, frame_errors};
125    pub(crate) use scylla_cql::frame::{
126        FrameParams, SerializedRequest, parse_response_body_extensions, protocol_features,
127        read_response_frame, request, server_event_type,
128    };
129
130    pub mod types {
131        //! CQL binary protocol in-wire types.
132
133        pub use scylla_cql::frame::types::{Consistency, SerialConsistency};
134    }
135
136    pub mod response {
137        //! CQL responses sent by the server.
138
139        pub(crate) use scylla_cql::frame::response::*;
140
141        pub mod result {
142            //! CQL protocol-level representation of a `RESULT` response.
143            //!
144            //! Contains lower-level types that are used to represent the result of a query.
145
146            #[cfg(all(scylla_unstable, feature = "unstable-cpp-rs"))]
147            pub use scylla_cql::frame::response::result::DeserializedMetadataAndRawRows;
148
149            pub(crate) use scylla_cql::frame::response::result::*;
150            pub use scylla_cql::frame::response::result::{
151                CollectionType, ColumnSpec, ColumnType, NativeType, PartitionKeyIndex, TableSpec,
152                UserDefinedType,
153            };
154        }
155    }
156}
157
158/// Serializing bound values of a query to be sent to the DB.
159// Note: When editing comment on submodules here edit corresponding comments
160// on scylla-cql modules too.
161pub mod serialize {
162    pub use scylla_cql::serialize::SerializationError;
163    /// Contains the [BatchValues][batch::BatchValues] and [BatchValuesIterator][batch::BatchValuesIterator] trait and their
164    /// implementations.
165    pub mod batch {
166        // Main types
167        pub use scylla_cql::serialize::batch::{
168            BatchValues, BatchValuesFromIterator, BatchValuesIterator,
169            BatchValuesIteratorFromIterator, TupleValuesIter,
170        };
171    }
172
173    /// Contains the [SerializeRow][row::SerializeRow] trait and its implementations.
174    pub mod row {
175        // Main types
176        pub use scylla_cql::serialize::row::{RowSerializationContext, SerializeRow};
177
178        // Errors
179        pub use scylla_cql::serialize::row::{
180            BuiltinSerializationError, BuiltinSerializationErrorKind, BuiltinTypeCheckError,
181            BuiltinTypeCheckErrorKind,
182        };
183    }
184
185    /// Contains the [SerializeValue][value::SerializeValue] trait and its implementations.
186    pub mod value {
187        // Main types
188        pub use scylla_cql::serialize::value::SerializeValue;
189
190        // Errors
191        pub use scylla_cql::serialize::value::{
192            BuiltinSerializationError, BuiltinSerializationErrorKind, BuiltinTypeCheckError,
193            BuiltinTypeCheckErrorKind, MapSerializationErrorKind, MapTypeCheckErrorKind,
194            SetOrListSerializationErrorKind, SetOrListTypeCheckErrorKind,
195            TupleSerializationErrorKind, TupleTypeCheckErrorKind, UdtSerializationErrorKind,
196            UdtTypeCheckErrorKind,
197        };
198    }
199
200    /// Contains types and traits used for safe serialization of values for a CQL statement.
201    pub mod writers {
202        pub use scylla_cql::serialize::writers::{
203            CellOverflowError, CellValueBuilder, CellWriter, RowWriter, WrittenCellProof,
204        };
205    }
206}
207
208pub mod deserialize {
209    #![doc = include_str!("deserialize/README.md")]
210
211    pub use scylla_cql::deserialize::{DeserializationError, FrameSlice, TypeCheckError};
212
213    /// Deserializing the whole query result contents.
214    pub mod result {
215        pub use scylla_cql::deserialize::result::TypedRowIterator;
216    }
217
218    /// Deserializing a row of the query result.
219    pub mod row {
220        pub use scylla_cql::deserialize::row::{
221            BuiltinDeserializationError, BuiltinDeserializationErrorKind, BuiltinTypeCheckError,
222            BuiltinTypeCheckErrorKind, ColumnIterator, DeserializeRow, RawColumn,
223        };
224    }
225
226    /// Deserializing a single CQL value from a column of the query result row.
227    pub mod value {
228        pub use scylla_cql::deserialize::value::{
229            BuiltinDeserializationError, BuiltinDeserializationErrorKind, BuiltinTypeCheckError,
230            BuiltinTypeCheckErrorKind, DeserializeValue, ListlikeIterator,
231            MapDeserializationErrorKind, MapIterator, MapTypeCheckErrorKind,
232            SetOrListDeserializationErrorKind, SetOrListTypeCheckErrorKind,
233            TupleDeserializationErrorKind, TupleTypeCheckErrorKind, UdtIterator,
234            UdtTypeCheckErrorKind,
235        };
236
237        // Note: deprecated doesn't work on re-exports, users won't get the warning.
238        // Added it anyway for documentation purposes.
239        // TODO(2.0): Remove those re-exports.
240        #[deprecated(since = "1.5.0", note = "Moved to `scylla::value` module")]
241        pub use scylla_cql::deserialize::value::{Emptiable, MaybeEmpty};
242    }
243
244    // Shorthands for better readability.
245    pub(crate) trait DeserializeOwnedRow:
246        for<'frame, 'metadata> row::DeserializeRow<'frame, 'metadata>
247    {
248    }
249    impl<T> DeserializeOwnedRow for T where
250        T: for<'frame, 'metadata> row::DeserializeRow<'frame, 'metadata>
251    {
252    }
253}
254
255pub mod authentication;
256pub mod client;
257
258pub mod cluster;
259pub mod errors;
260mod network;
261pub mod observability;
262pub mod policies;
263pub mod response;
264pub mod routing;
265pub mod statement;
266
267pub(crate) mod utils;
268
269#[cfg(test)]
270pub(crate) use utils::test_utils;
271
272#[cfg(doctest)]
273mod book_tests;
274
275#[cfg(all(scylla_unstable, feature = "unstable-testing"))]
276#[doc(hidden)]
277pub mod internal_testing {
278    use scylla_cql::serialize::row::SerializedValues;
279
280    use crate::routing::Token;
281    use crate::routing::partitioner::PartitionerName;
282    use crate::statement::prepared::TokenCalculationError;
283
284    pub fn calculate_token_for_partition_key(
285        serialized_partition_key_values: &SerializedValues,
286        partitioner: &PartitionerName,
287    ) -> Result<Token, TokenCalculationError> {
288        crate::routing::partitioner::calculate_token_for_partition_key(
289            serialized_partition_key_values,
290            partitioner,
291        )
292    }
293}