Skip to main content

sea_orm_relations_kit/
related.rs

1//! Counts, existence checks, aggregates and one-of-many for `SeaORM`'s own relations:
2//! anything with a `Related<R>` impl, direct (`has_many`, `has_one`, `belongs_to`) or
3//! through a junction table (`via`).
4//!
5//! Each function takes a page of owners and answers for all of them in one query,
6//! in the order of the owners.
7
8use std::collections::HashMap;
9use std::str::FromStr;
10
11use sea_orm::{
12    sea_query::{
13        DynIden, Expr, ExprTrait, Func, IntoIden, JoinType, Query, SelectStatement, TableRef,
14    },
15    ConnectionTrait, DbBackend, DbErr, EntityTrait, Identity, ModelTrait, QueryResult, QuerySelect,
16    QueryTrait, Related, Select, Value,
17};
18
19use crate::key::{key_or_error, primary_column, Key};
20use crate::morph::keys_of;
21use crate::of_many::{self, Pick, Source};
22
23/// An aggregate over a column of the related rows.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Aggregate {
26    /// `SUM(column)`
27    Sum,
28    /// `AVG(column)`
29    Avg,
30    /// `MIN(column)`
31    Min,
32    /// `MAX(column)`
33    Max,
34}
35
36impl Aggregate {
37    pub(crate) fn of(self, expr: Expr) -> Expr {
38        match self {
39            Self::Sum => Func::sum(expr).into(),
40            Self::Avg => Func::avg(expr).into(),
41            Self::Min => Func::min(expr).into(),
42            Self::Max => Func::max(expr).into(),
43        }
44    }
45}
46
47/// How many related rows each owner has: `[3, 0, 1]` for three posts.
48///
49/// ```no_run
50/// # mod posts { use sea_orm::entity::prelude::*;
51/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
52/// #   #[sea_orm(table_name = "posts")]
53/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32 }
54/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
55/// #   pub enum Relation { #[sea_orm(has_many = "super::comments::Entity")] Comments }
56/// #   impl Related<super::comments::Entity> for Entity {
57/// #     fn to() -> RelationDef { Relation::Comments.def() } }
58/// #   impl ActiveModelBehavior for ActiveModel {} }
59/// # mod comments { use sea_orm::entity::prelude::*;
60/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
61/// #   #[sea_orm(table_name = "comments")]
62/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32, pub post_id: i32 }
63/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
64/// #   pub enum Relation {
65/// #     #[sea_orm(belongs_to = "super::posts::Entity", from = "Column::PostId", to = "super::posts::Column::Id")]
66/// #     Post }
67/// #   impl Related<super::posts::Entity> for Entity {
68/// #     fn to() -> RelationDef { Relation::Post.def() } }
69/// #   impl ActiveModelBehavior for ActiveModel {} }
70/// use sea_orm::{DatabaseConnection, DbErr, EntityTrait, PaginatorTrait};
71/// use sea_orm_relations_kit::count_related;
72///
73/// async fn page(db: &DatabaseConnection) -> Result<(), DbErr> {
74///     let posts = posts::Entity::find().all(db).await?;
75///     let comments = count_related::<comments::Entity, _, _>(db, &posts).await?;
76///     for (post, count) in posts.iter().zip(comments) {
77///         println!("{}: {count} comments", post.id);
78///     }
79///     Ok(())
80/// }
81/// # fn main() {}
82/// ```
83///
84/// # Errors
85///
86/// On a database error, or when the relation is keyed by several columns.
87pub async fn count_related<R, O, Db>(db: &Db, owners: &[O]) -> Result<Vec<u64>, DbErr>
88where
89    R: EntityTrait,
90    O: ModelTrait<Entity: Related<R>> + Sync,
91    Db: ConnectionTrait,
92{
93    let totals = grouped::<R, O, Db>(db, owners, None, Expr::cust("COUNT(*)")).await?;
94    totals.per_owner(0, read_count)
95}
96
97/// [`count_related`] counting only the related rows `related` matches.
98///
99/// # Errors
100///
101/// On a database error, or when the relation is keyed by several columns.
102pub async fn count_related_with<R, O, Db>(
103    db: &Db,
104    owners: &[O],
105    related: Select<R>,
106) -> Result<Vec<u64>, DbErr>
107where
108    R: EntityTrait,
109    O: ModelTrait<Entity: Related<R>> + Sync,
110    Db: ConnectionTrait,
111{
112    let totals = grouped::<R, O, Db>(db, owners, Some(related), Expr::cust("COUNT(*)")).await?;
113    totals.per_owner(0, read_count)
114}
115
116/// Whether each owner has any related row.
117///
118/// # Errors
119///
120/// On a database error, or when the relation is keyed by several columns.
121pub async fn exists_related<R, O, Db>(db: &Db, owners: &[O]) -> Result<Vec<bool>, DbErr>
122where
123    R: EntityTrait,
124    O: ModelTrait<Entity: Related<R>> + Sync,
125    Db: ConnectionTrait,
126{
127    Ok(count_related::<R, O, Db>(db, owners)
128        .await?
129        .into_iter()
130        .map(|count| count > 0)
131        .collect())
132}
133
134/// `SUM`, `AVG`, `MIN` or `MAX` of `column` over each owner's related rows, as `f64`;
135/// `None` for an owner without related rows.
136///
137/// # Errors
138///
139/// On a database error, or when the relation is keyed by several columns.
140pub async fn aggregate_related<R, O, Db>(
141    db: &Db,
142    owners: &[O],
143    column: R::Column,
144    aggregate: Aggregate,
145) -> Result<Vec<Option<f64>>, DbErr>
146where
147    R: EntityTrait,
148    O: ModelTrait<Entity: Related<R>> + Sync,
149    Db: ConnectionTrait,
150{
151    let path = Path::of::<O::Entity, R>()?;
152    let target = if path.junction.is_some() {
153        Expr::col((R::default(), column))
154    } else {
155        Expr::col((ROWS, column))
156    };
157    let total = as_double(db.get_database_backend(), aggregate.of(target));
158    let totals = grouped::<R, O, Db>(db, owners, None, total).await?;
159    totals.per_owner(None, |row| row.try_get::<Option<f64>>("", "total"))
160}
161
162/// For each owner, the related row with the largest (`Pick::Max`) or smallest
163/// (`Pick::Min`) `column`, in one query. Only for direct relations (`has_many`).
164///
165/// # Errors
166///
167/// On a database error, or when the relation goes through a junction table or is
168/// keyed by several columns.
169pub async fn of_many<R, O, Db>(
170    db: &Db,
171    owners: &[O],
172    column: R::Column,
173    pick: Pick,
174) -> Result<Vec<Option<R::Model>>, DbErr>
175where
176    R: EntityTrait,
177    R::Model: Sync,
178    O: ModelTrait<Entity: Related<R>> + Sync,
179    Db: ConnectionTrait,
180{
181    let path = Path::of::<O::Entity, R>()?;
182    if path.junction.is_some() {
183        return Err(DbErr::Custom(
184            "one-of-many picks from a direct relation, not one through a junction table".into(),
185        ));
186    }
187    let owner_column = R::Column::from_str(&path.column.to_string()).map_err(|_| {
188        DbErr::Custom(format!(
189            "`{}` is not a column of the related entity",
190            path.column
191        ))
192    })?;
193    let (values, keys) = owner_values(owners, &path)?;
194    let source = Source::<R> {
195        owner_column,
196        scope: None,
197    };
198    of_many::pick(db, &source, values, &keys, column, pick).await
199}
200
201/// The latest related row of each owner by `column`: [`of_many`] with [`Pick::Max`].
202///
203/// # Errors
204///
205/// As [`of_many`].
206pub async fn latest_of_many<R, O, Db>(
207    db: &Db,
208    owners: &[O],
209    column: R::Column,
210) -> Result<Vec<Option<R::Model>>, DbErr>
211where
212    R: EntityTrait,
213    R::Model: Sync,
214    O: ModelTrait<Entity: Related<R>> + Sync,
215    Db: ConnectionTrait,
216{
217    of_many::<R, O, Db>(db, owners, column, Pick::Max).await
218}
219
220/// The oldest related row of each owner by `column`: [`of_many`] with [`Pick::Min`].
221///
222/// # Errors
223///
224/// As [`of_many`].
225pub async fn oldest_of_many<R, O, Db>(
226    db: &Db,
227    owners: &[O],
228    column: R::Column,
229) -> Result<Vec<Option<R::Model>>, DbErr>
230where
231    R: EntityTrait,
232    R::Model: Sync,
233    O: ModelTrait<Entity: Related<R>> + Sync,
234    Db: ConnectionTrait,
235{
236    of_many::<R, O, Db>(db, owners, column, Pick::Min).await
237}
238
239/// The alias of the counted table in the grouped queries.
240const ROWS: &str = "related_rows";
241
242/// The rows to count for a relation and how they point at the owner.
243struct Path {
244    /// The owner's column the related rows point at (usually its primary key).
245    owner_column: DynIden,
246    /// The table holding the rows to count: the related table, or the junction.
247    table: TableRef,
248    /// The column of `table` holding the owner's key.
249    column: DynIden,
250    /// Through a junction: the junction's column pointing at the related table, and
251    /// the related table's column it points at.
252    junction: Option<(DynIden, DynIden)>,
253}
254
255impl Path {
256    fn of<E: Related<R>, R: EntityTrait>() -> Result<Self, DbErr> {
257        let Some(via) = E::via() else {
258            let to = E::to();
259            return Ok(Self {
260                owner_column: single(&to.from_col)?,
261                table: to.to_tbl,
262                column: single(&to.to_col)?,
263                junction: None,
264            });
265        };
266        Ok(Self {
267            owner_column: single(&via.from_col)?,
268            table: via.to_tbl,
269            column: single(&via.to_col)?,
270            junction: Some((single(&E::to().from_col)?, single(&E::to().to_col)?)),
271        })
272    }
273}
274
275fn single(identity: &Identity) -> Result<DynIden, DbErr> {
276    match identity {
277        Identity::Unary(column) => Ok(column.clone()),
278        _ => Err(DbErr::Custom(
279            "relations keyed by several columns are not supported".into(),
280        )),
281    }
282}
283
284/// The values of the owners' linking column, for `IN (...)`, and their keys. A `NULL`
285/// link (an optional `belongs_to`) has no related rows; a value that cannot be a key
286/// is an error rather than a silent zero.
287fn owner_values<O: ModelTrait>(
288    owners: &[O],
289    path: &Path,
290) -> Result<(Vec<Value>, Vec<Option<Key>>), DbErr> {
291    let name = path.owner_column.to_string();
292    let column = <O::Entity as EntityTrait>::Column::from_str(&name)
293        .map_err(|_| DbErr::Custom(format!("`{name}` is not a column of the owner entity")))?;
294    let mut values = Vec::with_capacity(owners.len());
295    let mut keys = Vec::with_capacity(owners.len());
296    for owner in owners {
297        let value = owner.get(column);
298        if value.is_some() {
299            keys.push(Some(key_or_error(&value, &name)?));
300            values.push(value);
301        } else {
302            keys.push(None);
303        }
304    }
305    Ok((values, keys))
306}
307
308/// `SELECT owner AS owner_key, <total> AS total FROM rows WHERE owner IN (...) GROUP BY
309/// owner`, one result per owner (or `None` when it has no rows).
310async fn grouped<R, O, Db>(
311    db: &Db,
312    owners: &[O],
313    related: Option<Select<R>>,
314    total: Expr,
315) -> Result<Grouped, DbErr>
316where
317    R: EntityTrait,
318    O: ModelTrait<Entity: Related<R>> + Sync,
319    Db: ConnectionTrait,
320{
321    let path = Path::of::<O::Entity, R>()?;
322    let (values, keys) = owner_values(owners, &path)?;
323    if values.is_empty() {
324        return Ok(Grouped {
325            keys,
326            rows: HashMap::new(),
327        });
328    }
329
330    let owner = (ROWS, path.column.clone());
331    let mut query: SelectStatement = Query::select();
332    query
333        .expr_as(Expr::col(owner.clone()), "owner_key")
334        .expr_as(total, "total")
335        .from_as(path.table.clone(), ROWS.into_iden())
336        .and_where(Expr::col(owner.clone()).is_in(values))
337        .group_by_col(owner);
338    if let Some((junction, target)) = &path.junction {
339        query.join(
340            JoinType::InnerJoin,
341            R::default(),
342            Expr::col((ROWS, junction.clone())).equals((R::default(), target.clone())),
343        );
344    }
345    if let Some(related) = related {
346        // Through a junction, its column points at a column of the related rows;
347        // otherwise the counted rows are the related rows themselves.
348        let condition = match &path.junction {
349            Some((junction, target)) => Expr::col((ROWS, junction.clone())).in_subquery(
350                related
351                    .select_only()
352                    .expr(Expr::col(target.clone()))
353                    .into_query(),
354            ),
355            None => Expr::col((ROWS, primary_column::<R>())).in_subquery(keys_of(related)),
356        };
357        query.and_where(condition);
358    }
359
360    let mut rows = HashMap::new();
361    for row in db.query_all(&query).await? {
362        rows.insert(Key::read(&row, "owner_key")?, row);
363    }
364    Ok(Grouped { keys, rows })
365}
366
367/// The result rows of a grouped query, keyed by owner, and the owners' keys in order.
368struct Grouped {
369    keys: Vec<Option<Key>>,
370    rows: HashMap<Key, QueryResult>,
371}
372
373impl Grouped {
374    /// `read` applied to each owner's row, in the order of the owners; `missing` for
375    /// owners without one.
376    fn per_owner<T>(
377        &self,
378        missing: T,
379        read: impl Fn(&QueryResult) -> Result<T, DbErr>,
380    ) -> Result<Vec<T>, DbErr>
381    where
382        T: Clone,
383    {
384        self.keys
385            .iter()
386            .map(|key| {
387                key.as_ref()
388                    .and_then(|key| self.rows.get(key))
389                    .map_or_else(|| Ok(missing.clone()), &read)
390            })
391            .collect()
392    }
393}
394
395fn read_count(row: &QueryResult) -> Result<u64, DbErr> {
396    row.try_get::<i64>("", "total").map(i64::unsigned_abs)
397}
398
399/// `CAST(expr AS DOUBLE PRECISION)`, so every backend returns a float for any
400/// numeric column.
401pub fn as_double(backend: DbBackend, expr: Expr) -> Expr {
402    let double = match backend {
403        DbBackend::MySql => "DOUBLE",
404        _ => "DOUBLE PRECISION",
405    };
406    Func::cast_as(expr, double).into()
407}