glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Associations loaded onto records already in hand, as Laravel's
//! `$books->load('author')`: `books = books.preload(:author)!` after a
//! query that didn't, in one query per association as a query's
//! `preload` does.

use std::future::Future;

use super::Association;
use super::assoc::Preload;
use super::{Expr, Query, ToValue, Value};
use crate::error::Result;
use crate::model::Model;

/// Loading associations for a list of records; in the prelude.
pub trait LoadedRecords<M: Model>: Sized {
    /// The records with `association` loaded for every one of them:
    /// `books.preload(:author)!`.
    fn preload<P: Into<Preload<M>>>(
        self,
        association: impl FnOnce(&M::Columns) -> P,
    ) -> impl Future<Output = Result<Vec<M>>> + Send;

    /// The records with a `has_many` counted for each:
    /// `authors.with_count(:books)!`.
    fn with_count<C>(
        self,
        association: impl FnOnce(&M::Columns) -> Association<M, C>,
    ) -> impl Future<Output = Result<Vec<M>>> + Send
    where
        M: 'static;
}

impl<M: Model + Send + 'static> LoadedRecords<M> for Vec<M> {
    fn preload<P: Into<Preload<M>>>(
        self,
        association: impl FnOnce(&M::Columns) -> P,
    ) -> impl Future<Output = Result<Vec<M>>> + Send {
        let preload: Preload<M> = association(&M::columns()).into();
        let mut records = self;
        async move {
            let conn = super::current()?;
            preload.run(&mut records, conn).await?;
            Ok(records)
        }
    }

    fn with_count<C>(
        self,
        association: impl FnOnce(&M::Columns) -> Association<M, C>,
    ) -> impl Future<Output = Result<Vec<M>>> + Send
    where
        M: 'static,
    {
        let preload = association(&M::columns()).counting();
        let mut records = self;
        async move {
            let preload = preload.ok_or_else(|| {
                crate::Error::internal(
                    "with_count counts a `has_many` association (not one `through` a join table)",
                )
            })?;
            let conn = super::current()?;
            preload.run(&mut records, conn).await?;
            Ok(records)
        }
    }
}

/// Records in hand by their keys, as Rails' `ids` and `find`, and back to
/// a query; in the prelude.
pub trait Records<M: Model> {
    /// The records' primary keys, in order: `books.ids()`. For numeric
    /// keys; `books.map(:id)` gives text or UUID ones.
    fn ids(&self) -> Vec<i64>;

    /// The record with this primary key, if it's in the list:
    /// `books.find_id(7)`. A key given as text (`params[:id]`) is parsed for
    /// a numeric key, as `Model.find` does.
    fn find_id(&self, id: impl ToValue) -> Option<&M>;

    /// A query for these same records, to go on with:
    /// `books.to_query().update_all(…)!`. The list's order isn't kept.
    fn to_query(&self) -> Query<M>;
}

impl<M: Model> Records<M> for [M] {
    fn ids(&self) -> Vec<i64> {
        self.iter()
            .filter_map(|record| match record.id_value() {
                Value::Int(id) => Some(id),
                _ => None,
            })
            .collect()
    }

    fn find_id(&self, id: impl ToValue) -> Option<&M> {
        let id = match id.to_value() {
            Value::Text(text) if M::INTEGER_KEY => Value::Int(text.trim().parse().ok()?),
            value => value,
        };
        self.iter().find(|record| record.id_value() == id)
    }

    fn to_query(&self) -> Query<M> {
        let values: Vec<Value> = self.iter().map(|record| record.id_value()).collect();
        Query::new().filter(|_| Expr::In {
            column: M::PRIMARY_KEY,
            values,
        })
    }
}