use persy::{Config, Persy, TxStrategy}; use std::path::Path; #[derive(Debug)] enum Error { Persy(persy::PersyError), } /// /// Example of transaction concurrency management strategy /// /// fn main() { if !Path::new("concurrency.persy").exists() { Persy::create("concurrency.persy").expect("create file correctly"); let persy = Persy::open("concurrency.persy", persy::Config::new()).expect("open file correctly"); let mut tx = persy.begin().expect("begin tx correctly"); tx.create_segment("data").expect("create segment correctly"); let prepared = tx.prepare().expect("prepare commit correctly"); prepared.commit().expect("tx committed correctly"); } if !Path::new("concurrency1.persy").exists() { Persy::create("concurrency1.persy").expect("create file correctly"); let persy = Persy::open("concurrency1.persy", persy::Config::new()).expect("open file correctly"); let mut tx = persy.begin().expect("begin tx correctly"); tx.create_segment("data").expect("create segment correctly"); let prepared = tx.prepare().expect("prepare commit correctly"); prepared.commit().expect("tx committed correctly"); } { let mut config = Config::new(); config.change_tx_strategy(TxStrategy::LastWin); let persy = Persy::open("concurrency.persy", config).expect("open file correctly"); let mut tx = persy.begin().unwrap(); let data = String::from("first data").into_bytes(); let id = tx.insert("data", &data).unwrap(); let prep = tx.prepare().unwrap(); prep.commit().unwrap(); let second_data = String::from("second data").into_bytes(); let mut tx = persy.begin().unwrap(); tx.update("data", &id, &second_data).unwrap(); let third_data = String::from("third data").into_bytes(); let mut tx1 = persy.begin().unwrap(); tx1.update("data", &id, &third_data).unwrap(); let prep = tx.prepare().unwrap(); prep.commit().unwrap(); let prep = tx1.prepare().unwrap(); prep.commit().unwrap(); let val = persy.read("data", &id).unwrap().unwrap(); assert_eq!(val, third_data); } { let mut config = Config::new(); config.change_tx_strategy(TxStrategy::VersionOnRead); let persy = Persy::open("concurrency1.persy", config).expect("open file correctly"); let mut tx = persy.begin().unwrap(); let data = String::from("first data").into_bytes(); let id = tx.insert("data", &data).unwrap(); let prep = tx.prepare().unwrap(); prep.commit().unwrap(); let mut tx = persy.begin().unwrap(); let _persistent_data_can_be_check = tx.read("data", &id).unwrap(); let second_data = String::from("second data").into_bytes(); tx.update("data", &id, &second_data).unwrap(); let third_data = String::from("third data").into_bytes(); let tx1 = persy.begin().unwrap(); tx.update("data", &id, &third_data).unwrap(); let prep = tx.prepare().unwrap(); prep.commit().unwrap(); let to_fail = tx1.prepare(); assert!(to_fail.is_err()); let val = persy.read("data", &id).unwrap().unwrap(); assert_eq!(val, second_data); } } impl From for Error { fn from(err: persy::PersyError) -> Error { Error::Persy(err) } }