Overview
The Batch struct represents a CQL batch statement that executes multiple statements atomically. A batch can contain any mix of prepared and unprepared statements.
For maximum performance, always prefer using prepared statements in batches.
Source: scylla/src/statement/batch.rs:22
Type Definition
pub struct Batch {
pub statements: Vec<BatchStatement>,
// ... internal fields
}
Batch Types
pub enum BatchType {
Logged,
Unlogged,
Counter,
}
Default. Ensures atomicity - all statements succeed or all fail. Includes performance overhead for logging.
No atomicity guarantee. Statements may partially succeed. Better performance.
Special batch type for counter updates only.
Constructors
new
Creates an empty batch of the specified type.
pub fn new(batch_type: BatchType) -> Self
New empty batch with default configuration
new_with_statements
Creates a batch with initial statements.
pub fn new_with_statements(
batch_type: BatchType,
statements: Vec<BatchStatement>
) -> Self
statements
Vec<BatchStatement>
required
Initial statements to include in the batch
Statement Management
append_statement
Adds a statement to the batch.
pub fn append_statement(&mut self, statement: impl Into<BatchStatement>)
statement
impl Into<BatchStatement>
required
Statement to append (can be &str, Statement, or PreparedStatement)
Example:
let mut batch = Batch::new(BatchType::Logged);
// Add unprepared statement
batch.append_statement("INSERT INTO users (id, name) VALUES (1, 'Alice')");
// Add prepared statement
let prepared = session.prepare("INSERT INTO users (id, name) VALUES (?, ?)").await?;
batch.append_statement(prepared);
get_type
Returns the batch type.
pub fn get_type(&self) -> BatchType
BatchStatement Enum
pub enum BatchStatement {
Query(Statement),
PreparedStatement(PreparedStatement),
}
Conversions
impl From<&str> for BatchStatement
impl From<Statement> for BatchStatement
impl From<PreparedStatement> for BatchStatement
Configuration Methods
Consistency
set_consistency
pub fn set_consistency(&mut self, c: Consistency)
Consistency level for the entire batch
unset_consistency
pub fn unset_consistency(&mut self)
get_consistency
pub fn get_consistency(&self) -> Option<Consistency>
Serial Consistency
set_serial_consistency
pub fn set_serial_consistency(&mut self, sc: Option<SerialConsistency>)
sc
Option<SerialConsistency>
required
Serial consistency for LWT operations in the batch
unset_serial_consistency
pub fn unset_serial_consistency(&mut self)
get_serial_consistency
pub fn get_serial_consistency(&self) -> Option<SerialConsistency>
Idempotence
set_is_idempotent
pub fn set_is_idempotent(&mut self, is_idempotent: bool)
true if the batch can be safely retried
get_is_idempotent
pub fn get_is_idempotent(&self) -> bool
Tracing
set_tracing
pub fn set_tracing(&mut self, should_trace: bool)
Enable CQL tracing for this batch
get_tracing
pub fn get_tracing(&self) -> bool
Timestamp
set_timestamp
Sets the default timestamp for all statements in the batch.
pub fn set_timestamp(&mut self, timestamp: Option<i64>)
Timestamp in microseconds, or None for server-side timestamps
get_timestamp
pub fn get_timestamp(&self) -> Option<i64>
Timeout
set_request_timeout
pub fn set_request_timeout(&mut self, timeout: Option<Duration>)
get_request_timeout
pub fn get_request_timeout(&self) -> Option<Duration>
Policies
set_retry_policy
pub fn set_retry_policy(&mut self, retry_policy: Option<Arc<dyn RetryPolicy>>)
get_retry_policy
pub fn get_retry_policy(&self) -> Option<&Arc<dyn RetryPolicy>>
set_load_balancing_policy
pub fn set_load_balancing_policy(
&mut self,
load_balancing_policy: Option<Arc<dyn LoadBalancingPolicy>>
)
get_load_balancing_policy
pub fn get_load_balancing_policy(&self) -> Option<&Arc<dyn LoadBalancingPolicy>>
Execution Profile
set_execution_profile_handle
pub fn set_execution_profile_handle(
&mut self,
profile_handle: Option<ExecutionProfileHandle>
)
get_execution_profile_handle
pub fn get_execution_profile_handle(&self) -> Option<&ExecutionProfileHandle>
History Listener
set_history_listener
pub fn set_history_listener(&mut self, history_listener: Arc<dyn HistoryListener>)
remove_history_listener
pub fn remove_history_listener(&mut self) -> Option<Arc<dyn HistoryListener>>
Example Usage
Basic Batch
use scylla::{Session, SessionBuilder};
use scylla::statement::batch::{Batch, BatchType};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.build()
.await?;
let mut batch = Batch::new(BatchType::Logged);
batch.append_statement("INSERT INTO users (id, name) VALUES (1, 'Alice')");
batch.append_statement("INSERT INTO users (id, name) VALUES (2, 'Bob')");
session.batch(&batch, ((), ())).await?;
Ok(())
}
Batch with Prepared Statements
use scylla::statement::batch::{Batch, BatchType};
let mut batch = Batch::new(BatchType::Logged);
let prepared = session
.prepare("INSERT INTO users (id, name) VALUES (?, ?)")
.await?;
batch.append_statement(&prepared);
batch.append_statement(&prepared);
// Execute with values for each statement
session.batch(&batch, ((1, "Alice"), (2, "Bob"))).await?;
Batch with Mixed Statements
let mut batch = Batch::new(BatchType::Unlogged);
// Mix of prepared and unprepared
let prepared = session.prepare("INSERT INTO users (id, name) VALUES (?, ?)").await?;
batch.append_statement(prepared);
batch.append_statement("INSERT INTO log (event) VALUES ('batch executed')");
// First tuple for prepared statement, second is empty for unprepared
session.batch(&batch, ((1, "Alice"), ())).await?;
Counter Batch
let mut batch = Batch::new(BatchType::Counter);
batch.append_statement("UPDATE counters SET count = count + 1 WHERE id = 1");
batch.append_statement("UPDATE counters SET count = count + 1 WHERE id = 2");
session.batch(&batch, ((), ())).await?;
Batch Values
See BatchValues for details on providing values to batch statements.
Best Practices
- Use prepared statements in batches for better performance
- Keep batches small - large batches can cause timeouts
- Use Unlogged batches when atomicity is not required
- Partition awareness - statements in a batch should target the same partition when possible
- Counter batches - only include counter updates in Counter batch type
Don’t use batches as a performance optimization for unrelated statements. Batches add overhead and should only be used when atomicity is required or when statements target the same partition.
See Also