sea-orm-relations-kit 0.1.0

Laravel-style relations for SeaORM: polymorphic relations, many-to-many attach/sync/toggle, relation counts and latest-of-many
Documentation
//! One related row per owner, picked by the largest or smallest value of a column:
//! the latest comment of each post, the cheapest price of each product.

use std::collections::HashMap;

use sea_orm::{
    sea_query::{Expr, ExprTrait, Func, JoinType, Query, SelectStatement},
    ColumnTrait, ConnectionTrait, DbErr, EntityTrait, ModelTrait, QueryFilter, Value,
};

use crate::key::{primary_column, Key};

/// Which end of the column to pick.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pick {
    /// The row with the largest value: the latest by date or id.
    Max,
    /// The row with the smallest value: the oldest, the cheapest.
    Min,
}

impl Pick {
    fn of(self, expr: Expr) -> Expr {
        match self {
            Self::Max => Func::max(expr).into(),
            Self::Min => Func::min(expr).into(),
        }
    }
}

/// Where the related rows live and how they point at their owner.
pub struct Source<R: EntityTrait> {
    /// The column of `R` holding the owner's key.
    pub owner_column: R::Column,
    /// An extra `column = value` every row must match, such as a morph type.
    pub scope: Option<(R::Column, &'static str)>,
}

/// For each owner key in `values`, the row of `R` with the largest (or smallest)
/// `column`; ties go to the row with the largest (or smallest) primary key. Rows
/// where `column` is `NULL` are never picked, so an owner whose rows all have `NULL`
/// there gets `None`.
///
/// One query:
///
/// ```sql
/// SELECT * FROM r WHERE r.id IN (
///   SELECT MAX(picked.id) FROM r AS picked
///   JOIN (SELECT owner, MAX(column) AS value FROM r WHERE owner IN (...) GROUP BY owner) AS best
///     ON picked.owner = best.owner AND picked.column = best.value
///   GROUP BY picked.owner)
/// ```
pub async fn pick<R, Db>(
    db: &Db,
    source: &Source<R>,
    values: Vec<Value>,
    keys: &[Option<Key>],
    column: R::Column,
    pick: Pick,
) -> Result<Vec<Option<R::Model>>, DbErr>
where
    R: EntityTrait,
    R::Model: Sync,
    Db: ConnectionTrait,
{
    if values.is_empty() {
        return Ok(keys.iter().map(|_| None).collect());
    }
    let table = R::default();
    let owner = source.owner_column;
    let id = primary_column::<R>();

    let mut best = Query::select();
    best.column(owner)
        .expr_as(pick.of(Expr::col(column)), "picked_value")
        .from(table)
        .and_where(Expr::col(owner).is_in(values));
    if let Some((scope_column, scope_value)) = source.scope {
        best.and_where(Expr::col(scope_column).eq(scope_value));
    }
    best.group_by_col(owner);

    let mut picked: SelectStatement = Query::select();
    picked
        .expr(pick.of(Expr::col(("picked", id))))
        .from_as(table, "picked")
        .join_subquery(
            JoinType::InnerJoin,
            best,
            "best",
            Expr::col(("picked", owner))
                .equals(("best", owner))
                .and(Expr::col(("picked", column)).equals(("best", "picked_value"))),
        );
    if let Some((scope_column, scope_value)) = source.scope {
        picked.and_where(Expr::col(("picked", scope_column)).eq(scope_value));
    }
    picked.group_by_col(("picked", owner));

    let rows = R::find().filter(id.in_subquery(picked)).all(db).await?;
    let by_owner: HashMap<Key, R::Model> = rows
        .into_iter()
        .filter_map(|row| Some((Key::from_value(&row.get(owner))?, row)))
        .collect();
    Ok(keys
        .iter()
        .map(|key| key.as_ref().and_then(|key| by_owner.get(key).cloned()))
        .collect())
}