use super::*;
pub struct Database {
collections: Db,
count: usize,
}
impl Database {
pub fn new(path: &str) -> Self {
if Path::new(path).exists() {
remove_dir_all(path).unwrap();
}
let config = sled::Config::new().path(path);
let collections = config.open().unwrap();
Self { collections, count: 0 }
}
pub fn open(path: &str) -> Self {
let collections = sled::open(path).unwrap();
let count = collections.len();
Self { collections, count }
}
pub fn create_collection<D, const N: usize, const M: usize>(
&mut self,
name: &str,
config: Option<&Config>,
records: Option<&[Record<D, N>]>,
) -> Collection<D, N, M>
where
D: Copy + Serialize,
{
let default_config = Config::default();
let config = match config {
Some(config) => config,
None => &default_config,
};
let collection = match records {
Some(records) => Collection::build(config, records),
None => Collection::new(config),
};
self.save_collection(name, &collection);
collection
}
pub fn get_collection<D, const N: usize, const M: usize>(
&self,
name: &str,
) -> Collection<D, N, M>
where
D: Copy + Serialize + DeserializeOwned,
{
let value = self.collections.get(name).unwrap().unwrap();
bincode::deserialize(&value).unwrap()
}
pub fn save_collection<D, const N: usize, const M: usize>(
&mut self,
name: &str,
collection: &Collection<D, N, M>,
) where
D: Copy + Serialize,
{
let mut new = false;
if !self.collections.contains_key(name).unwrap() {
new = true;
}
let value = bincode::serialize(collection).unwrap();
self.collections.insert(name, value).unwrap();
if new {
self.count += 1;
}
}
pub fn delete_collection(&mut self, name: &str) {
self.collections.remove(name).unwrap();
self.count -= 1;
}
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
}