laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
//! Route model binding, which resolves a handler argument of a model type from a route
//! parameter.

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
}

/// Builds a query of the related rows that a route parameter's parent model owns, from the
/// parameter before it and the parameters before that one.
type ScopeQuery = for<'a> fn(&'a __Parameter, &'a [__Parameter]) -> BoxFuture<'a, Result<Box<dyn Any + Send>>>;

/// One relationship that scopes a nested route binding.
///
/// `#[model]` registers one for each of a model's relationships. For a route with `{user}`
/// followed by `{post}`, `User::posts` scopes the post from the parent's side, and `Post::user`
/// scopes it from the child's side.
#[doc(hidden)]
#[derive(Debug)]
pub struct __RouteScope {
    pub child: fn() -> TypeId,
    pub parent: fn() -> TypeId,
    pub parent_parameter: &'static str,
    pub side: __Side,
    /// The relationship's field, such as `posts`.
    pub field: &'static str,
    /// The relationship's name as `route:list` shows it, such as `User::posts`.
    pub name: &'static str,
    /// Whether the relationship has a `filter`. A filtered relationship holds only some of the
    /// rows that an unfiltered relationship between the same models holds.
    pub filtered: bool,
    /// Builds a query of the child's rows that the parent owns, as a `Builder` of the child.
    pub query: ScopeQuery,
}

inventory::collect!(__RouteScope);

/// The model that declares a [`__RouteScope`]'s relationship.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum __Side {
    /// The parent's `#[has_one]`, `#[has_many]`, or `#[belongs_to_many]`.
    Parent,
    /// The child's `#[belongs_to]`.
    Child,
}

/// Finds the `M` that `param` names by `condition`, among the rows that the model of the
/// previous parameter owns.
///
/// When there are no `parents`, or no relationship connects the two models, it finds any `M`.
#[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
}

/// Returns the relationship that scopes the child model, bound by `param`, to the model that
/// `parent` names, or `None` when no relationship connects them.
///
/// The `parent` parameter names a model either by its own name, such as `{user}` for `User`, or
/// by a child's `#[belongs_to]` relationship with the same name, such as `Post::author` for
/// `{author}`.
///
/// When several relationships connect the two models, the first match in this order wins:
///
/// 1. The parent's relationship named after the plural of the child's parameter, such as
///    `User::posts` for `{post}`.
/// 2. The child's relationship named after the parent's parameter.
/// 3. The parent's only relationship to the child.
/// 4. The child's only relationship to the parent.
///
/// A relationship without a `filter` counts as the only one when every other relationship on its
/// side has a filter.
///
/// # Errors
///
/// Returns a `500` error when several relationships connect the two models and none of them is
/// named after the parameters.
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()
    };
    // A filtered relationship next to an unfiltered one, such as `Team::admins` next to
    // `Team::members`, holds some of its rows, so the unfiltered one owns the child.
    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)
}

/// Builds a parent-side scope: the rows of `C` that `relation` relates to the `P` that `parent`
/// names.
#[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>)
    })
}

/// Builds a child-side scope through the child's `#[belongs_to]` `relation`: the rows of `C`
/// whose `foreign` column holds the `owner` value of the `P` that `parent` names.
///
/// When `relation` has a `filter`, a parent that doesn't meet it owns no rows.
#[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()));
        // With a `filter`, the relation holds the parent only when the parent meets it...
        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>)
    })
}

/// How `#[model]` finds a model by the field that a route names, as in `{post:slug}`, and fills
/// that placeholder from a model.
///
/// When the column's type parses from a route parameter and can fill one, as a route key's type
/// does, `#[model]` uses `Routable`. Otherwise it uses `Unroutable`, which fails with a message
/// that names the field. Autoref specialization on `&Field<M, T>` picks between the two.
#[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>()
        )
    }

    /// Returns the error message for a route that names a field the model doesn't have.
    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
        )
    }
}