use std::path::Path; #[derive(Debug)] enum Error { Persy(persy::PersyError), } /// /// Example of transaction recovery driven by user. /// /// In this example two transactions with different id are run without finalize the commit and /// forcing the process to crash. /// /// Multiple run of this example will show that only the data of the transaction with a specific id /// is recovered. /// /// fn main() { let create_segment; // check if the file exist if not create it if !Path::new("data.persy").exists() { persy::Persy::create("data.persy").expect("create file correctly"); create_segment = true; } else { create_segment = false; } // open the storage using a custom recovery function that recover only the transactions with // custom id "ok_commit" let persy = persy::Persy::open_with_recover("data.persy", persy::Config::new(), |id| { String::from("ok_commit").into_bytes().eq(id) }) .expect("open file correctly"); // if the file was new create the segment if create_segment { 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"); } //scan the persistent data and verify if the data in there is all valid also after the crash/ let good = vec![10; 20]; for (id, content) in persy.scan("data").expect("segment scan works") { if good.eq(&content) { println!("found some right recovered content"); } else { panic!( " panic !!! this data should haven't been recovered id:{:?} , {:?}", id, content ); } } // insert some data with a "ok_commit" transaction id without finalize the commit let mut tx = persy .begin_with(persy::TransactionConfig::new().set_transaction_id(String::from("ok_commit").into_bytes())) .expect("begin tx correctly"); let val = vec![10; 20]; tx.insert("data", &val).expect("insert correctly"); let _prepared = tx.prepare().expect("prepare commit correctly"); //insert some data with "no_commit" transaction id without finalize the commit let mut tx = persy .begin_with(persy::TransactionConfig::new().set_transaction_id(String::from("no_commit").into_bytes())) .expect("begin tx correctly"); let val = vec![10; 50]; tx.insert("data", &val).expect("insert correctly"); let _prepared = tx.prepare().expect("prepare commit correctly"); // panic without commit the next run will recover only some specific data panic!("this panic on purpose without commit") } impl From for Error { fn from(err: persy::PersyError) -> Error { Error::Persy(err) } }