pub struct PreparedStatement {
    pub prepare_tracing_ids: Vec<Uuid>,
    /* private fields */
}
Expand description

Represents a statement prepared on the server.

To prepare a statement, simply execute Session::prepare.

If you plan on reusing the statement, or bounding some values to it during execution, always prefer using prepared statements over Session::query_* methods, e.g. Session::query_unpaged.

Benefits that prepared statements have to offer:

  • Performance - a prepared statement holds information about metadata that allows to carry out a statement execution in a type safe manner. When any of Session::query_* methods is called with non-empty bound values, the driver has to prepare the statement before execution (to provide type safety). This implies 2 round trips per Session::query_unpaged. On the other hand, the cost of Session::execute_unpaged is only 1 round trip.
  • Increased type-safety - bound values’ types are validated with the PreparedMetadata received from the server during the serialization.
  • Improved load balancing - thanks to statement metadata, the driver is able to compute a set of destined replicas for the statement execution. These replicas will be preferred when choosing the node (and shard) to send the request to.
  • Result deserialization optimization - see PreparedStatement::set_use_cached_result_metadata.

§Clone implementation

Cloning a prepared statement is a cheap operation. It only requires copying a couple of small fields and some Arc pointers. Always prefer cloning over executing Session::prepare multiple times to save some roundtrips.

§Statement repreparation

When schema is updated, the server is supposed to invalidate its prepared statement caches. Then, if client tries to execute a given statement, the server will respond with an error. Users should not worry about it, since the driver handles it properly and tries to reprepare the statement. However, there are some cases when client-side prepared statement should be dropped and prepared once again via Session::prepare - see the mention about altering schema below.

§Altering schema

If for some reason you decided to alter the part of schema that corresponds to given prepared statement, then the corresponding statement (and its copies obtained via PreparedStatement::clone) should be dropped. The statement should be prepared again.

There are two reasons for this:

§CQL v4 protocol limitations

The driver only supports CQL version 4.

In multi-client scenario, only the first client which reprepares the statement will receive the updated metadata from the server. The rest of the clients will still hold on the outdated metadata. In version 4 of CQL protocol there is currently no way for the server to notify other clients about prepared statement’s metadata update.

§Client-side metadata immutability

The decision was made to keep client-side metadata immutable. Mainly because of the CQLv4 limitations mentioned above. This means that metadata is not updated during statement repreparation. This raises two issues:

So, to mitigate those issues, drop the outdated PreparedStatement manually and prepare it again against the new schema.

Fields§

§prepare_tracing_ids: Vec<Uuid>

Implementations§

source§

impl PreparedStatement

source

pub fn get_id(&self) -> &Bytes

source

pub fn get_statement(&self) -> &str

source

pub fn set_page_size(&mut self, page_size: i32)

Sets the page size for this CQL query.

Panics if given number is nonpositive.

source

pub fn get_page_size(&self) -> i32

Returns the page size for this CQL query.

source

pub fn get_prepare_tracing_ids(&self) -> &[Uuid]

Gets tracing ids of queries used to prepare this statement

source

pub fn is_token_aware(&self) -> bool

Returns true if the prepared statement has necessary information to be routed in a token-aware manner. If false, the query will always be sent to a random node/shard.

source

pub fn is_confirmed_lwt(&self) -> bool

Returns true if it is known that the prepared statement contains a Lightweight Transaction. If so, the optimisation can be performed: the query should be routed to the replicas in a predefined order (i. e. always try first to contact replica A, then B if it fails, then C, etc.). If false, the query should be routed normally. Note: this a Scylla-specific optimisation. Therefore, the result will be always false for Cassandra.

source

pub fn compute_partition_key( &self, bound_values: &impl SerializeRow, ) -> Result<Bytes, PartitionKeyError>

Computes the partition key of the target table from given values — it assumes that all partition key columns are passed in values. Partition keys have specific serialization rules. Ref: https://github.com/scylladb/scylla/blob/40adf38915b6d8f5314c621a94d694d172360833/compound_compat.hh#L33-L47

Note: this is no longer required to compute a token. This is because partitioners are now stateful and stream-based, so they do not require materialised partition key. Therefore, for computing a token, there are more efficient methods, such as Self::calculate_token().

source

pub fn calculate_token( &self, values: &impl SerializeRow, ) -> Result<Option<Token>, QueryError>

Calculates the token for given prepared statement and values.

Returns the token that would be computed for executing the provided prepared statement with the provided values.

source

pub fn get_table_spec(&self) -> Option<&TableSpec<'_>>

