sea-orm-relations-kit 0.1.1

Relations SeaORM lacks: polymorphic relations, many-to-many attach/sync/toggle, relation counts and latest-of-many
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! Polymorphic one-to-one and one-to-many relations, and resolving a child's owner.

use std::collections::{BTreeMap, HashMap};

use sea_orm::{
    sea_query::{ColumnType, Expr, ExprTrait},
    ActiveModelTrait, ColumnTrait, Condition, ConnectionTrait, DbErr, EntityTrait, FromQueryResult,
    ModelTrait, QueryFilter, QueryResult, QuerySelect, QueryTrait, Select, Value,
};

use crate::key::{primary_column, require_key, values_for, Key};
use crate::of_many::{self, Pick, Source};
use crate::related::{as_double, Aggregate};
use crate::target::MorphTarget;

/// An entity that can own polymorphic children, with the name stored in their
/// `*_type` column.
///
/// The name is a short, stable alias like `"post"`: Rust has no class names to store,
/// and an alias survives renaming the entity or moving it to another module.
///
/// ```
/// # mod posts { use sea_orm::entity::prelude::*;
/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
/// #   #[sea_orm(table_name = "posts")]
/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32 }
/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
/// #   impl ActiveModelBehavior for ActiveModel {} }
/// use sea_orm_relations_kit::Morphable;
///
/// impl Morphable for posts::Entity {
///     const MORPH_TYPE: &'static str = "post";
/// }
/// ```
pub trait Morphable: EntityTrait {
    /// The value stored in the `*_type` column of this entity's children.
    const MORPH_TYPE: &'static str;
}

/// The `*_type` and `*_id` columns of a polymorphic child: `commentable_type` and
/// `commentable_id` on `comments`.
///
/// Declare it once per relation, as a constant next to the child entity:
///
/// ```
/// # mod comments { use sea_orm::entity::prelude::*;
/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
/// #   #[sea_orm(table_name = "comments")]
/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32,
/// #     pub commentable_type: String, pub commentable_id: i64 }
/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
/// #   impl ActiveModelBehavior for ActiveModel {} }
/// use sea_orm_relations_kit::Morph;
///
/// pub const COMMENTABLE: Morph<comments::Entity> =
///     Morph::new(comments::Column::CommentableType, comments::Column::CommentableId);
/// ```
///
/// From the owner it finds the children ([`find_for`](Self::find_for),
/// [`load_for`](Self::load_for)); from a child it finds the owner
/// ([`owner`](Self::owner), [`load_owners`](Self::load_owners)).
#[derive(Clone, Copy, Debug)]
pub struct Morph<C: EntityTrait> {
    type_column: C::Column,
    id_column: C::Column,
}

impl<C: EntityTrait> Morph<C> {
    /// The relation stored in `type_column` and `id_column` of `C`.
    pub const fn new(type_column: C::Column, id_column: C::Column) -> Self {
        Self {
            type_column,
            id_column,
        }
    }

    /// The `*_type` column.
    pub const fn type_column(&self) -> C::Column {
        self.type_column
    }

    /// The `*_id` column.
    pub const fn id_column(&self) -> C::Column {
        self.id_column
    }
}

