use elif_orm::{
database::ManagedPool,
error::ModelError,
transaction::{
with_transaction, with_transaction_default, IsolationLevel, Transaction, TransactionConfig,
},
};
fn main() {
println!("Transaction usage examples (see source code for implementation details)");
}
#[allow(dead_code)]
async fn transaction_examples() -> Result<(), ModelError> {
let pool = create_mock_pool().await?;
let tx = Transaction::begin_default(&pool).await?;
tx.commit().await?;
let config = TransactionConfig {
isolation_level: Some(IsolationLevel::Serializable),
auto_retry: true,
max_retries: 3,
..Default::default()
};
let tx = Transaction::begin(&pool, config).await?;
tx.commit().await?;
let tx = Transaction::begin_read_only(&pool).await?;
tx.commit().await?;
let result = with_transaction_default(&pool, |_tx| {
Box::pin(async {
Ok("Operation completed successfully".to_string())
})
})
.await?;
println!("Result: {}", result);
let serializable_config = TransactionConfig {
isolation_level: Some(IsolationLevel::Serializable),
auto_retry: true,
max_retries: 5,
..Default::default()
};
let result = with_transaction(&pool, serializable_config, |_tx| {
Box::pin(async {
perform_complex_operation().await
})
})
.await?;
println!("Complex operation result: {}", result);
Ok(())
}
#[allow(dead_code)]
async fn create_mock_pool() -> Result<ManagedPool, ModelError> {
Err(ModelError::Connection(
"Mock pool - database not configured".to_string(),
))
}
#[allow(dead_code)]
async fn perform_complex_operation() -> Result<String, ModelError> {
Ok("Complex operation completed".to_string())
}
#[allow(dead_code)]
async fn process_order_with_transaction(
pool: &ManagedPool,
order_id: i32,
) -> Result<(), ModelError> {
with_transaction_default(pool, |_tx| {
Box::pin(async move {
println!("Processing order {}", order_id);
Ok(())
})
})
.await
}
#[allow(dead_code)]
async fn bank_transfer(
pool: &ManagedPool,
from_account: i32,
to_account: i32,
amount: i64,
) -> Result<(), ModelError> {
let config = TransactionConfig {
isolation_level: Some(IsolationLevel::Serializable),
auto_retry: true,
max_retries: 3,
..Default::default()
};
with_transaction(pool, config, |_tx| {
Box::pin(async move {
println!(
"Transferring {} from account {} to account {}",
amount, from_account, to_account
);
Ok(())
})
})
.await
}
#[allow(dead_code)]
async fn bulk_data_import(pool: &ManagedPool, data: Vec<String>) -> Result<usize, ModelError> {
let mut tx = Transaction::begin_default(pool).await?;
let mut processed = 0;
for item in data {
match process_item(&item).await {
Ok(_) => {
processed += 1;
if processed % 100 == 0 {
tx.commit().await?;
tx = Transaction::begin_default(pool).await?;
}
}
Err(e) => {
eprintln!("Failed to process item {}: {}", item, e);
}
}
}
if tx.is_active() {
tx.commit().await?;
}
Ok(processed)
}
#[allow(dead_code)]
async fn process_item(_item: &str) -> Result<(), ModelError> {
Ok(())
}