Skip to main content

sea_orm_relations_kit/
morph.rs

1//! Polymorphic one-to-one and one-to-many relations, and resolving a child's owner.
2
3use std::collections::{BTreeMap, HashMap};
4
5use sea_orm::{
6    sea_query::{ColumnType, Expr, ExprTrait},
7    ActiveModelTrait, ColumnTrait, Condition, ConnectionTrait, DbErr, EntityTrait, FromQueryResult,
8    ModelTrait, QueryFilter, QueryResult, QuerySelect, QueryTrait, Select, Value,
9};
10
11use crate::key::{primary_column, require_key, values_for, Key};
12use crate::of_many::{self, Pick, Source};
13use crate::related::{as_double, Aggregate};
14use crate::target::MorphTarget;
15
16/// An entity that can own polymorphic children, with the name stored in their
17/// `*_type` column.
18///
19/// The name is a short, stable alias like `"post"`: Rust has no class names to store,
20/// and an alias survives renaming the entity or moving it to another module.
21///
22/// ```
23/// # mod posts { use sea_orm::entity::prelude::*;
24/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
25/// #   #[sea_orm(table_name = "posts")]
26/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32 }
27/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
28/// #   impl ActiveModelBehavior for ActiveModel {} }
29/// use sea_orm_relations_kit::Morphable;
30///
31/// impl Morphable for posts::Entity {
32///     const MORPH_TYPE: &'static str = "post";
33/// }
34/// ```
35pub trait Morphable: EntityTrait {
36    /// The value stored in the `*_type` column of this entity's children.
37    const MORPH_TYPE: &'static str;
38}
39
40/// The `*_type` and `*_id` columns of a polymorphic child: `commentable_type` and
41/// `commentable_id` on `comments`.
42///
43/// Declare it once per relation, as a constant next to the child entity:
44///
45/// ```
46/// # mod comments { use sea_orm::entity::prelude::*;
47/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
48/// #   #[sea_orm(table_name = "comments")]
49/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32,
50/// #     pub commentable_type: String, pub commentable_id: i64 }
51/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
52/// #   impl ActiveModelBehavior for ActiveModel {} }
53/// use sea_orm_relations_kit::Morph;
54///
55/// pub const COMMENTABLE: Morph<comments::Entity> =
56///     Morph::new(comments::Column::CommentableType, comments::Column::CommentableId);
57/// ```
58///
59/// From the owner it finds the children ([`find_for`](Self::find_for),
60/// [`load_for`](Self::load_for)); from a child it finds the owner
61/// ([`owner`](Self::owner), [`load_owners`](Self::load_owners)).
62#[derive(Clone, Copy, Debug)]
63pub struct Morph<C: EntityTrait> {
64    type_column: C::Column,
65    id_column: C::Column,
66}
67
68impl<C: EntityTrait> Morph<C> {
69    /// The relation stored in `type_column` and `id_column` of `C`.
70    pub const fn new(type_column: C::Column, id_column: C::Column) -> Self {
71        Self {
72            type_column,
73            id_column,
74        }
75    }
76
77    /// The `*_type` column.
78    pub const fn type_column(&self) -> C::Column {
79        self.type_column
80    }
81
82    /// The `*_id` column.
83    pub const fn id_column(&self) -> C::Column {
84        self.id_column
85    }
86}
87
88impl<C: EntityTrait> Morph<C>
89where
90    C::Model: Sync,
91{
92    // ---- From the child: its owner ------------------------------------------------
93
94    /// Points `child` at `owner` by setting both columns.
95    ///
96    /// # Errors
97    ///
98    /// When `owner`'s key does not fit the `*_id` column, or `owner` has no key yet.
99    pub fn associate<O>(&self, child: &mut C::ActiveModel, owner: &O) -> Result<(), DbErr>
100    where
101        O: ModelTrait<Entity: Morphable>,
102    {
103        let key = require_key(owner)?;
104        child.try_set(
105            self.type_column,
106            Value::String(Some(O::Entity::MORPH_TYPE.to_string())),
107        )?;
108        child.try_set(self.id_column, key.to_value_for(self.id_column)?)
109    }
110
111    /// Sets both columns to `NULL`, for a relation where the owner is optional.
112    ///
113    /// # Errors
114    ///
115    /// When a column is not nullable in the database; the error comes on save.
116    pub fn dissociate(&self, child: &mut C::ActiveModel) -> Result<(), DbErr> {
117        child.try_set(self.type_column, Value::String(None))?;
118        child.try_set(self.id_column, null_of(self.id_column))
119    }
120
121    /// The owner's morph type stored on `child`, `None` when it is `NULL`.
122    pub fn owner_type(&self, child: &C::Model) -> Option<String> {
123        match child.get(self.type_column) {
124            Value::String(Some(morph_type)) => Some(morph_type),
125            _ => None,
126        }
127    }
128
129    /// The owner's key stored on `child`, `None` when it is `NULL`.
130    pub fn owner_key(&self, child: &C::Model) -> Option<Key> {
131        Key::from_value(&child.get(self.id_column))
132    }
133
134    /// Whether `child` belongs to `owner`.
135    pub fn is_owned_by<O>(&self, child: &C::Model, owner: &O) -> bool
136    where
137        O: ModelTrait<Entity: Morphable>,
138    {
139        self.owner_type(child).as_deref() == Some(O::Entity::MORPH_TYPE)
140            && self.owner_key(child).is_some()
141            && self.owner_key(child) == Key::of(owner)
142    }
143
144    /// The owner of `child`, whichever entity it is.
145    ///
146    /// `T` is an enum of the possible owners, declared with
147    /// [`morph_target!`](crate::morph_target). `None` when the columns are `NULL` or
148    /// the owner row is gone.
149    ///
150    /// # Errors
151    ///
152    /// On a database error, or when the stored type is not one of `T`'s.
153    pub async fn owner<T, Db>(&self, db: &Db, child: &C::Model) -> Result<Option<T>, DbErr>
154    where
155        T: MorphTarget,
156        Db: ConnectionTrait,
157    {
158        let (Some(morph_type), Some(key)) = (self.owner_type(child), self.owner_key(child)) else {
159            return Ok(None);
160        };
161        let found = T::load_type(db, &morph_type, vec![key]).await?;
162        Ok(found.into_iter().next().map(|(_, owner)| owner))
163    }
164
165    /// The owners of many children, one query per owner type, in the order of
166    /// `children`. Children sharing an owner get a clone of it.
167    ///
168    /// # Errors
169    ///
170    /// On a database error, or when a stored type is not one of `T`'s.
171    pub async fn load_owners<T, Db>(
172        &self,
173        db: &Db,
174        children: &[C::Model],
175    ) -> Result<Vec<Option<T>>, DbErr>
176    where
177        T: MorphTarget + Clone,
178        Db: ConnectionTrait,
179    {
180        let links: Vec<Option<(String, Key)>> = children
181            .iter()
182            .map(|child| self.owner_type(child).zip(self.owner_key(child)))
183            .collect();
184
185        let mut keys_by_type: BTreeMap<&str, Vec<Key>> = BTreeMap::new();
186        for (morph_type, key) in links.iter().flatten() {
187            keys_by_type
188                .entry(morph_type)
189                .or_default()
190                .push(key.clone());
191        }
192
193        let mut owners: HashMap<(&str, Key), T> = HashMap::new();
194        for (morph_type, keys) in keys_by_type {
195            for (key, owner) in T::load_type(db, morph_type, keys).await? {
196                owners.insert((morph_type, key), owner);
197            }
198        }
199
200        Ok(links
201            .iter()
202            .map(|link| {
203                link.as_ref()
204                    .and_then(|(morph_type, key)| owners.get(&(morph_type.as_str(), key.clone())))
205                    .cloned()
206            })
207            .collect())
208    }
209
210    // ---- From the owner: its children ---------------------------------------------
211
212    /// `WHERE type = 'post' AND id = 15`: the children of `owner`, for any query on
213    /// `C`.
214    ///
215    /// # Errors
216    ///
217    /// When `owner`'s key does not fit the `*_id` column.
218    pub fn of<O>(&self, owner: &O) -> Result<Condition, DbErr>
219    where
220        O: ModelTrait<Entity: Morphable>,
221    {
222        let key = require_key(owner)?.to_value_for(self.id_column)?;
223        Ok(self.of_type::<O::Entity>().add(self.id_column.eq(key)))
224    }
225
226    /// `WHERE type = 'post'`: children of any owner of type `O`.
227    pub fn of_type<O: Morphable>(&self) -> Condition {
228        Condition::all().add(self.type_column.eq(O::MORPH_TYPE))
229    }
230
231    /// `WHERE type IN (...)`: children of owners of the given types.
232    pub fn of_types<'a>(&self, morph_types: impl IntoIterator<Item = &'a str>) -> Condition {
233        Condition::all().add(self.type_column.is_in(morph_types))
234    }
235
236    /// The children of `owner`, ready to filter, order and run.
237    ///
238    /// For a one-to-one relation take `.one(db)`; for the latest child order by a
239    /// column descending first.
240    ///
241    /// # Errors
242    ///
243    /// When `owner`'s key does not fit the `*_id` column.
244    pub fn find_for<O>(&self, owner: &O) -> Result<Select<C>, DbErr>
245    where
246        O: ModelTrait<Entity: Morphable>,
247    {
248        Ok(C::find().filter(self.of(owner)?))
249    }
250
251    /// The children of many owners in one query, in the order of `owners`, without a
252    /// query per owner.
253    ///
254    /// # Errors
255    ///
256    /// On a database error, or when an owner's key does not fit the `*_id` column.
257    pub async fn load_for<O, Db>(&self, db: &Db, owners: &[O]) -> Result<Vec<Vec<C::Model>>, DbErr>
258    where
259        O: ModelTrait<Entity: Morphable> + Sync,
260        Db: ConnectionTrait,
261    {
262        self.load_for_with(db, owners, C::find()).await
263    }
264
265    /// [`load_for`](Self::load_for) with your own query for the children, to filter or
266    /// order them.
267    ///
268    /// # Errors
269    ///
270    /// On a database error, or when an owner's key does not fit the `*_id` column.
271    pub async fn load_for_with<O, Db>(
272        &self,
273        db: &Db,
274        owners: &[O],
275        children: Select<C>,
276    ) -> Result<Vec<Vec<C::Model>>, DbErr>
277    where
278        O: ModelTrait<Entity: Morphable> + Sync,
279        Db: ConnectionTrait,
280    {
281        let keys = owners
282            .iter()
283            .map(require_key)
284            .collect::<Result<Vec<_>, _>>()?;
285        if keys.is_empty() {
286            return Ok(Vec::new());
287        }
288
289        let rows = children
290            .filter(self.of_type::<O::Entity>())
291            .filter(self.id_column.is_in(values_for(&keys, self.id_column)?))
292            .all(db)
293            .await?;
294
295        let mut by_owner: HashMap<Key, Vec<C::Model>> = HashMap::new();
296        for row in rows {
297            if let Some(key) = self.owner_key(&row) {
298                by_owner.entry(key).or_default().push(row);
299            }
300        }
301        Ok(keys
302            .iter()
303            .map(|key| by_owner.get(key).cloned().unwrap_or_default())
304            .collect())
305    }
306
307    /// How many children each owner has, in one `GROUP BY` query; `0` for none.
308    ///
309    /// # Errors
310    ///
311    /// On a database error, or when an owner's key does not fit the `*_id` column.
312    pub async fn count_for<O, Db>(&self, db: &Db, owners: &[O]) -> Result<Vec<u64>, DbErr>
313    where
314        O: ModelTrait<Entity: Morphable> + Sync,
315        Db: ConnectionTrait,
316    {
317        self.count_for_with(db, owners, C::find()).await
318    }
319
320    /// [`count_for`](Self::count_for) counting only the children `children` matches.
321    ///
322    /// # Errors
323    ///
324    /// On a database error, or when an owner's key does not fit the `*_id` column.
325    pub async fn count_for_with<O, Db>(
326        &self,
327        db: &Db,
328        owners: &[O],
329        children: Select<C>,
330    ) -> Result<Vec<u64>, DbErr>
331    where
332        O: ModelTrait<Entity: Morphable> + Sync,
333        Db: ConnectionTrait,
334    {
335        let keys = owners
336            .iter()
337            .map(require_key)
338            .collect::<Result<Vec<_>, _>>()?;
339        if keys.is_empty() {
340            return Ok(Vec::new());
341        }
342        // The caller's ORDER BY would make the grouped query invalid on Postgres.
343        let mut children = children;
344        QueryTrait::query(&mut children).clear_order_by();
345        let query = children
346            .select_only()
347            .column_as(self.id_column, "owner_key")
348            .column_as(Expr::col(self.id_column).count(), "total")
349            .filter(self.of_type::<O::Entity>())
350            .filter(self.id_column.is_in(values_for(&keys, self.id_column)?))
351            .group_by(self.id_column);
352        count_by_key(db, query, &keys).await
353    }
354
355    /// `SUM`, `AVG`, `MIN` or `MAX` of `column` over each owner's children, as `f64`;
356    /// `None` for an owner without children.
357    ///
358    /// # Errors
359    ///
360    /// On a database error, or when an owner's key does not fit the `*_id` column.
361    pub async fn aggregate_for<O, Db>(
362        &self,
363        db: &Db,
364        owners: &[O],
365        column: C::Column,
366        aggregate: Aggregate,
367    ) -> Result<Vec<Option<f64>>, DbErr>
368    where
369        O: ModelTrait<Entity: Morphable> + Sync,
370        Db: ConnectionTrait,
371    {
372        let keys = owners
373            .iter()
374            .map(require_key)
375            .collect::<Result<Vec<_>, _>>()?;
376        if keys.is_empty() {
377            return Ok(Vec::new());
378        }
379        let total = as_double(db.get_database_backend(), aggregate.of(Expr::col(column)));
380        let rows: HashMap<Key, Option<f64>> = C::find()
381            .select_only()
382            .column_as(self.id_column, "owner_key")
383            .column_as(total, "total")
384            .filter(self.of_type::<O::Entity>())
385            .filter(self.id_column.is_in(values_for(&keys, self.id_column)?))
386            .group_by(self.id_column)
387            .into_model::<KeyTotal>()
388            .all(db)
389            .await?
390            .into_iter()
391            .map(|row| (row.key, row.total))
392            .collect();
393        Ok(keys
394            .iter()
395            .map(|key| rows.get(key).copied().flatten())
396            .collect())
397    }
398
399    /// For each owner, the child with the largest ([`Pick::Max`]) or smallest
400    /// ([`Pick::Min`]) `column`, in one query: the latest comment of each post.
401    ///
402    /// # Errors
403    ///
404    /// On a database error, or when an owner's key does not fit the `*_id` column.
405    pub async fn pick_for<O, Db>(
406        &self,
407        db: &Db,
408        owners: &[O],
409        column: C::Column,
410        pick: Pick,
411    ) -> Result<Vec<Option<C::Model>>, DbErr>
412    where
413        O: ModelTrait<Entity: Morphable> + Sync,
414        Db: ConnectionTrait,
415    {
416        let keys = owners
417            .iter()
418            .map(require_key)
419            .collect::<Result<Vec<_>, _>>()?;
420        let values = values_for(&keys, self.id_column)?;
421        let source = Source::<C> {
422            owner_column: self.id_column,
423            scope: Some((self.type_column, O::Entity::MORPH_TYPE)),
424        };
425        let keys: Vec<Option<Key>> = keys.into_iter().map(Some).collect();
426        of_many::pick(db, &source, values, &keys, column, pick).await
427    }
428
429    /// The latest child of each owner by `column`: [`pick_for`](Self::pick_for) with
430    /// [`Pick::Max`].
431    ///
432    /// # Errors
433    ///
434    /// As [`pick_for`](Self::pick_for).
435    pub async fn latest_for<O, Db>(
436        &self,
437        db: &Db,
438        owners: &[O],
439        column: C::Column,
440    ) -> Result<Vec<Option<C::Model>>, DbErr>
441    where
442        O: ModelTrait<Entity: Morphable> + Sync,
443        Db: ConnectionTrait,
444    {
445        self.pick_for(db, owners, column, Pick::Max).await
446    }
447
448    /// The oldest child of each owner by `column`: [`pick_for`](Self::pick_for) with
449    /// [`Pick::Min`].
450    ///
451    /// # Errors
452    ///
453    /// As [`pick_for`](Self::pick_for).
454    pub async fn oldest_for<O, Db>(
455        &self,
456        db: &Db,
457        owners: &[O],
458        column: C::Column,
459    ) -> Result<Vec<Option<C::Model>>, DbErr>
460    where
461        O: ModelTrait<Entity: Morphable> + Sync,
462        Db: ConnectionTrait,
463    {
464        self.pick_for(db, owners, column, Pick::Min).await
465    }
466
467    /// Deletes the children of `owner`, for its delete hook: polymorphic columns have
468    /// no foreign key, so the database cannot cascade. Runs one `DELETE`, so the
469    /// children's own hooks do not run. Returns how many rows went.
470    ///
471    /// # Errors
472    ///
473    /// On a database error, or when `owner`'s key does not fit the `*_id` column.
474    pub async fn delete_for<O, Db>(&self, db: &Db, owner: &O) -> Result<u64, DbErr>
475    where
476        O: ModelTrait<Entity: Morphable> + Sync,
477        Db: ConnectionTrait,
478    {
479        let result = C::delete_many().filter(self.of(owner)?).exec(db).await?;
480        Ok(result.rows_affected)
481    }
482
483    /// Deletes children of type `O` whose owner row no longer exists. Returns how
484    /// many rows went.
485    ///
486    /// # Errors
487    ///
488    /// On a database error.
489    pub async fn delete_orphans<O, Db>(&self, db: &Db) -> Result<u64, DbErr>
490    where
491        O: Morphable,
492        Db: ConnectionTrait,
493    {
494        let result = C::delete_many()
495            .filter(self.of_type::<O>())
496            .filter(self.id_column.not_in_subquery(keys_of(O::find())))
497            .exec(db)
498            .await?;
499        Ok(result.rows_affected)
500    }
501
502    // ---- Filters ---------------------------------------------------------------
503
504    /// For queries on `C`: children whose owner is an `O` that `owners` matches.
505    ///
506    /// ```
507    /// # mod posts { use sea_orm::entity::prelude::*;
508    /// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
509    /// #   #[sea_orm(table_name = "posts")]
510    /// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32, pub published: bool }
511    /// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
512    /// #   impl ActiveModelBehavior for ActiveModel {} }
513    /// # mod comments { use sea_orm::entity::prelude::*;
514    /// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
515    /// #   #[sea_orm(table_name = "comments")]
516    /// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32,
517    /// #     pub commentable_type: String, pub commentable_id: i64 }
518    /// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
519    /// #   impl ActiveModelBehavior for ActiveModel {} }
520    /// # use sea_orm_relations_kit::{Morph, Morphable};
521    /// # impl Morphable for posts::Entity { const MORPH_TYPE: &'static str = "post"; }
522    /// # const COMMENTABLE: Morph<comments::Entity> =
523    /// #     Morph::new(comments::Column::CommentableType, comments::Column::CommentableId);
524    /// use sea_orm::{DbBackend, EntityTrait, QueryFilter, QueryTrait};
525    /// use sea_orm::entity::prelude::*;
526    ///
527    /// let on_published_posts = comments::Entity::find().filter(
528    ///     COMMENTABLE.owned_by(posts::Entity::find().filter(posts::Column::Published.eq(true))),
529    /// );
530    /// assert_eq!(
531    ///     on_published_posts.build(DbBackend::Postgres).to_string(),
532    ///     r#"SELECT "comments"."id", "comments"."commentable_type", "comments"."commentable_id" FROM "comments" WHERE "comments"."commentable_type" = 'post' AND "comments"."commentable_id" IN (SELECT "posts"."id" FROM "posts" WHERE "posts"."published" = TRUE)"#
533    /// );
534    /// ```
535    pub fn owned_by<O: Morphable>(&self, owners: Select<O>) -> Condition {
536        self.of_type::<O>()
537            .add(self.id_column.in_subquery(keys_of(owners)))
538    }
539
540    /// For queries on `C`: children whose owner is an `O` that `owners` does not
541    /// match, including owners that no longer exist.
542    pub fn not_owned_by<O: Morphable>(&self, owners: Select<O>) -> Condition {
543        self.of_type::<O>()
544            .add(self.id_column.not_in_subquery(keys_of(owners)))
545    }
546
547    /// For queries on `O`: owners with at least one child that `children` matches;
548    /// pass `C::find()` for owners with any child.
549    pub fn owners_with<O: Morphable>(&self, children: Select<C>) -> Condition {
550        Condition::all().add(primary_column::<O>().in_subquery(self.owner_keys::<O>(children)))
551    }
552
553    /// For queries on `O`: owners without any child that `children` matches.
554    pub fn owners_without<O: Morphable>(&self, children: Select<C>) -> Condition {
555        Condition::all().add(primary_column::<O>().not_in_subquery(self.owner_keys::<O>(children)))
556    }
557
558    /// `SELECT id_column FROM children WHERE type = O AND id_column IS NOT NULL`.
559    /// The `IS NOT NULL` keeps `NOT IN` from matching nothing on a `NULL`.
560    fn owner_keys<O: Morphable>(&self, children: Select<C>) -> sea_orm::sea_query::SelectStatement {
561        children
562            .select_only()
563            .column(self.id_column)
564            .filter(self.of_type::<O>())
565            .filter(self.id_column.is_not_null())
566            .into_query()
567    }
568}
569
570/// `SELECT pk FROM rows`, for `IN (...)` subqueries.
571pub fn keys_of<E: EntityTrait>(rows: Select<E>) -> sea_orm::sea_query::SelectStatement {
572    rows.select_only()
573        .column(primary_column::<E>())
574        .into_query()
575}
576
577/// A `NULL` of the type `column` stores.
578fn null_of<C: ColumnTrait>(column: C) -> Value {
579    match column.def().get_column_type() {
580        ColumnType::TinyInteger => Value::TinyInt(None),
581        ColumnType::SmallInteger => Value::SmallInt(None),
582        ColumnType::Integer => Value::Int(None),
583        ColumnType::BigInteger => Value::BigInt(None),
584        ColumnType::TinyUnsigned => Value::TinyUnsigned(None),
585        ColumnType::SmallUnsigned => Value::SmallUnsigned(None),
586        ColumnType::Unsigned => Value::Unsigned(None),
587        ColumnType::BigUnsigned => Value::BigUnsigned(None),
588        #[cfg(feature = "with-uuid")]
589        ColumnType::Uuid => Value::Uuid(None),
590        _ => Value::String(None),
591    }
592}
593
594/// One `owner_key, total` row of a grouped count.
595struct KeyCount {
596    key: Key,
597    total: i64,
598}
599
600impl FromQueryResult for KeyCount {
601    fn from_query_result(row: &QueryResult, _pre: &str) -> Result<Self, DbErr> {
602        Ok(Self {
603            key: Key::read(row, "owner_key")?,
604            total: row.try_get("", "total")?,
605        })
606    }
607}
608
609/// One `owner_key, total` row of a grouped aggregate.
610struct KeyTotal {
611    key: Key,
612    total: Option<f64>,
613}
614
615impl FromQueryResult for KeyTotal {
616    fn from_query_result(row: &QueryResult, _pre: &str) -> Result<Self, DbErr> {
617        Ok(Self {
618            key: Key::read(row, "owner_key")?,
619            total: row.try_get("", "total")?,
620        })
621    }
622}
623
624/// Runs a `GROUP BY owner_key` count and lines the totals up with `keys`.
625pub async fn count_by_key<E, Db>(db: &Db, query: Select<E>, keys: &[Key]) -> Result<Vec<u64>, DbErr>
626where
627    E: EntityTrait,
628    Db: ConnectionTrait,
629{
630    let totals: HashMap<Key, i64> = query
631        .into_model::<KeyCount>()
632        .all(db)
633        .await?
634        .into_iter()
635        .map(|row| (row.key, row.total))
636        .collect();
637    Ok(keys
638        .iter()
639        .map(|key| totals.get(key).map_or(0, |total| total.unsigned_abs()))
640        .collect())
641}