use std::sync::Arc;
use txn_db::{Db, TxnError};
fn main() -> Result<(), TxnError> {
let dir = std::env::temp_dir().join("txn-db-durable-example");
std::fs::create_dir_all(&dir).map_err(|e| TxnError::store("create example dir", e))?;
let path = dir.join("accounts.wal");
let _ = std::fs::remove_file(&path);
{
let db = Db::open(&path)?;
let mut tx = db.begin();
tx.put(b"alice".to_vec(), 100u64.to_le_bytes().to_vec());
tx.put(b"bob".to_vec(), 50u64.to_le_bytes().to_vec());
let ts = tx.commit()?;
println!("session 1: committed alice + bob at {ts}");
let mut pending = db.begin();
pending.put(b"carol".to_vec(), 999u64.to_le_bytes().to_vec());
drop(pending);
println!("session 1: left carol uncommitted, dropping database");
}
{
let db = Db::open(&path)?;
println!("session 2: reopened, watermark at {}", db.last_committed());
let snap = db.snapshot();
println!(" alice = {}", balance(&snap.get(b"alice")?));
println!(" bob = {}", balance(&snap.get(b"bob")?));
println!(" carol present: {}", snap.get(b"carol")?.is_some());
let mut tx = db.begin();
let alice = balance(&tx.get(b"alice")?);
let bob = balance(&tx.get(b"bob")?);
tx.put(b"alice".to_vec(), (alice - 25).to_le_bytes().to_vec());
tx.put(b"bob".to_vec(), (bob + 25).to_le_bytes().to_vec());
let ts = tx.commit()?;
println!("session 2: transferred 25 alice -> bob at {ts}");
}
let _ = std::fs::remove_file(&path);
Ok(())
}
fn balance(value: &Option<Arc<[u8]>>) -> u64 {
value.as_ref().map_or(0, |bytes| {
let mut buf = [0u8; 8];
buf.copy_from_slice(&bytes[..8]);
u64::from_le_bytes(buf)
})
}