simple_database/
traits.rs

1use super::Error;
2
3use super::database::Index;
4
5use std::path::{PathBuf, Path};
6
7use serde::{Serialize, Deserialize};
8use dyn_clone::{clone_trait_object, DynClone};
9
10pub type KeyValue = Vec<(Vec<u8>, Vec<u8>)>;
11
12#[async_trait::async_trait]
13pub trait KeyValueStore: std::fmt::Debug + Send + Sync + DynClone {
14    async fn new(location: PathBuf) -> Result<Self, Error> where Self: Sized;
15    async fn partition(&self, location: PathBuf) -> Result<Box<dyn KeyValueStore>, Error>;
16    async fn get_partition(&self, location: &Path) -> Option<Box<dyn KeyValueStore>>;
17    async fn clear(&self) -> Result<(), Error>;
18    async fn delete(&self, key: &[u8]) -> Result<(), Error>;
19    async fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error>;
20    async fn set(&self, key: &[u8], value: &[u8]) -> Result<(), Error>;
21
22    async fn get_all(&self) -> Result<KeyValue, Error>;
23    async fn keys(&self) -> Result<Vec<Vec<u8>>, Error>;
24    async fn values(&self) -> Result<Vec<Vec<u8>>, Error>;
25
26    fn location(&self) -> PathBuf;
27}
28clone_trait_object!(KeyValueStore);
29
30pub trait Indexable {
31    const PRIMARY_KEY: &'static str = "primary_key";
32    const DEFAULT_SORT: &'static str = Self::PRIMARY_KEY;
33    fn primary_key(&self) -> Vec<u8>;
34    fn secondary_keys(&self) -> Index {Index::default()}
35    fn index(&self) -> Index {
36        let mut index = self.secondary_keys();
37        index.insert(Self::PRIMARY_KEY.to_string(), hex::encode(self.primary_key()).into());
38        index
39    }
40}
41
42pub trait Field: Serialize + for<'a> Deserialize<'a> + std::fmt::Debug {
43    fn as_bytes(&self) -> Vec<u8>;
44}