use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use crate::{Column, Executor, Model, Result, Select, Value};
fn key(value: Option<Value>) -> Option<String> {
value.filter(|v| !v.is_null()).map(|v| v.to_string())
}
fn distinct_values<M: Model>(records: &[M], column: &str) -> Vec<Value> {
let mut seen = std::collections::HashSet::new();
records
.iter()
.filter_map(|r| r.value_of(column))
.filter(|v| !v.is_null() && seen.insert(v.to_string()))
.collect()
}
pub struct BelongsTo<C, P> {
foreign_key: &'static str,
_models: PhantomData<fn() -> (C, P)>,
}
impl<C: Model, P: Model> BelongsTo<C, P> {
pub const fn new(foreign_key: Column<C>) -> Self {
Self {
foreign_key: foreign_key.name(),
_models: PhantomData,
}
}
pub const fn foreign_key(&self) -> Column<C> {
Column::new(self.foreign_key)
}
pub fn query(&self, child: &C) -> Select<P> {
match child.value_of(self.foreign_key).filter(|v| !v.is_null()) {
Some(fk) => P::filter(P::primary_key_column().eq(fk)),
None => P::filter(crate::Expr::none()),
}
}
pub async fn load<'e, E: Executor<'e>>(
&self,
executor: E,
children: &[C],
) -> Result<One<C, P>> {
let ids = distinct_values(children, self.foreign_key);
let parents = if ids.is_empty() {
Vec::new()
} else {
P::filter(P::primary_key_column().is_in(ids))
.all(executor)
.await?
};
let map = parents
.into_iter()
.filter_map(|p| key(Some(p.primary_key())).map(|k| (k, p)))
.collect();
Ok(One::new(map, self.foreign_key))
}
}
pub struct HasMany<P, C> {
foreign_key: &'static str,
_models: PhantomData<fn() -> (P, C)>,
}
impl<P: Model, C: Model> HasMany<P, C> {
pub const fn new(foreign_key: Column<C>) -> Self {
Self {
foreign_key: foreign_key.name(),
_models: PhantomData,
}
}
pub const fn foreign_key(&self) -> Column<C> {
Column::new(self.foreign_key)
}
pub fn query(&self, parent: &P) -> Select<C> {
C::filter(self.foreign_key().eq(parent.primary_key()))
}
pub async fn load<'e, E: Executor<'e>>(
&self,
executor: E,
parents: &[P],
) -> Result<Many<P, C>> {
self.load_from(executor, parents, C::query()).await
}
pub async fn load_from<'e, E: Executor<'e>>(
&self,
executor: E,
parents: &[P],
base: Select<C>,
) -> Result<Many<P, C>> {
let ids = distinct_values(parents, P::PRIMARY_KEY);
let children = if ids.is_empty() {
Vec::new()
} else {
base.filter(self.foreign_key().is_in(ids))
.all(executor)
.await?
};
let mut map: HashMap<String, Vec<C>> = HashMap::new();
for child in children {
if let Some(k) = key(child.value_of(self.foreign_key)) {
map.entry(k).or_default().push(child);
}
}
Ok(Many::new(map, P::PRIMARY_KEY))
}
}
pub struct HasOne<P, C> {
foreign_key: &'static str,
_models: PhantomData<fn() -> (P, C)>,
}
impl<P: Model, C: Model> HasOne<P, C> {
pub const fn new(foreign_key: Column<C>) -> Self {
Self {
foreign_key: foreign_key.name(),
_models: PhantomData,
}
}
pub const fn foreign_key(&self) -> Column<C> {
Column::new(self.foreign_key)
}
pub fn query(&self, parent: &P) -> Select<C> {
C::filter(self.foreign_key().eq(parent.primary_key()))
}
pub async fn load<'e, E: Executor<'e>>(&self, executor: E, parents: &[P]) -> Result<One<P, C>> {
let ids = distinct_values(parents, P::PRIMARY_KEY);
let children = if ids.is_empty() {
Vec::new()
} else {
C::filter(self.foreign_key().is_in(ids))
.all(executor)
.await?
};
let map = children
.into_iter()
.filter_map(|c| key(c.value_of(self.foreign_key)).map(|k| (k, c)))
.collect();
Ok(One::new(map, P::PRIMARY_KEY))
}
}
pub struct One<O, T> {
map: HashMap<String, T>,
owner_key: &'static str,
_owner: PhantomData<fn() -> O>,
}
impl<O: Model, T> One<O, T> {
fn new(map: HashMap<String, T>, owner_key: &'static str) -> Self {
Self {
map,
owner_key,
_owner: PhantomData,
}
}
pub fn get(&self, owner: &O) -> Option<&T> {
key(owner.value_of(self.owner_key)).and_then(|k| self.map.get(&k))
}
pub fn take(&mut self, owner: &O) -> Option<T> {
key(owner.value_of(self.owner_key)).and_then(|k| self.map.remove(&k))
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn values(&self) -> impl Iterator<Item = &T> {
self.map.values()
}
}
pub struct Many<O, T> {
map: HashMap<String, Vec<T>>,
owner_key: &'static str,
_owner: PhantomData<fn() -> O>,
}
impl<O: Model, T> Many<O, T> {
fn new(map: HashMap<String, Vec<T>>, owner_key: &'static str) -> Self {
Self {
map,
owner_key,
_owner: PhantomData,
}
}
pub fn get(&self, owner: &O) -> &[T] {
key(owner.value_of(self.owner_key))
.and_then(|k| self.map.get(&k))
.map_or(&[], Vec::as_slice)
}
pub fn take(&mut self, owner: &O) -> Vec<T> {
key(owner.value_of(self.owner_key))
.and_then(|k| self.map.remove(&k))
.unwrap_or_default()
}
pub fn len(&self) -> usize {
self.map.values().map(Vec::len).sum()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn values(&self) -> impl Iterator<Item = &T> {
self.map.values().flatten()
}
}
macro_rules! relation_boilerplate {
($($ty:ident<$a:ident, $b:ident>),*) => {$(
impl<$a, $b> Clone for $ty<$a, $b> {
fn clone(&self) -> Self {
*self
}
}
impl<$a, $b> Copy for $ty<$a, $b> {}
impl<$a, $b> fmt::Debug for $ty<$a, $b> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(stringify!($ty))
.field("foreign_key", &self.foreign_key)
.finish()
}
}
)*};
}
relation_boilerplate!(BelongsTo<C, P>, HasMany<P, C>, HasOne<P, C>);
impl<O, T: fmt::Debug> fmt::Debug for One<O, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.map.iter()).finish()
}
}
impl<O, T: fmt::Debug> fmt::Debug for Many<O, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.map.iter()).finish()
}
}