use crate::{Batch, Database, Entity, Error, IndexValue, InsertInput, Query};
use std::{
cell::{Ref, RefCell},
rc::Rc,
};
pub trait UniqueKey {
type Entity: Entity;
#[doc(hidden)]
const INDEX: &'static str;
#[doc(hidden)]
fn components(&self) -> impl AsRef<[IndexValue<'_>]>;
}
#[derive(Debug, PartialEq, Eq)]
pub enum InsertOutcome<E> {
Inserted(E),
AlreadyPresent,
}
pub trait QuerySession<E: Entity> {
fn entity_query<'a>(&self) -> Query<'a, E>;
}
impl<E: Entity> QuerySession<E> for DatabaseSession {
fn entity_query<'a>(&self) -> Query<'a, E> {
self.query()
}
}
#[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)
}
#[must_use]
pub fn query<'a, E: Entity>(&self) -> Query<'a, E> {
Query::from_session(self.0.clone())
}
pub fn get<E: Entity>(&self, key: impl Into<crate::Id<E>>) -> Result<Option<E>, Error> {
self.read()?.get::<E>(key)
}
pub fn get_many<E: Entity>(
&self,
keys: &[impl Copy + Into<crate::Id<E>>],
) -> Result<Vec<Option<E>>, Error> {
self.read()?.get_many::<E>(keys)
}
pub fn get_unique<K: UniqueKey>(&self, key: &K) -> Result<Option<K::Entity>, Error> {
self.read()?.get_unique(key)
}
pub fn insert<E: Entity>(&self, row: &E) -> Result<(), Error> {
let mut batch = Batch::new();
batch.insert(row)?;
self.commit(batch)
}
pub fn insert_input<I: InsertInput>(&self, input: I) -> Result<I::Entity, Error> {
let mut batch = Batch::new();
let row = batch.insert_input(input)?;
self.commit(batch)?;
Ok(row)
}
pub fn insert_if_absent<K: UniqueKey>(
&self,
input: impl InsertInput<Entity = K::Entity>,
) -> Result<InsertOutcome<K::Entity>, Error> {
self.0
.try_borrow_mut()
.map_err(|_| Error::BorrowConflict)?
.insert_if_absent::<K>(input)
}
pub fn replace<E: Entity>(&self, row: &E) -> Result<E, Error> {
let mut batch = Batch::new();
batch.replace(row)?;
self.commit_returning(batch, row.id())
}
pub fn delete<E: Entity>(&self, key: impl Into<crate::Id<E>>) -> Result<(), Error> {
let mut batch = Batch::new();
batch.delete::<E>(key)?;
self.commit(batch)
}
pub fn commit(&self, batch: Batch) -> Result<(), Error> {
self.0
.try_borrow_mut()
.map_err(|_| Error::BorrowConflict)?
.commit(batch)
}
pub fn commit_returning<E: Entity>(
&self,
batch: Batch,
key: impl Into<crate::Id<E>>,
) -> Result<E, Error> {
self.0
.try_borrow_mut()
.map_err(|_| Error::BorrowConflict)?
.commit_returning(batch, key)
}
}