use std::any::{Any, TypeId};
use axum::http::request::Parts;
use futures_util::future::BoxFuture;
use super::__query;
use super::{AnyRelation, Column, Model};
use crate::Result;
use crate::db::{Builder, Condition, IntoExpr, col};
use crate::routing::{__Parameter, RouteModel};
use crate::str::Str;
#[doc(hidden)]
pub fn __find_by_route_key<M: Model>(key: impl IntoExpr) -> impl Future<Output = Result<Option<M>>> + Send {
let route_key = col(format!("{}.{}", M::META.table, M::META.route_key));
__query::<M>().filter(route_key.eq(key)).first()
}
#[doc(hidden)]
pub async fn __bind<M: RouteModel>(parts: &Parts) -> Result<M> {
crate::routing::find_model(parts, M::PARAMETER).await
}
type ScopeQuery = for<'a> fn(&'a __Parameter, &'a [__Parameter]) -> BoxFuture<'a, Result<Box<dyn Any + Send>>>;
#[doc(hidden)]
#[derive(Debug)]
pub struct __RouteScope {
pub child: fn() -> TypeId,
pub parent: fn() -> TypeId,
pub parent_parameter: &'static str,
pub side: __Side,
pub field: &'static str,
pub name: &'static str,
pub filtered: bool,
pub query: ScopeQuery,
}
inventory::collect!(__RouteScope);
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum __Side {
Parent,
Child,
}
#[doc(hidden)]
pub async fn __find_in_route<M: Model>(
condition: Result<Condition>,
param: &__Parameter,
parents: &[__Parameter],
) -> Result<Option<M>> {
let condition = condition?;
let query = match parents.split_last() {
Some((parent, grandparents)) => match scope(TypeId::of::<M>(), param, parent)? {
Some(scope) => *(scope.query)(parent, grandparents)
.await?
.downcast::<Builder<M>>()
.expect("a route scope queries its child"),
None => __query::<M>(),
},
None => __query::<M>(),
};
query.filter(condition).first().await
}
fn scope(child: TypeId, param: &__Parameter, parent: &__Parameter) -> Result<Option<&'static __RouteScope>> {
let scopes: Vec<&__RouteScope> = inventory::iter::<__RouteScope>
.into_iter()
.filter(|scope| (scope.child)() == child)
.collect();
let named: Vec<TypeId> = scopes
.iter()
.filter(|scope| scope.side == __Side::Child && scope.field == parent.name)
.map(|scope| (scope.parent)())
.collect();
let between: Vec<&__RouteScope> = scopes
.into_iter()
.filter(|scope| scope.parent_parameter == parent.name || named.contains(&(scope.parent)()))
.collect();
let plural = param.name.plural();
let find = |side: __Side, field: &str| {
between
.iter()
.find(|scope| scope.side == side && scope.field == field)
.copied()
};
let only = |side: __Side| {
let sides: Vec<&__RouteScope> = between.iter().filter(|scope| scope.side == side).copied().collect();
let unfiltered: Vec<&__RouteScope> = sides.iter().filter(|scope| !scope.filtered).copied().collect();
match (&sides[..], &unfiltered[..]) {
([scope], _) | (_, [scope]) => Some(*scope),
_ => None,
}
};
let chosen = find(__Side::Parent, &plural)
.or_else(|| find(__Side::Child, &parent.name))
.or_else(|| only(__Side::Parent))
.or_else(|| only(__Side::Child));
if chosen.is_none() && !between.is_empty() {
let mut names: Vec<String> = between.iter().map(|scope| format!("`{}`", scope.name)).collect();
names.sort();
return Err(crate::error::fail(format!(
"can't tell how `{{{}}}` belongs to `{{{}}}`: through {}. Name the parent's relationship after the \
parameter in the plural, as `{plural}`, or the child's after the parent's parameter, or call \
`without_scoped_bindings()` on the route",
param.name,
parent.name,
names.join(" or "),
)));
}
Ok(chosen)
}
#[doc(hidden)]
pub fn __scope_through<'a, P, C>(
relation: &'static dyn AnyRelation<P, C>,
parent: &'a __Parameter,
grandparents: &'a [__Parameter],
) -> BoxFuture<'a, Result<Box<dyn Any + Send>>>
where
P: Model + RouteModel,
C: Model,
{
Box::pin(async move {
let parent: P = crate::routing::find_model_at(parent, grandparents).await?;
Ok(Box::new(relation.query(&parent)) as Box<dyn Any + Send>)
})
}
#[doc(hidden)]
pub fn __scope_owned<'a, C, P, K>(
relation: &'static dyn AnyRelation<C, P>,
foreign: &'static str,
owner: Column<P, K>,
parent: &'a __Parameter,
grandparents: &'a [__Parameter],
) -> BoxFuture<'a, Result<Box<dyn Any + Send>>>
where
C: Model,
P: Model + RouteModel,
K: IntoExpr + Clone + Send + Sync + 'static,
{
Box::pin(async move {
let parent: P = crate::routing::find_model_at(parent, grandparents).await?;
let key = owner.get(&parent).clone();
let foreign = col(format!("{}.{}", C::META.table, foreign));
let mut query = __query::<C>().filter(foreign.eq(key.clone()));
if relation.condition().is_some() {
query = query.filter(relation.exists(__query::<P>().filter(owner.expr().eq(key))));
}
Ok(Box::new(query) as Box<dyn Any + Send>)
})
}
#[doc(hidden)]
pub mod __route_field {
use std::any::type_name;
use serde::de::DeserializeOwned;
use super::{Column, Model};
use crate::Result;
use crate::db::{Condition, Decode, IntoExpr};
use crate::routing::__Parameter;
use crate::url::RouteParam;
#[derive(Debug)]
pub struct Field<M, T>(pub Column<M, T>);
pub trait Routable<M> {
fn condition(&self, field: &str, param: &__Parameter) -> Result<Condition>;
fn param(&self, field: &str, model: &M) -> std::result::Result<String, String>;
}
impl<M, T> Routable<M> for Field<M, T>
where
M: Model,
T: DeserializeOwned + IntoExpr + Decode + RouteParam + Clone + Send + Sync + 'static,
{
fn condition(&self, field: &str, param: &__Parameter) -> Result<Condition> {
let value: T = crate::routing::parse_params(&[(param.name.clone(), param.value.clone())], |error| {
format!(
"the `{}` route parameter doesn't fit `{field}`'s `{}`: {error}",
param.name,
type_name::<T>()
)
})?;
Ok(self.0.eq(value))
}
fn param(&self, _field: &str, model: &M) -> std::result::Result<String, String> {
Ok(self.0.get(model).to_route_param())
}
}
pub trait Unroutable<M> {
fn condition(&self, field: &str, param: &__Parameter) -> Result<Condition>;
fn param(&self, field: &str, model: &M) -> std::result::Result<String, String>;
}
impl<M: Model, T> Unroutable<M> for &Field<M, T> {
fn condition(&self, field: &str, _param: &__Parameter) -> Result<Condition> {
Err(crate::error::fail(unroutable::<M, T>(field)))
}
fn param(&self, field: &str, _model: &M) -> std::result::Result<String, String> {
Err(unroutable::<M, T>(field))
}
}
fn unroutable<M: Model, T>(field: &str) -> String {
format!(
"a route can't name `{}`'s `{field}` field, as in `{{..:{field}}}`: its type, `{}`, must deserialize from \
a route parameter and implement `RouteParam`",
M::META.name,
type_name::<T>()
)
}
pub fn unknown<M: Model>(field: &str) -> String {
format!(
"`{}` has no `{field}` field for a route to find it by, as `{{..:{field}}}` asks",
M::META.name
)
}
}