impl<C: EntityTrait> Morph<C>
where
    C::Model: Sync,
{
    // ---- From the child: its owner ------------------------------------------------

    /// Points `child` at `owner` by setting both columns.
    ///
    /// # Errors
    ///
    /// When `owner`'s key does not fit the `*_id` column, or `owner` has no key yet.
    pub fn associate<O>(&self, child: &mut C::ActiveModel, owner: &O) -> Result<(), DbErr>
    where
        O: ModelTrait<Entity: Morphable>,
    {
        let key = require_key(owner)?;
        child.try_set(
            self.type_column,
            Value::String(Some(O::Entity::MORPH_TYPE.to_string())),
        )?;
        child.try_set(self.id_column, key.to_value_for(self.id_column)?)
    }

    /// Sets both columns to `NULL`, for a relation where the owner is optional.
    ///
    /// # Errors
    ///
    /// When a column is not nullable in the database; the error comes on save.
    pub fn dissociate(&self, child: &mut C::ActiveModel) -> Result<(), DbErr> {
        child.try_set(self.type_column, Value::String(None))?;
        child.try_set(self.id_column, null_of(self.id_column))
    }

    /// The owner's morph type stored on `child`, `None` when it is `NULL`.
    pub fn owner_type(&self, child: &C::Model) -> Option<String> {
        match child.get(self.type_column) {
            Value::String(Some(morph_type)) => Some(morph_type),
            _ => None,
        }
    }

    /// The owner's key stored on `child`, `None` when it is `NULL`.
    pub fn owner_key(&self, child: &C::Model) -> Option<Key> {
        Key::from_value(&child.get(self.id_column))
    }

    /// Whether `child` belongs to `owner`.
    pub fn is_owned_by<O>(&self, child: &C::Model, owner: &O) -> bool
    where
        O: ModelTrait<Entity: Morphable>,
    {
        self.owner_type(child).as_deref() == Some(O::Entity::MORPH_TYPE)
            && self.owner_key(child).is_some()
            && self.owner_key(child) == Key::of(owner)
    }

    /// The owner of `child`, whichever entity it is.
    ///
    /// `T` is an enum of the possible owners, declared with
    /// [`morph_target!`](crate::morph_target). `None` when the columns are `NULL` or
    /// the owner row is gone.
    ///
    /// # Errors
    ///
    /// On a database error, or when the stored type is not one of `T`'s.
    pub async fn owner<T, Db>(&self, db: &Db, child: &C::Model) -> Result<Option<T>, DbErr>
    where
        T: MorphTarget,
        Db: ConnectionTrait,
    {
        let (Some(morph_type), Some(key)) = (self.owner_type(child), self.owner_key(child)) else {
            return Ok(None);
        };
        let found = T::load_type(db, &morph_type, vec![key]).await?;
        Ok(found.into_iter().next().map(|(_, owner)| owner))
    }

    /// The owners of many children, one query per owner type, in the order of
    /// `children`. Children sharing an owner get a clone of it.
    ///
    /// # Errors
    ///
    /// On a database error, or when a stored type is not one of `T`'s.
    pub async fn load_owners<T, Db>(
        &self,
        db: &Db,
        children: &[C::Model],
    ) -> Result<Vec<Option<T>>, DbErr>
    where
        T: MorphTarget + Clone,
        Db: ConnectionTrait,
    {
        let links: Vec<Option<(String, Key)>> = children
            .iter()
            .map(|child| self.owner_type(child).zip(self.owner_key(child)))
            .collect();

        let mut keys_by_type: BTreeMap<&str, Vec<Key>> = BTreeMap::new();
        for (morph_type, key) in links.iter().flatten() {
            keys_by_type
                .entry(morph_type)
                .or_default()
                .push(key.clone());
        }

        let mut owners: HashMap<(&str, Key), T> = HashMap::new();
        for (morph_type, keys) in keys_by_type {
            for (key, owner) in T::load_type(db, morph_type, keys).await? {
                owners.insert((morph_type, key), owner);
            }
        }

        Ok(links
            .iter()
            .map(|link| {
                link.as_ref()
                    .and_then(|(morph_type, key)| owners.get(&(morph_type.as_str(), key.clone())))
                    .cloned()
            })
            .collect())
    }

    // ---- From the owner: its children ---------------------------------------------

    /// `WHERE type = 'post' AND id = 15`: the children of `owner`, for any query on
    /// `C`.
    ///
    /// # Errors
    ///
    /// When `owner`'s key does not fit the `*_id` column.
    pub fn of<O>(&self, owner: &O) -> Result<Condition, DbErr>
    where
        O: ModelTrait<Entity: Morphable>,
    {
        let key = require_key(owner)?.to_value_for(self.id_column)?;
        Ok(self.of_type::<O::Entity>().add(self.id_column.eq(key)))
    }

    /// `WHERE type = 'post'`: children of any owner of type `O`.
    pub fn of_type<O: Morphable>(&self) -> Condition {
        Condition::all().add(self.type_column.eq(O::MORPH_TYPE))
    }

    /// `WHERE type IN (...)`: children of owners of the given types.
    pub fn of_types<'a>(&self, morph_types: impl IntoIterator<Item = &'a str>) -> Condition {
        Condition::all().add(self.type_column.is_in(morph_types))
    }

    /// The children of `owner`, ready to filter, order and run.
    ///
    /// For a one-to-one relation take `.one(db)`; for the latest child order by a
    /// column descending first.
    ///
    /// # Errors
    ///
    /// When `owner`'s key does not fit the `*_id` column.
    pub fn find_for<O>(&self, owner: &O) -> Result<Select<C>, DbErr>
    where
        O: ModelTrait<Entity: Morphable>,
    {
        Ok(C::find().filter(self.of(owner)?))
    }

    /// The children of many owners in one query, in the order of `owners`, without a
    /// query per owner.
    ///
    /// # Errors
    ///
    /// On a database error, or when an owner's key does not fit the `*_id` column.
    pub async fn load_for<O, Db>(&self, db: &Db, owners: &[O]) -> Result<Vec<Vec<C::Model>>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        self.load_for_with(db, owners, C::find()).await
    }

    /// [`load_for`](Self::load_for) with your own query for the children, to filter or
    /// order them.
    ///
    /// # Errors
    ///
    /// On a database error, or when an owner's key does not fit the `*_id` column.
    pub async fn load_for_with<O, Db>(
        &self,
        db: &Db,
        owners: &[O],
        children: Select<C>,
    ) -> Result<Vec<Vec<C::Model>>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        let keys = owners
            .iter()
            .map(require_key)
            .collect::<Result<Vec<_>, _>>()?;
        if keys.is_empty() {
            return Ok(Vec::new());
        }

        let rows = children
            .filter(self.of_type::<O::Entity>())
            .filter(self.id_column.is_in(values_for(&keys, self.id_column)?))
            .all(db)
            .await?;

        let mut by_owner: HashMap<Key, Vec<C::Model>> = HashMap::new();
        for row in rows {
            if let Some(key) = self.owner_key(&row) {
                by_owner.entry(key).or_default().push(row);
            }
        }
        Ok(keys
            .iter()
            .map(|key| by_owner.get(key).cloned().unwrap_or_default())
            .collect())
    }

    /// How many children each owner has, in one `GROUP BY` query; `0` for none.
    ///
    /// # Errors
    ///
    /// On a database error, or when an owner's key does not fit the `*_id` column.
    pub async fn count_for<O, Db>(&self, db: &Db, owners: &[O]) -> Result<Vec<u64>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        self.count_for_with(db, owners, C::find()).await
    }

    /// [`count_for`](Self::count_for) counting only the children `children` matches.
    ///
    /// # Errors
    ///
    /// On a database error, or when an owner's key does not fit the `*_id` column.
    pub async fn count_for_with<O, Db>(
        &self,
        db: &Db,
        owners: &[O],
        children: Select<C>,
    ) -> Result<Vec<u64>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        let keys = owners
            .iter()
            .map(require_key)
            .collect::<Result<Vec<_>, _>>()?;
        if keys.is_empty() {
            return Ok(Vec::new());
        }
        // The caller's ORDER BY would make the grouped query invalid on Postgres.
        let mut children = children;
        QueryTrait::query(&mut children).clear_order_by();
        let query = children
            .select_only()
            .column_as(self.id_column, "owner_key")
            .column_as(Expr::col(self.id_column).count(), "total")
            .filter(self.of_type::<O::Entity>())
            .filter(self.id_column.is_in(values_for(&keys, self.id_column)?))
            .group_by(self.id_column);
        count_by_key(db, query, &keys).await
    }

    /// `SUM`, `AVG`, `MIN` or `MAX` of `column` over each owner's children, as `f64`;
    /// `None` for an owner without children.
    ///
    /// # Errors
    ///
    /// On a database error, or when an owner's key does not fit the `*_id` column.
    pub async fn aggregate_for<O, Db>(
        &self,
        db: &Db,
        owners: &[O],
        column: C::Column,
        aggregate: Aggregate,
    ) -> Result<Vec<Option<f64>>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        let keys = owners
            .iter()
            .map(require_key)
            .collect::<Result<Vec<_>, _>>()?;
        if keys.is_empty() {
            return Ok(Vec::new());
        }
        let total = as_double(db.get_database_backend(), aggregate.of(Expr::col(column)));
        let rows: HashMap<Key, Option<f64>> = C::find()
            .select_only()
            .column_as(self.id_column, "owner_key")
            .column_as(total, "total")
            .filter(self.of_type::<O::Entity>())
            .filter(self.id_column.is_in(values_for(&keys, self.id_column)?))
            .group_by(self.id_column)
            .into_model::<KeyTotal>()
            .all(db)
            .await?
            .into_iter()
            .map(|row| (row.key, row.total))
            .collect();
        Ok(keys
            .iter()
            .map(|key| rows.get(key).copied().flatten())
            .collect())
    }

    /// For each owner, the child with the largest ([`Pick::Max`]) or smallest
    /// ([`Pick::Min`]) `column`, in one query: the latest comment of each post.
    ///
    /// # Errors
    ///
    /// On a database error, or when an owner's key does not fit the `*_id` column.
    pub async fn pick_for<O, Db>(
        &self,
        db: &Db,
        owners: &[O],
        column: C::Column,
        pick: Pick,
    ) -> Result<Vec<Option<C::Model>>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        let keys = owners
            .iter()
            .map(require_key)
            .collect::<Result<Vec<_>, _>>()?;
        let values = values_for(&keys, self.id_column)?;
        let source = Source::<C> {
            owner_column: self.id_column,
            scope: Some((self.type_column, O::Entity::MORPH_TYPE)),
        };
        let keys: Vec<Option<Key>> = keys.into_iter().map(Some).collect();
        of_many::pick(db, &source, values, &keys, column, pick).await
    }

    /// The latest child of each owner by `column`: [`pick_for`](Self::pick_for) with
    /// [`Pick::Max`].
    ///
    /// # Errors
    ///
    /// As [`pick_for`](Self::pick_for).
    pub async fn latest_for<O, Db>(
        &self,
        db: &Db,
        owners: &[O],
        column: C::Column,
    ) -> Result<Vec<Option<C::Model>>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        self.pick_for(db, owners, column, Pick::Max).await
    }

    /// The oldest child of each owner by `column`: [`pick_for`](Self::pick_for) with
    /// [`Pick::Min`].
    ///
    /// # Errors
    ///
    /// As [`pick_for`](Self::pick_for).
    pub async fn oldest_for<O, Db>(
        &self,
        db: &Db,
        owners: &[O],
        column: C::Column,
    ) -> Result<Vec<Option<C::Model>>, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        self.pick_for(db, owners, column, Pick::Min).await
    }

    /// Deletes the children of `owner`, for its delete hook: polymorphic columns have
    /// no foreign key, so the database cannot cascade. Runs one `DELETE`, so the
    /// children's own hooks do not run. Returns how many rows went.
    ///
    /// # Errors
    ///
    /// On a database error, or when `owner`'s key does not fit the `*_id` column.
    pub async fn delete_for<O, Db>(&self, db: &Db, owner: &O) -> Result<u64, DbErr>
    where
        O: ModelTrait<Entity: Morphable> + Sync,
        Db: ConnectionTrait,
    {
        let result = C::delete_many().filter(self.of(owner)?).exec(db).await?;
        Ok(result.rows_affected)
    }

    /// Deletes children of type `O` whose owner row no longer exists. Returns how
    /// many rows went.
    ///
    /// # Errors
    ///
    /// On a database error.
    pub async fn delete_orphans<O, Db>(&self, db: &Db) -> Result<u64, DbErr>
    where
        O: Morphable,
        Db: ConnectionTrait,
    {
        let result = C::delete_many()
            .filter(self.of_type::<O>())
            .filter(self.id_column.not_in_subquery(keys_of(O::find())))
            .exec(db)
            .await?;
        Ok(result.rows_affected)
    }

    // ---- Filters ---------------------------------------------------------------

    /// For queries on `C`: children whose owner is an `O` that `owners` matches.
    ///
    /// ```
    /// # mod posts { use sea_orm::entity::prelude::*;
    /// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    /// #   #[sea_orm(table_name = "posts")]
    /// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32, pub published: bool }
    /// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
    /// #   impl ActiveModelBehavior for ActiveModel {} }
    /// # mod comments { use sea_orm::entity::prelude::*;
    /// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    /// #   #[sea_orm(table_name = "comments")]
    /// #   pub struct Model { #[sea_orm(primary_key)] pub id: i32,
    /// #     pub commentable_type: String, pub commentable_id: i64 }
    /// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
    /// #   impl ActiveModelBehavior for ActiveModel {} }
    /// # use sea_orm_relations_kit::{Morph, Morphable};
    /// # impl Morphable for posts::Entity { const MORPH_TYPE: &'static str = "post"; }
    /// # const COMMENTABLE: Morph<comments::Entity> =
    /// #     Morph::new(comments::Column::CommentableType, comments::Column::CommentableId);
    /// use sea_orm::{DbBackend, EntityTrait, QueryFilter, QueryTrait};
    /// use sea_orm::entity::prelude::*;
    ///
    /// let on_published_posts = comments::Entity::find().filter(
    ///     COMMENTABLE.owned_by(posts::Entity::find().filter(posts::Column::Published.eq(true))),
    /// );
    /// assert_eq!(
    ///     on_published_posts.build(DbBackend::Postgres).to_string(),
    ///     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)"#
    /// );
    /// ```
    pub fn owned_by<O: Morphable>(&self, owners: Select<O>) -> Condition {
        self.of_type::<O>()
            .add(self.id_column.in_subquery(keys_of(owners)))
    }

    /// For queries on `C`: children whose owner is an `O` that `owners` does not
    /// match, including owners that no longer exist.
    pub fn not_owned_by<O: Morphable>(&self, owners: Select<O>) -> Condition {
        self.of_type::<O>()
            .add(self.id_column.not_in_subquery(keys_of(owners)))
    }

    /// For queries on `O`: owners with at least one child that `children` matches;
    /// pass `C::find()` for owners with any child.
    pub fn owners_with<O: Morphable>(&self, children: Select<C>) -> Condition {
        Condition::all().add(primary_column::<O>().in_subquery(self.owner_keys::<O>(children)))
    }

    /// For queries on `O`: owners without any child that `children` matches.
    pub fn owners_without<O: Morphable>(&self, children: Select<C>) -> Condition {
        Condition::all().add(primary_column::<O>().not_in_subquery(self.owner_keys::<O>(children)))
    }

    /// `SELECT id_column FROM children WHERE type = O AND id_column IS NOT NULL`.
    /// The `IS NOT NULL` keeps `NOT IN` from matching nothing on a `NULL`.
    fn owner_keys<O: Morphable>(&self, children: Select<C>) -> sea_orm::sea_query::SelectStatement {
        children
            .select_only()
            .column(self.id_column)
            .filter(self.of_type::<O>())
            .filter(self.id_column.is_not_null())
            .into_query()
    }
}

