use crate::transaction::{Transaction, TransactionPool};
use crate::{DatabaseConnectionPool, ServiceError};
use arangors::transaction::{TransactionCollections, TransactionSettings};
use std::collections::HashMap;
const LOCK_TIMEOUT: usize = 60000;
pub struct TransactionBuilder {
collections: Option<Vec<String>>,
wait_for_sync: Option<bool>,
lock_timeout: Option<usize>,
}
impl TransactionBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
pub fn wait_for_sync(mut self) -> Self {
self.wait_for_sync = Some(true);
self
}
pub fn lock_timeout(mut self, lock_timeout: usize) -> Self {
self.lock_timeout = Some(lock_timeout);
self
}
#[maybe_async::maybe_async]
pub async fn build(
self,
db_pool: &DatabaseConnectionPool,
) -> Result<Transaction, ServiceError> {
let collection_names = self.collections.unwrap_or(db_pool.collections_names());
let accessor = db_pool
.database
.begin_transaction(
TransactionSettings::builder()
.lock_timeout(self.lock_timeout.unwrap_or(LOCK_TIMEOUT))
.wait_for_sync(self.wait_for_sync.unwrap_or(false))
.collections(
TransactionCollections::builder()
.write(collection_names.clone())
.build(),
)
.build(),
)
.await?;
log::trace!("Initialized ArangoDB transaction {}", accessor.id());
let mut collections = HashMap::new();
for collections_name in db_pool.collections_names().iter() {
let collection = accessor.collection(collections_name).await?;
collections.insert(collections_name.clone(), collection);
}
log::trace!("Initialized Aragog transaction pool");
let database = db_pool.database.clone();
Ok(Transaction {
accessor,
pool: TransactionPool {
collections,
database,
},
})
}
}
impl Default for TransactionBuilder {
fn default() -> Self {
Self {
collections: None,
wait_for_sync: None,
lock_timeout: None,
}
}
}