summaryrefslogtreecommitdiff
path: root/src/database/abstraction.rs
blob: 93660f9f26876086d79d8596870ce5d144db1391 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use super::Config;
use crate::Result;

use std::{future::Future, pin::Pin, sync::Arc};

#[cfg(feature = "sled")]
pub mod sled;

#[cfg(feature = "sqlite")]
pub mod sqlite;

#[cfg(feature = "heed")]
pub mod heed;

#[cfg(feature = "rocksdb")]
pub mod rocksdb;

#[cfg(feature = "persy")]
pub mod persy;

#[cfg(any(
    feature = "sqlite",
    feature = "rocksdb",
    feature = "heed",
    feature = "persy"
))]
pub mod watchers;

pub trait KeyValueDatabaseEngine: Send + Sync {
    fn open(config: &Config) -> Result<Self>
    where
        Self: Sized;
    fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>>;
    fn flush(&self) -> Result<()>;
    fn cleanup(&self) -> Result<()> {
        Ok(())
    }
    fn memory_usage(&self) -> Result<String> {
        Ok("Current database engine does not support memory usage reporting.".to_owned())
    }
}

pub trait KvTree: Send + Sync {
    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;

    fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;
    fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()>;

    fn remove(&self, key: &[u8]) -> Result<()>;

    fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;

    fn iter_from<'a>(
        &'a self,
        from: &[u8],
        backwards: bool,
    ) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;

    fn increment(&self, key: &[u8]) -> Result<Vec<u8>>;
    fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()>;

    fn scan_prefix<'a>(
        &'a self,
        prefix: Vec<u8>,
    ) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;

    fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;

    fn clear(&self) -> Result<()> {
        for (key, _) in self.iter() {
            self.remove(&key)?;
        }

        Ok(())
    }
}