Struct Database

Source
pub struct Database<T: Hash + Eq> {
    pub label: String,
    pub save_path: Option<PathBuf>,
    pub strict_dupes: bool,
    pub items: HashSet<T>,
}
Expand description

The primary database structure, allowing storage of a generic type with dumping/saving options avalible.

The generic type used should primarily be structures as they resemble a conventional database model and should implament hash::Hash and Eq for basic in-memory storage with Serialize and Deserialize being implamented for file operations involving the database (these are also required).

Fields§

§label: String

Friendly name for the database, preferibly in slug-form-like-this as this is the fallback path

This is used when dumping the database without a Database::save_path being defined and a friendly way to order a database

§save_path: Option<PathBuf>

The overwrite path to save the database as, this is recommended otherwise it will end up as ./Hello\ There.tinydb if Database::label is “Hello There”

Primarily used inside of Database::dump_db.

§strict_dupes: bool

If the database should return an error if it tries to insert where an identical item already is. Setting this as false doesn’t allow duplicates, it just doesn’t flag an error.

§items: HashSet<T>

In-memory HashSet of all items

Implementations§

Source§

impl<T: Hash + Eq + Serialize + DeserializeOwned> Database<T>

Source

pub fn new( label: impl Into<String>, save_path: impl Into<Option<PathBuf>>, strict_dupes: bool, ) -> Self

Creates a new database instance from given parameters.

Source

pub fn from(path: impl Into<PathBuf>) -> Result<Self, DatabaseError>

Creates a database from a .tinydb file.

This retrives a dump file (saved database) from the path given and loads it as the Database structure.

§Examples
use tinydb::Database;
use serde::{Serialize, Deserialize};
use std::path::PathBuf;

/// Small example structure to show.
#[derive(Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
struct ExampleStruct {
   data: i32
}

/// Makes a small testing database.
fn make_db() {
    let mut test_db = Database::new("test", None, false);
    test_db.add_item(ExampleStruct { data: 34 });
    test_db.dump_db();
}

/// Get `test_db` defined in [make_db] and test.
fn main() {
    make_db();

    let got_db = Database::from(
        PathBuf::from("test.tinydb")
    ).unwrap();

    assert_eq!(
        got_db.query_item(|s: &ExampleStruct| &s.data, 34).unwrap(),
        &ExampleStruct { data: 34 }
    ); // Check that the database still has added [ExampleStruct].
}
Source

pub fn auto_from( path: impl Into<PathBuf>, strict_dupes: bool, ) -> Result<Self, DatabaseError>

Loads database from existant path or creates a new one if it doesn’t already exist.

This is the recommended way to use TinyDB if you are wanting to easily setup an entire database instance in a short, consise manner. Similar to Database::new and Database::from, this function will also have to be given a strict type argument and you will still have to provide script_dupes even if the database is likely to load an existing one.

This function does make some assumptions about the database name and uses the 2nd to last part before a .. This means that x.y.z will have the name of y, not x so therefore it is recommended to have a database path with x.tinydb or x.db only.

§Examples
use tinydb::*;
use std::path::PathBuf;
use serde::{Serialize, Deserialize};

/// Small example structure to show.
#[derive(Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
struct ExampleStruct {
   data: i32
}

fn main() {
    let dummy_db: Database<ExampleStruct> = Database::new("cool", None, false); // create demo db for `db_from`

    let db_from_path = PathBuf::from("cool.tinydb");
    let db_from: Database<ExampleStruct> = Database::auto_from(db_from_path, false).unwrap(); // automatically load it

    let db_new_path = PathBuf::from("xyz.tinydb");
    let db_new: Database<ExampleStruct> = Database::auto_from(db_new_path, false).unwrap(); // automatically create new as "xyz" doesn't exist
}
Source

pub fn add_item(&mut self, item: T) -> Result<(), DatabaseError>

Adds a new item to the in-memory database.

If this is the first item added to the database, please ensure it’s the only type you’d like to add. Due to generics, the first item you add will be set as the type to use (unless removed).

Source

pub fn update_item(&mut self, item: &T, new: T) -> Result<(), DatabaseError>

Replaces an item inside of the database with another item, used for updating/replacing items easily.

Database::query_item can be used in conjunction to find and replace values individually if needed.

Source

pub fn remove_item(&mut self, item: &T) -> Result<(), DatabaseError>

Removes an item from the database.

See Database::update_item if you’d like to update/replace an item easily, rather than individually deleting and adding.

§Errors

Will return error::DatabaseError::ItemNotFound if the item that is attempting to be deleted was not found.

Source

pub fn dump_db(&self) -> Result<(), DatabaseError>

Dumps/saves database to a binary file.

§Saving path methods

The database will usually save as \[label\].tinydb where \[label\] is the defined Database::label (path is reletive to where tinydb was executed).

You can also overwrite this behaviour by defining a Database::save_path when generating the database inside of Database::new.

Source

pub fn query_item<Q: PartialEq, V: Fn(&T) -> &Q>( &self, value: V, query: Q, ) -> Result<&T, DatabaseError>

Query the database for a specific item.

§Syntax
self.query_item(|[p]| [p].[field], [query]);
  • [p] The closure (Will be whatever the database currently is saving as a schema).
  • [field] The exact field of p. If the database doesn’t contain structures, don’t add the .[field].
  • [query] Item to query for. This is a generic and can be of any reasonable type.
§Examples
use serde::{Serialize, Deserialize};
use tinydb::Database;

#[derive(Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Clone)]
struct ExampleStruct {
    my_age: i32
}

fn main() {
    let my_struct = ExampleStruct { my_age: 329 };
    let mut my_db = Database::new("query_test", None, false);

    my_db.add_item(my_struct.clone());

    let results = my_db.query_item(|s: &ExampleStruct| &s.my_age, 329);

    assert_eq!(results.unwrap(), &my_struct);
}
Source

pub fn contains(&self, query: &T) -> bool

Searches the database for a specific value. If it does not exist, this method will return error::DatabaseError::ItemNotFound.

This is a wrapper around HashSet::contains.

§Examples
use tinydb::Database;
use serde::{Serialize, Deserialize};

#[derive(Hash, Eq, PartialEq, Serialize, Deserialize, Copy, Clone)]
struct ExampleStruct {
    item: i32
}

fn main() {
    let exp_struct = ExampleStruct { item: 4942 };
    let mut db = Database::new("Contains example", None, false);

    db.add_item(exp_struct.clone());

    assert_eq!(db.contains(&exp_struct), true);
}

Trait Implementations§

Source§

impl<T: Clone + Hash + Eq> Clone for Database<T>

Source§

fn clone(&self) -> Database<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + Hash + Eq> Debug for Database<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, T> Deserialize<'de> for Database<T>
where T: Deserialize<'de> + Hash + Eq,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T: PartialEq + Hash + Eq> PartialEq for Database<T>

Source§

fn eq(&self, other: &Database<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T> Serialize for Database<T>
where T: Serialize + Hash + Eq,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<T: Eq + Hash + Eq> Eq for Database<T>

Source§

impl<T: Hash + Eq> StructuralPartialEq for Database<T>

Auto Trait Implementations§

§

impl<T> Freeze for Database<T>

§

impl<T> RefUnwindSafe for Database<T>
where T: RefUnwindSafe,

§

impl<T> Send for Database<T>
where T: Send,

§

impl<T> Sync for Database<T>
where T: Sync,

§

impl<T> Unpin for Database<T>
where T: Unpin,

§

impl<T> UnwindSafe for Database<T>
where T: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,