persy 0.7.0

Transactional Persistence Engine
Documentation
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 sotrage using a custom recorvery 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");
        persy.create_segment(&mut tx, "data").expect("create segment correctly");
        let prepared = persy.prepare_commit(tx).expect("prepare commit correctly");
        persy.commit(prepared).expect("tx commited 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_id(String::from("ok_commit").into_bytes())
        .expect("begin tx correctly");
    let val = vec![10; 20];
    persy.insert_record(&mut tx, "data", &val).expect("insert correctly");
    let _prepared = persy.prepare_commit(tx).expect("prepare commit correctly");

    //insert some data with "no_commit" transaction id without finalize the commit
    let mut tx = persy
        .begin_id(String::from("no_commit").into_bytes())
        .expect("begin tx correctly");
    let val = vec![10; 50];
    persy.insert_record(&mut tx, "data", &val).expect("insert correctly");
    let _prepared = persy.prepare_commit(tx).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<persy::PersyError> for Error {
    fn from(err: persy::PersyError) -> Error {
        Error::Persy(err)
    }
}