use crate::{Batch, Database, Entity, Error};
use std::{
cell::{Ref, RefCell},
rc::Rc,
};
#[derive(Clone)]
pub struct DatabaseSession(Rc<RefCell<Database>>);
impl DatabaseSession {
#[must_use]
pub fn new(database: Database) -> Self {
Self(Rc::new(RefCell::new(database)))
}
pub fn try_into_database(self) -> Result<Database, Self> {
Rc::try_unwrap(self.0)
.map(RefCell::into_inner)
.map_err(Self)
}
pub fn read(&self) -> Result<Ref<'_, Database>, Error> {
self.0.try_borrow().map_err(|_| Error::BorrowConflict)
}
pub fn get<E: Entity>(&self, key: E::Key) -> Result<Option<E>, Error> {
self.read()?.get::<E>(key)
}
pub fn commit(&self, batch: Batch) -> Result<(), Error> {
self.0
.try_borrow_mut()
.map_err(|_| Error::BorrowConflict)?
.commit(batch)
}
}