1
use nebari::{
2
    tree::{Root, Versioned},
3
    Error,
4
};
5

            
6
fn main() -> Result<(), Error> {
7
    // The Roots type creates a multi-"tree" database by creating a folder at
8
    // the path provided and creating individual files within. While the
9
    // nomenclature "file" is used, Nebari is written atop an abstraction layer
10
    // that allows using a memory-backed simulated file system and could be used
11
    // to implement non-traditional storage backends.
12
    let roots = nebari::Config::default_for("simple-database.nebari").open()?;
13

            
14
    // Each tree contains a unique set of keys and values, and can be written
15
    // using a versioned or unversioned tree root.
16
    let tree_one = roots.tree(Versioned::tree("one"))?;
17
    tree_one.set("hello", "world")?;
18
    let tree_two = roots.tree(Versioned::tree("two"))?;
19
    assert!(tree_two.get("hello".as_bytes())?.is_none());
20

            
21
    // Each operation on a Tree is executed within an ACID-compliant
22
    // transaction. If you want to execute multiple operations in a single
23
    // transaction, you can do that as well:
24
    let transaction = roots.transaction(&[Versioned::tree("one"), Versioned::tree("two")])?;
25
    {
26
        // This API isn't as ergonomic as it should be. The trees are accessible in
27
        // the same order in which they're specified in the transaction call:
28
        let mut tx_tree_one = transaction.tree::<Versioned>(0).unwrap();
29
        tx_tree_one.set("hello", "everyone")?;
30

            
31
        // The operation above is not visible to trees outside of the transaction:
32
        assert_eq!(
33
            tree_one.get("hello".as_bytes())?.as_deref(),
34
            Some("world".as_bytes())
35
        );
36

            
37
        let mut tx_tree_two = transaction.tree::<Versioned>(1).unwrap();
38
        tx_tree_two.set("another tree", "another value")?;
39
    }
40

            
41
    // If you drop the transaction before calling commit, the transaction will be rolled back.
42
    transaction.commit()?;
43

            
44
    // Now the changes are visible:
45
    assert_eq!(
46
        tree_one.get("hello".as_bytes())?.as_deref(),
47
        Some("everyone".as_bytes())
48
    );
49

            
50
    Ok(())
51
}