Skip to main content

sea_orm_relations_kit/
of_many.rs

1//! One related row per owner, picked by the largest or smallest value of a column:
2//! the latest comment of each post, the cheapest price of each product.
3
4use std::collections::HashMap;
5
6use sea_orm::{
7    sea_query::{Expr, ExprTrait, Func, JoinType, Query, SelectStatement},
8    ColumnTrait, ConnectionTrait, DbErr, EntityTrait, ModelTrait, QueryFilter, Value,
9};
10
11use crate::key::{primary_column, Key};
12
13/// Which end of the column to pick.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Pick {
16    /// The row with the largest value: the latest by date or id.
17    Max,
18    /// The row with the smallest value: the oldest, the cheapest.
19    Min,
20}
21
22impl Pick {
23    fn of(self, expr: Expr) -> Expr {
24        match self {
25            Self::Max => Func::max(expr).into(),
26            Self::Min => Func::min(expr).into(),
27        }
28    }
29}
30
31/// Where the related rows live and how they point at their owner.
32pub struct Source<R: EntityTrait> {
33    /// The column of `R` holding the owner's key.
34    pub owner_column: R::Column,
35    /// An extra `column = value` every row must match, such as a morph type.
36    pub scope: Option<(R::Column, &'static str)>,
37}
38
39/// For each owner key in `values`, the row of `R` with the largest (or smallest)
40/// `column`; ties go to the row with the largest (or smallest) primary key. Rows
41/// where `column` is `NULL` are never picked, so an owner whose rows all have `NULL`
42/// there gets `None`.
43///
44/// One query:
45///
46/// ```sql
47/// SELECT * FROM r WHERE r.id IN (
48///   SELECT MAX(picked.id) FROM r AS picked
49///   JOIN (SELECT owner, MAX(column) AS value FROM r WHERE owner IN (...) GROUP BY owner) AS best
50///     ON picked.owner = best.owner AND picked.column = best.value
51///   GROUP BY picked.owner)
52/// ```
53pub async fn pick<R, Db>(
54    db: &Db,
55    source: &Source<R>,
56    values: Vec<Value>,
57    keys: &[Option<Key>],
58    column: R::Column,
59    pick: Pick,
60) -> Result<Vec<Option<R::Model>>, DbErr>
61where
62    R: EntityTrait,
63    R::Model: Sync,
64    Db: ConnectionTrait,
65{
66    if values.is_empty() {
67        return Ok(keys.iter().map(|_| None).collect());
68    }
69    let table = R::default();
70    let owner = source.owner_column;
71    let id = primary_column::<R>();
72
73    let mut best = Query::select();
74    best.column(owner)
75        .expr_as(pick.of(Expr::col(column)), "picked_value")
76        .from(table)
77        .and_where(Expr::col(owner).is_in(values));
78    if let Some((scope_column, scope_value)) = source.scope {
79        best.and_where(Expr::col(scope_column).eq(scope_value));
80    }
81    best.group_by_col(owner);
82
83    let mut picked: SelectStatement = Query::select();
84    picked
85        .expr(pick.of(Expr::col(("picked", id))))
86        .from_as(table, "picked")
87        .join_subquery(
88            JoinType::InnerJoin,
89            best,
90            "best",
91            Expr::col(("picked", owner))
92                .equals(("best", owner))
93                .and(Expr::col(("picked", column)).equals(("best", "picked_value"))),
94        );
95    if let Some((scope_column, scope_value)) = source.scope {
96        picked.and_where(Expr::col(("picked", scope_column)).eq(scope_value));
97    }
98    picked.group_by_col(("picked", owner));
99
100    let rows = R::find().filter(id.in_subquery(picked)).all(db).await?;
101    let by_owner: HashMap<Key, R::Model> = rows
102        .into_iter()
103        .filter_map(|row| Some((Key::from_value(&row.get(owner))?, row)))
104        .collect();
105    Ok(keys
106        .iter()
107        .map(|key| key.as_ref().and_then(|key| by_owner.get(key).cloned()))
108        .collect())
109}