db/heromodels/src/db.rs
Lee Smet d8b40b6995
simplify DB constructor
Signed-off-by: Lee Smet <lee.smet@hotmail.com>
2025-04-25 14:15:52 +02:00

74 lines
2.1 KiB
Rust

use std::borrow::Borrow;
use heromodels_core::{Index, Model};
use serde::{Deserialize, Serialize};
pub mod hero;
pub trait Db {
/// Error type returned by database operations.
type Error: std::fmt::Debug;
/// Open the collection for a specific model. This method must create the collection if it does not exist.
fn collection<M: Model>(&self) -> Result<impl Collection<&str, M>, Error<Self::Error>>;
}
/// A collection stores a specific model under a specific key
pub trait Collection<K, V>
where
K: Serialize,
V: Serialize + for<'a> Deserialize<'a>,
{
/// Error type for database operations
type Error: std::fmt::Debug;
/// Get all items where the given index field is equal to key.
fn get<I, Q>(&self, key: &Q) -> Result<Vec<V>, Error<Self::Error>>
where
I: Index<Model = V>,
I::Key: Borrow<Q>,
Q: ToString + ?Sized;
/// Get an object from its ID. This does not use an index lookup
fn get_by_id(&self, id: u32) -> Result<Option<V>, Error<Self::Error>>;
/// Store an item in the DB.
fn set(&self, value: &V) -> Result<(), Error<Self::Error>>;
/// Delete all items from the db with a given index.
fn delete<I, Q>(&self, key: &Q) -> Result<(), Error<Self::Error>>
where
I: Index<Model = V>,
I::Key: Borrow<Q>,
Q: ToString + ?Sized;
/// Delete an object with a given ID
fn delete_by_id(&self, id: u32) -> Result<(), Error<Self::Error>>;
/// Get all objects from the colelction
fn get_all(&self) -> Result<Vec<V>, Error<Self::Error>>;
}
/// Errors returned by the DB implementation
#[derive(Debug)]
pub enum Error<E> {
/// Error in the underlying database
DB(E),
/// Error decoding a stored model
Decode(bincode::error::DecodeError),
/// Error encoding a model for storage
Encode(bincode::error::EncodeError),
}
impl<E> From<bincode::error::DecodeError> for Error<E> {
fn from(value: bincode::error::DecodeError) -> Self {
Error::Decode(value)
}
}
impl<E> From<bincode::error::EncodeError> for Error<E> {
fn from(value: bincode::error::EncodeError) -> Self {
Error::Encode(value)
}
}