pub struct LocalDatabase<T> { /* private fields */ }Expand description
A local database for storing key-value pairs.
The database is stored in a JSON file, which is updated every time a key-value pair is added, updated, or removed. Writes are atomic (write to temporary file, then rename) to prevent corruption.
§Example
use blueprint_store_local_database::LocalDatabase;
let db = LocalDatabase::<u64>::open("data.json")?;
db.set("key", 42)?;
assert_eq!(db.get("key")?, Some(42));Implementations§
Source§impl<T> LocalDatabase<T>
impl<T> LocalDatabase<T>
Sourcepub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error>
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error>
Reads a LocalDatabase from the given path.
If the file does not exist, an empty database is created.
§Examples
use blueprint_store_local_database::LocalDatabase;
let db = LocalDatabase::<u64>::open("data.json")?;
assert!(db.is_empty()?);§Errors
- The parent of
pathis not a directory - Unable to write to
path
Sourcepub fn len(&self) -> Result<usize, Error>
pub fn len(&self) -> Result<usize, Error>
Returns the number of key-value pairs in the database.
Sourcepub fn set(&self, key: &str, value: T) -> Result<(), Error>
pub fn set(&self, key: &str, value: T) -> Result<(), Error>
Adds or updates a key-value pair in the database.
§Errors
- Unable to serialize the data
- Unable to write to disk
Sourcepub fn get(&self, key: &str) -> Result<Option<T>, Error>
pub fn get(&self, key: &str) -> Result<Option<T>, Error>
Retrieves a value associated with the given key.
Sourcepub fn remove(&self, key: &str) -> Result<Option<T>, Error>
pub fn remove(&self, key: &str) -> Result<Option<T>, Error>
Removes a key-value pair from the database.
Returns the removed value if the key existed.
Sourcepub fn entries(&self) -> Result<Vec<(String, T)>, Error>
pub fn entries(&self) -> Result<Vec<(String, T)>, Error>
Returns a clone of all key-value pairs in the database.
Sourcepub fn find<F>(&self, predicate: F) -> Result<Option<T>, Error>
pub fn find<F>(&self, predicate: F) -> Result<Option<T>, Error>
Finds the first value matching a predicate.
Sourcepub fn update<F>(&self, key: &str, f: F) -> Result<bool, Error>
pub fn update<F>(&self, key: &str, f: F) -> Result<bool, Error>
Atomically gets a value by key, applies a mutation, and flushes.
Returns true if the key was found and updated.