Struct scylla::statement::prepared_statement::PreparedStatement
source · 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 perSession::query_unpaged
. On the other hand, the cost ofSession::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:
- bound values serialization errors - since
PreparedMetadata
is not updated - result deserialization errors - when
PreparedStatement::set_use_cached_result_metadata
is enabled, sinceResultMetadata
is not updated
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
impl PreparedStatement
pub fn get_id(&self) -> &Bytes
pub fn get_statement(&self) -> &str
sourcepub fn set_page_size(&mut self, page_size: i32)
pub fn set_page_size(&mut self, page_size: i32)
Sets the page size for this CQL query.
Panics if given number is nonpositive.
sourcepub fn get_page_size(&self) -> i32
pub fn get_page_size(&self) -> i32
Returns the page size for this CQL query.
sourcepub fn get_prepare_tracing_ids(&self) -> &[Uuid]
pub fn get_prepare_tracing_ids(&self) -> &[Uuid]
Gets tracing ids of queries used to prepare this statement
sourcepub fn is_token_aware(&self) -> bool
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.
sourcepub fn is_confirmed_lwt(&self) -> bool
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.
sourcepub fn compute_partition_key(
&self,
bound_values: &impl SerializeRow,
) -> Result<Bytes, PartitionKeyError>
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().
sourcepub fn calculate_token(
&self,
values: &impl SerializeRow,
) -> Result<Option<Token>, QueryError>
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.
sourcepub fn get_table_spec(&self) -> Option<&TableSpec<'_>>
pub fn get_table_spec(&self) -> Option<&TableSpec<'_>>
Return keyspace name and table name this statement is operating on.
sourcepub fn get_keyspace_name(&self) -> Option<&str>
pub fn get_keyspace_name(&self) -> Option<&str>
Returns the name of the keyspace this statement is operating on.
sourcepub fn get_table_name(&self) -> Option<&str>
pub fn get_table_name(&self) -> Option<&str>
Returns the name of the table this statement is operating on.
sourcepub fn set_consistency(&mut self, c: Consistency)
pub fn set_consistency(&mut self, c: Consistency)
Sets the consistency to be used when executing this statement.
sourcepub fn get_consistency(&self) -> Option<Consistency>
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.
sourcepub fn set_serial_consistency(&mut self, sc: Option<SerialConsistency>)
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)
sourcepub fn get_serial_consistency(&self) -> Option<SerialConsistency>
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)
sourcepub fn set_is_idempotent(&mut self, is_idempotent: bool)
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
sourcepub fn get_is_idempotent(&self) -> bool
pub fn get_is_idempotent(&self) -> bool
Gets the idempotence of this statement
sourcepub fn set_tracing(&mut self, should_trace: bool)
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
sourcepub fn get_tracing(&self) -> bool
pub fn get_tracing(&self) -> bool
Gets whether tracing is enabled for this statement
sourcepub fn set_use_cached_result_metadata(&mut self, use_cached_metadata: bool)
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.
sourcepub fn get_use_cached_result_metadata(&self) -> bool
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.
sourcepub fn set_timestamp(&mut self, timestamp: Option<i64>)
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
sourcepub fn get_timestamp(&self) -> Option<i64>
pub fn get_timestamp(&self) -> Option<i64>
Gets the default timestamp for this statement in microseconds.
sourcepub fn set_request_timeout(&mut self, timeout: Option<Duration>)
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.
sourcepub fn get_request_timeout(&self) -> Option<Duration>
pub fn get_request_timeout(&self) -> Option<Duration>
Gets client timeout associated with this query
sourcepub fn get_variable_col_specs(&self) -> &[ColumnSpec<'static>]
pub fn get_variable_col_specs(&self) -> &[ColumnSpec<'static>]
Access column specifications of the bind variables of this statement
sourcepub fn get_variable_pk_indexes(&self) -> &[PartitionKeyIndex]
pub fn get_variable_pk_indexes(&self) -> &[PartitionKeyIndex]
Access info about partition key indexes of the bind variables of this statement
sourcepub fn get_result_set_col_specs(&self) -> &[ColumnSpec<'static>]
pub fn get_result_set_col_specs(&self) -> &[ColumnSpec<'static>]
Access column specifications of the result set returned after the execution of this statement
sourcepub fn set_retry_policy(&mut self, retry_policy: Option<Arc<dyn RetryPolicy>>)
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.
sourcepub fn get_retry_policy(&self) -> Option<&Arc<dyn RetryPolicy>>
pub fn get_retry_policy(&self) -> Option<&Arc<dyn RetryPolicy>>
Get the retry policy set for the statement.
sourcepub fn set_history_listener(
&mut self,
history_listener: Arc<dyn HistoryListener>,
)
pub fn set_history_listener( &mut self, history_listener: Arc<dyn HistoryListener>, )
Sets the listener capable of listening what happens during query execution.
sourcepub fn remove_history_listener(&mut self) -> Option<Arc<dyn HistoryListener>>
pub fn remove_history_listener(&mut self) -> Option<Arc<dyn HistoryListener>>
Removes the listener set by set_history_listener
.
sourcepub fn set_execution_profile_handle(
&mut self,
profile_handle: Option<ExecutionProfileHandle>,
)
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.
sourcepub fn get_execution_profile_handle(&self) -> Option<&ExecutionProfileHandle>
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
impl Clone for PreparedStatement
source§impl Debug for PreparedStatement
impl Debug for PreparedStatement
source§impl From<PreparedStatement> for BatchStatement
impl From<PreparedStatement> for BatchStatement
source§fn from(p: PreparedStatement) -> Self
fn from(p: PreparedStatement) -> Self
Auto Trait Implementations§
impl !Freeze for PreparedStatement
impl !RefUnwindSafe for PreparedStatement
impl Send for PreparedStatement
impl Sync for PreparedStatement
impl Unpin for PreparedStatement
impl !UnwindSafe for PreparedStatement
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§default unsafe fn clone_to_uninit(&self, dst: *mut T)
default unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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