[][src]Struct tinydb::Database

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

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

impl<T: Hash + Eq + Serialize + DeserializeOwned> Database<T>[src]

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

Creates a new database instance from given parameters.

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

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].
}

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

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
}

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

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).

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

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.

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

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.

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

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.

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

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);
}

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

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

impl<T: Clone + Hash + Eq> Clone for Database<T>[src]

impl<T: Debug + Hash + Eq> Debug for Database<T>[src]

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

impl<T: Eq + Hash> Eq for Database<T>[src]

impl<T: PartialEq + Hash + Eq> PartialEq<Database<T>> for Database<T>[src]

impl<T: Hash + Eq> Serialize for Database<T> where
    T: Serialize
[src]

impl<T: Hash + Eq> StructuralEq for Database<T>[src]

impl<T: Hash + Eq> StructuralPartialEq for Database<T>[src]

Auto Trait Implementations

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

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

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

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.