/// `SELECT pk FROM rows`, for `IN (...)` subqueries.
pub fn keys_of<E: EntityTrait>(rows: Select<E>) -> sea_orm::sea_query::SelectStatement {
    rows.select_only()
        .column(primary_column::<E>())
        .into_query()
}

/// A `NULL` of the type `column` stores.
fn null_of<C: ColumnTrait>(column: C) -> Value {
    match column.def().get_column_type() {
        ColumnType::TinyInteger => Value::TinyInt(None),
        ColumnType::SmallInteger => Value::SmallInt(None),
        ColumnType::Integer => Value::Int(None),
        ColumnType::BigInteger => Value::BigInt(None),
        ColumnType::TinyUnsigned => Value::TinyUnsigned(None),
        ColumnType::SmallUnsigned => Value::SmallUnsigned(None),
        ColumnType::Unsigned => Value::Unsigned(None),
        ColumnType::BigUnsigned => Value::BigUnsigned(None),
        #[cfg(feature = "with-uuid")]
        ColumnType::Uuid => Value::Uuid(None),
        _ => Value::String(None),
    }
}

/// One `owner_key, total` row of a grouped count.
struct KeyCount {
    key: Key,
    total: i64,
}

impl FromQueryResult for KeyCount {
    fn from_query_result(row: &QueryResult, _pre: &str) -> Result<Self, DbErr> {
        Ok(Self {
            key: Key::read(row, "owner_key")?,
            total: row.try_get("", "total")?,
        })
    }
}

/// One `owner_key, total` row of a grouped aggregate.
struct KeyTotal {
    key: Key,
    total: Option<f64>,
}

impl FromQueryResult for KeyTotal {
    fn from_query_result(row: &QueryResult, _pre: &str) -> Result<Self, DbErr> {
        Ok(Self {
            key: Key::read(row, "owner_key")?,
            total: row.try_get("", "total")?,
        })
    }
}

/// Runs a `GROUP BY owner_key` count and lines the totals up with `keys`.
pub async fn count_by_key<E, Db>(db: &Db, query: Select<E>, keys: &[Key]) -> Result<Vec<u64>, DbErr>
where
    E: EntityTrait,
    Db: ConnectionTrait,
{
    let totals: HashMap<Key, i64> = query
        .into_model::<KeyCount>()
        .all(db)
        .await?
        .into_iter()
        .map(|row| (row.key, row.total))
        .collect();
    Ok(keys
        .iter()
        .map(|key| totals.get(key).map_or(0, |total| total.unsigned_abs()))
        .collect())
}