Return keyspace name and table name this statement is operating on.

source

pub fn get_keyspace_name(&self) -> Option<&str>

Returns the name of the keyspace this statement is operating on.

source

pub fn get_table_name(&self) -> Option<&str>

Returns the name of the table this statement is operating on.

source

pub fn set_consistency(&mut self, c: Consistency)

Sets the consistency to be used when executing this statement.

source

pub fn get_consistency(&self) -> Option<Consistency>

Gets the consistency to be used when executing this prepared statement if it is filled. If this is empty, the default_consistency of the session will be used.

source

pub fn set_serial_consistency(&mut self, sc: Option<SerialConsistency>)

Sets the serial consistency to be used when executing this statement. (Ignored unless the statement is an LWT)

source

pub fn get_serial_consistency(&self) -> Option<SerialConsistency>

Gets the serial consistency to be used when executing this statement. (Ignored unless the statement is an LWT)

source

pub fn set_is_idempotent(&mut self, is_idempotent: bool)

Sets the idempotence of this statement A query is idempotent if it can be applied multiple times without changing the result of the initial application If set to true we can be sure that it is idempotent If set to false it is unknown whether it is idempotent This is used in RetryPolicy to decide if retrying a query is safe

source

pub fn get_is_idempotent(&self) -> bool

Gets the idempotence of this statement

source

pub fn set_tracing(&mut self, should_trace: bool)

Enable or disable CQL Tracing for this statement If enabled session.execute() will return a QueryResult containing tracing_id which can be used to query tracing information about the execution of this query

source

pub fn get_tracing(&self) -> bool

Gets whether tracing is enabled for this statement

source

pub fn set_use_cached_result_metadata(&mut self, use_cached_metadata: bool)

Make use of cached metadata to decode results of the statement’s execution.

If true, the driver will request the server not to attach the result metadata in response to the statement execution.

The driver will cache the result metadata received from the server after statement preparation and will use it to deserialize the results of statement execution.

This option is false by default.

source

pub fn get_use_cached_result_metadata(&self) -> bool

Gets the information whether the driver uses cached metadata to decode the results of the statement’s execution.

source

pub fn set_timestamp(&mut self, timestamp: Option<i64>)

Sets the default timestamp for this statement in microseconds. If not None, it will replace the server side assigned timestamp as default timestamp If a statement contains a USING TIMESTAMP clause, calling this method won’t change anything

source

pub fn get_timestamp(&self) -> Option<i64>

Gets the default timestamp for this statement in microseconds.

source

pub fn set_request_timeout(&mut self, timeout: Option<Duration>)

Sets the client-side timeout for this statement. If not None, the driver will stop waiting for the request to finish after timeout passed. Otherwise, default session client timeout will be applied.

source

pub fn get_request_timeout(&self) -> Option<Duration>

Gets client timeout associated with this query

source

pub fn get_variable_col_specs(&self) -> &[ColumnSpec<'static>]

Access column specifications of the bind variables of this statement

source

pub fn get_variable_pk_indexes(&self) -> &[PartitionKeyIndex]

Access info about partition key indexes of the bind variables of this statement

source

pub fn get_result_set_col_specs(&self) -> &[ColumnSpec<'static>]

Access column specifications of the result set returned after the execution of this statement

source

pub fn set_retry_policy(&mut self, retry_policy: Option<Arc<dyn RetryPolicy>>)

Set the retry policy for this statement, overriding the one from execution profile if not None.

source

pub fn get_retry_policy(&self) -> Option<&Arc<dyn RetryPolicy>>

Get the retry policy set for the statement.

source

pub fn set_history_listener( &mut self, history_listener: Arc<dyn HistoryListener>, )

Sets the listener capable of listening what happens during query execution.

source

pub fn remove_history_listener(&mut self) -> Option<Arc<dyn HistoryListener>>

Removes the listener set by set_history_listener.

source

pub fn set_execution_profile_handle( &mut self, profile_handle: Option<ExecutionProfileHandle>, )

Associates the query with execution profile referred by the provided handle. Handle may be later remapped to another profile, and query will reflect those changes.

source

pub fn get_execution_profile_handle(&self) -> Option<&ExecutionProfileHandle>

Borrows the execution profile handle associated with this query.

Trait Implementations§

source§

impl Clone for PreparedStatement

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PreparedStatement

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<PreparedStatement> for BatchStatement

source§

fn from(p: PreparedStatement) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

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
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> ErasedDestructor for T
where T: 'static,