use super::*;
pub struct Database {
collections: Db,
count: usize,
}
impl Database {
pub fn new(path: &str) -> Result<Self, Box<dyn Error>> {
if Path::new(path).exists() {
remove_dir_all(path)?;
}
let config = sled::Config::new().path(path);
let collections = config.open()?;
Ok(Self { collections, count: 0 })
}
pub fn open(path: &str) -> Result<Self, Box<dyn Error>> {
let collections = sled::open(path)?;
let count = collections.len();
Ok(Self { collections, count })
}
pub fn create_collection(
&mut self,
name: &str,
config: Option<&Config>,
records: Option<&[Record]>,
) -> Result<Collection, Box<dyn Error>> {
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)?;
Ok(collection)
}
pub fn get_collection(
&self,
name: &str,
) -> Result<Collection, Box<dyn Error>> {
let value = self.collections.get(name)?;
match value {
Some(value) => Ok(bincode::deserialize(&value)?),
None => Err(err::COLLECTION_NOT_FOUND.into()),
}
}
pub fn save_collection(
&mut self,
name: &str,
collection: &Collection,
) -> Result<(), Box<dyn Error>> {
let mut new = false;
if !self.collections.contains_key(name)? {
new = true;
}
let value = bincode::serialize(collection)?;
self.collections.insert(name, value)?;
if new {
self.count += 1;
}
Ok(())
}
pub fn delete_collection(
&mut self,
name: &str,
) -> Result<(), Box<dyn Error>> {
self.collections.remove(name)?;
self.count -= 1;
Ok(())
}
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
}