use crate::{
Batch, Database, Entity, EntitySchema, Error, IndexValue, InsertInput, Query, Timestamp,
};
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<'_>]>;
}
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>>);
fn single_write_batch(entity: &EntitySchema) -> Batch {
if entity.has_managed() {
Batch::at(Timestamp::now())
} else {
Batch::new()
}
}
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: E::Key) -> Result<Option<E>, Error> {
self.read()?.get::<E>(key)
}
pub fn get_many<E: Entity>(&self, keys: &[E::Key]) -> 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> {
let components = key.components();
let values = components.as_ref();
if !K::Entity::SCHEMA
.index_by_name(K::INDEX)
.is_some_and(|index| index.is_unique_lookup(values.len()))
{
return Err(Error::InvalidQuery);
}
self.read()?
.query::<K::Entity>()
.using_index(K::INDEX, values)
.work_limit(1)
.try_one()
}
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 = single_write_batch(I::Entity::SCHEMA);
let row = batch.insert_input(input)?;
self.commit(batch)?;
Ok(row)
}
pub fn replace<E: Entity>(&self, row: &E) -> Result<(), Error> {
let mut batch = single_write_batch(E::SCHEMA);
batch.replace(row)?;
self.commit(batch)
}
pub fn delete<E: Entity>(&self, key: E::Key) -> 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)
}
}