aboutsummaryrefslogtreecommitdiff
path: root/database/src/backends/mod.rs
blob: ba30b46f7717fe51d261bc619437f1ba1a82e40a (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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

mod memory;
mod redb;
mod rocksdb;

use anyhow::{Result, bail};
use std::{path::Path, sync::Arc};

pub type WriteTxnFunction = dyn FnMut(&mut dyn WriteTransaction) -> Result<()>;
pub type ReadTxnFunction = dyn FnMut(&dyn ReadTransaction) -> Result<()>;

pub trait Database: Send + Sync + 'static {
    fn write_transaction(
        &self,
        f: &mut dyn FnMut(&mut dyn WriteTransaction) -> Result<()>,
    ) -> Result<()>;
    fn read_transaction(&self, f: &mut dyn FnMut(&dyn ReadTransaction) -> Result<()>)
    -> Result<()>;
}
pub trait WriteTransaction: ReadTransaction {
    fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()>;
    fn del(&mut self, key: &[u8]) -> Result<()>;
}
pub trait ReadTransaction {
    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
    fn iter<'a>(
        &'a self,
        key: &[u8],
        reverse: bool,
    ) -> Result<Box<dyn Iterator<Item = Result<Vec<u8>>> + 'a>>;
}

pub fn create_backend(driver: &str, path: &Path) -> Result<Arc<dyn Database>> {
    Ok(match driver {
        "rocksdb" => Arc::new(rocksdb::new(path)?),
        "redb" => Arc::new(redb::new(path)?),
        "memory" => Arc::new(memory::new()),
        _ => bail!("unknown db driver"),
    })
}