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>
impl<T: Hash + Eq + Serialize + DeserializeOwned> Database<T>
Sourcepub fn new(
label: impl Into<String>,
save_path: impl Into<Option<PathBuf>>,
strict_dupes: bool,
) -> Self
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.
- To add a first item, use Database::add_item.
- If you’d like to load a dumped database, use Database::from.
Sourcepub fn from(path: impl Into<PathBuf>) -> Result<Self, DatabaseError>
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].
}
Sourcepub fn auto_from(
path: impl Into<PathBuf>,
strict_dupes: bool,
) -> Result<Self, DatabaseError>
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
}
Sourcepub fn add_item(&mut self, item: T) -> Result<(), DatabaseError>
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).
Sourcepub fn update_item(&mut self, item: &T, new: T) -> Result<(), DatabaseError>
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.
Sourcepub fn remove_item(&mut self, item: &T) -> Result<(), DatabaseError>
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.
Sourcepub fn dump_db(&self) -> Result<(), DatabaseError>
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.
Sourcepub fn query_item<Q: PartialEq, V: Fn(&T) -> &Q>(
&self,
value: V,
query: Q,
) -> Result<&T, DatabaseError>
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 ofp
. 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);
}
Sourcepub fn contains(&self, query: &T) -> bool
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);
}