use super::*;
#[cfg_attr(feature = "py", pyclass(module = "oasysdb.database"))]
pub struct Database {
collections: Db,
count: usize,
}
#[cfg_attr(feature = "py", pymethods)]
impl Database {
#[cfg(feature = "py")]
#[staticmethod]
#[pyo3(name = "new")]
fn py_new(path: &str) -> PyResult<Self> {
Self::new(path).map_err(|e| e.into())
}
#[cfg(feature = "py")]
#[new]
fn py_open(path: &str) -> PyResult<Self> {
Self::open(path).map_err(|e| e.into())
}
pub fn get_collection(&self, name: &str) -> Result<Collection, Error> {
let value = self.collections.get(name)?;
match value {
Some(value) => Ok(bincode::deserialize(&value)?),
None => Err(Error::collection_not_found()),
}
}
pub fn save_collection(
&mut self,
name: &str,
collection: &Collection,
) -> Result<(), 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<(), 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
}
#[cfg(feature = "py")]
fn __len__(&self) -> usize {
self.len()
}
}
impl Database {
pub fn new(path: &str) -> Result<Self, 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, Error> {
let collections = sled::open(path)?;
let count = collections.len();
Ok(Self { collections, count })
}
}