Struct Db

Source
pub struct Db { /* private fields */ }
Expand description

§Db - Tagged data storage.

HashMap <container_name, container>

  • container *

    pages: HashMap<PageId, Page>

    index: HashMap<NodeId, PageId>

*Simplified structure for the data store.

Implementations§

Source§

impl Db

§Db

Initially load only tag you are interested in. Tags lazy load with use.

Todo: prune infrequently used data from memory.

Source

pub fn init(config: Option<Config>) -> Result<Db>

§Database init - Primary use
  • Parameters

    • config: Defaults to Config::default()
  • Returns

    • Result: Instance of Db
use crate::mycelium_core::Db;
use crate::mycelium_core::prelude::*;

// Builder pattern for config
let config = Config::new()
    .with_data_directory("./data")
    .with_block_count(32) // blocks per page when run persistently
    .with_block_size(1024); // size of blocks on page    ///

// TODO: If block count/size are adjusted on an existing Db::vacuum()
// should be run to update existing pages.

match Db::init(Some(config)) {
    Ok(_) => assert!(true),
    _ => assert!(false, "Failed to create db from config")
}
Source

pub fn new() -> Result<Db>

§new db

Db::new() will create a folder structure and system files used by the database or read existing ones. Nothing else is written to disk without specific calls to do so.

  • Returns
    • Result: Instance of db with default config
use crate::mycelium_core::prelude::*;

match Db::new() {
    Ok(_) => assert!(true),
    _ => assert!(false, "failed to start db core.")
}
Source

pub fn add(&self, item: &[u8], tag: &str) -> Result<[u8; 16], Box<dyn Error>>

§Add item to container.
  • Parameters

    • Item: Reference to byte array of item.
    • Tag: Container for item.
  • Returns

    • Result(DbId)
use crate::mycelium_core::Db;

// new db
let db = Db::new().expect("Failed to create db");
// add an item
let id = db.add(b"new item", "tag").expect("Failed to add item");
// should get a new id back. Id should not be [0;16] as that is
// an empty id from Uuid.
assert!(id != [0 as u8; 16])
Source

pub fn get(&self, tag: &str, id: DbId) -> Option<Node>

§Get a node (struct that wraps the serialized item).
  • Parameters

    • tag: name of container containing the item
    • id: [u8;16] identifier for a head node
  • Returns

    • Option: None if nothing found.
use crate::mycelium_core::Db;

//new db
let db = Db::new().expect("Failed to create db.");
//get an item that doesn't exist
let item_none = db.get("no_exist", [0;16]);
//should be none
assert!(item_none.is_none());

//add an item to tag tag
let id = db.add(b"item bytes", "tag").expect("Failed to add item.");
//get item just added with id
let item_b = db.get("tag", id).unwrap();
//item should have same contents
assert!(b"item bytes".to_vec() == item_b.get_item())
Source

pub fn get_reserved_sys(&self) -> PathBuf

§Get reserved system folder
Source

pub fn get_tag(&self, tag: &str) -> Option<Vec<Node>>

§Get all items in tag
  • Parameters

    • tag: Tag identifier to fetch items of
  • Returns:

    • Option<Vec>: list of nodes
use crate::mycelium_core::Db;

// new db
let db = Db::new().expect("Failed to create db");
// get items for non-existing tag
let empty = db.get_tag("emtpy_tag");
// should be empty
assert!(empty.is_none());

//add some items to tag dog
db.add(b"shepherd", "dog").expect("Failed to add to db");
db.add(b"pitbull", "dog").expect("Failed to add to db");
//get a list of items in tag dog
let dog_list = db.get_tag("dog").expect("Failed to get a result");
//should get 2 back
assert!(dog_list.len() == 2);
Source

pub fn get_tag_hashmap(&self, tag: &str) -> Option<HashMap<DbId, Node>>

§All nodes in tag as hashmap
  • Parameters:

    • tag: container id
  • Returns:

    • Option<HashMap<DbId,Node>>>
use crate::mycelium_core::Db;

// new db
let db = Db::new().expect("Failed to create db");
// add an item (returns an id we are ignoring)
db.add(b"Some bytes", "tag").expect("Failed to add to db");
// get hashmap
let hm = db.get_tag_hashmap("tag").expect("Failed to get map");

assert!(hm.len() == 1);
Source

pub fn get_working_dir(&self) -> PathBuf

§Database working directory
Source

pub fn get_system_id(&self) -> DbId

Source

pub fn list_tags(&self) -> Vec<String>

§Empty list if no tags
Source

pub fn load_tag(&self, tag: &str) -> Result<()>

§Load tag from disk

Multiple calls will destroy in memory changes replacing with what is on disk. load_tag on emtpy tag will result in container being created.

  • Parameters

    • tag: container name
  • Return

    • Result: ()/Err
use crate::mycelium_core::Db;

//new db
let db = Db::new().expect("Failed to create new db");

match db.load_tag("no_exists") {
    Ok(_) => assert!(true),
    Err(_) => assert!(false, "Error on load non existent tag"),
};
Source

pub fn node_history( &mut self, tag: &str, node_id: DbId, limit: usize, ) -> Option<(Option<Node>, Vec<Node>)>

§Load Node History

Nodes are a lazily loaded linked list with the most recent version as the head. Load the past versions of a node into memory before retrieving them.

  • Parameters

    • tag: container name containing node
    • node_id: Id for node to load history list for
  • Returns

    • Tuple.0: Head of node list. None if node has been archived
    • Tuple.1: List of node versions
use crate::mycelium_core::Db;

// new db
let mut db = Db::new().expect("Failed to create db");

// add item
let id = db.add(b"shepherd", "dog").expect("Failed to add item");
// update node
db.update_node(id, b"German Shepherd", "dog").expect("Failed to update");
// query history
let result = db.node_history("dog", id, 0).expect("Failed to get node history");

assert!(result.0.is_some() && result.1.len() ==1);
Source

pub fn refresh(&self, tag: &str) -> Result<(), Box<dyn Error>>

§Refresh Tag

Load tag from disk. Will drop any changes currently in memory.

  • Parameters

    • tag: container name
  • Return

    • Result: (), Box
use crate::mycelium_core::Db;

// new db
let db = Db::new().expect("Failed to create db");

// Loads from disk.
match db.refresh("dog") {
    Ok(_) => assert!(true),
    Err(_) => assert!(false),
}
Source

pub fn save_all(&self) -> Result<(), Error>

§Write all to disk/cache
Source

pub fn update_node( &self, node_id: DbId, item: &[u8], tag: &str, ) -> Result<(), Box<dyn Error>>

§Update Node

On update new node is pushed onto head of list structure and original is pushed into history.

  • Parameters:

    • node_id: [u8; 16] id of list head node
    • item: &u8 byte array of item
    • tag: container id of item
  • Returns

    • Result: (), Err.
use crate::mycelium_core::Db;

//new db
let db = Db::new().expect("Failed to create db");

// add item
let id = db.add(b"item bytes", "item").expect("Failed to add item");
// update item
match db.update_node(id, b"better bytes", "item") {
    Ok(_) => assert!(true),
    Err(_) => assert!(false, "Failed to update")
}

Auto Trait Implementations§

§

impl !Freeze for Db

§

impl RefUnwindSafe for Db

§

impl Send for Db

§

impl Sync for Db

§

impl Unpin for Db

§

impl UnwindSafe for Db

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.