2021-10-19 11:16:24 +02:00
|
|
|
use rkyv::{Archive, Serialize, Deserialize};
|
2021-10-13 04:57:40 +02:00
|
|
|
|
|
|
|
use super::{
|
|
|
|
AllocAdapter,
|
|
|
|
DB,
|
|
|
|
};
|
2021-10-19 11:16:24 +02:00
|
|
|
use crate::db::AlignedAdapter;
|
|
|
|
use crate::db::raw::RawDB;
|
|
|
|
use std::sync::Arc;
|
2021-10-20 18:37:50 +02:00
|
|
|
use crate::db::{Environment, DatabaseFlags};
|
|
|
|
use crate::db::Result;
|
2021-10-13 04:57:40 +02:00
|
|
|
|
2021-10-20 18:37:50 +02:00
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
2021-10-13 04:57:40 +02:00
|
|
|
#[derive(Archive, Serialize, Deserialize)]
|
2021-10-20 18:37:50 +02:00
|
|
|
#[derive(serde::Serialize, serde::Deserialize)]
|
2021-10-13 04:57:40 +02:00
|
|
|
pub struct Resource {
|
|
|
|
uuid: u128,
|
|
|
|
id: String,
|
|
|
|
name_idx: u64,
|
|
|
|
description_idx: u64,
|
|
|
|
}
|
|
|
|
|
2021-10-20 18:37:50 +02:00
|
|
|
#[derive(Clone)]
|
2021-10-13 04:57:40 +02:00
|
|
|
pub struct ResourceDB {
|
2021-10-19 11:16:24 +02:00
|
|
|
env: Arc<Environment>,
|
2021-10-13 04:57:40 +02:00
|
|
|
db: DB<AllocAdapter<Resource>>,
|
2021-10-19 11:16:24 +02:00
|
|
|
id_index: DB<AlignedAdapter<u64>>,
|
2021-10-13 04:57:40 +02:00
|
|
|
}
|
2021-10-19 11:16:24 +02:00
|
|
|
|
|
|
|
impl ResourceDB {
|
|
|
|
pub unsafe fn new(env: Arc<Environment>, db: RawDB, id_index: RawDB) -> Self {
|
|
|
|
let db = DB::new_unchecked(db);
|
|
|
|
let id_index = DB::new_unchecked(id_index);
|
|
|
|
|
|
|
|
Self { env, db, id_index }
|
|
|
|
}
|
|
|
|
|
2021-10-20 18:37:50 +02:00
|
|
|
pub unsafe fn open(env: Arc<Environment>) -> Result<Self> {
|
|
|
|
let db = RawDB::open(&env, Some("resources"))?;
|
|
|
|
let idx = RawDB::open(&env, Some("resources-idx"))?;
|
|
|
|
Ok(Self::new(env, db, idx))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub unsafe fn create(env: Arc<Environment>) -> Result<Self> {
|
|
|
|
let flags = DatabaseFlags::empty();
|
|
|
|
let db = RawDB::create(&env, Some("resources"), flags)?;
|
|
|
|
let idx = RawDB::create(&env, Some("resources-idx"), flags)?;
|
|
|
|
Ok(Self::new(env, db, idx))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn lookup_id<S: AsRef<str>>(&self, id: S) -> Result<Option<u64>> {
|
2021-10-19 11:16:24 +02:00
|
|
|
let txn = self.env.begin_ro_txn()?;
|
2021-10-20 18:37:50 +02:00
|
|
|
let id = self.id_index.get(&txn, &id.as_ref().as_bytes()).map(|ok| {
|
2021-10-19 11:16:24 +02:00
|
|
|
ok.map(|num| *num)
|
2021-10-20 18:37:50 +02:00
|
|
|
})?;
|
|
|
|
Ok(id)
|
2021-10-19 11:16:24 +02:00
|
|
|
}
|
|
|
|
}
|