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
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
//! Counts, existence checks, aggregates and one-of-many for `SeaORM`'s own relations:
//! anything with a `Related<R>` impl, direct (`has_many`, `has_one`, `belongs_to`) or
//! through a junction table (`via`).
//!
//! Each function takes a page of owners and answers for all of them in one query,
//! in the order of the owners.

use std::collections::HashMap;
use std::str::FromStr;

use sea_orm::{
    sea_query::{
        DynIden, Expr, ExprTrait, Func, IntoIden, JoinType, Query, SelectStatement, TableRef,
    },
    ConnectionTrait, DbBackend, DbErr, EntityTrait, Identity, ModelTrait, QueryResult, QuerySelect,
    QueryTrait, Related, Select, Value,
};

use crate::key::{key_or_error, primary_column, Key};
use crate::morph::keys_of;
use crate::of_many::{self, Pick, Source};

/// An aggregate over a column of the related rows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Aggregate {
    /// `SUM(column)`
    Sum,
    /// `AVG(column)`
    Avg,
    /// `MIN(column)`
    Min,
    /// `MAX(column)`
    Max,
}

impl Aggregate {
    pub(crate) fn of(self, expr: Expr) -> Expr {
        match self {
            Self::Sum => Func::sum(expr).into(),
            Self::Avg => Func::avg(expr).into(),
            Self::Min => Func::min(expr).into(),
            Self::Max => Func::max(expr).into(),
        }
    }
}

/// How many related rows each owner has: `[3, 0, 1]` for three posts.
///
/// ```no_run
/// # 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 { #[sea_orm(has_many = "super::comments::Entity")] Comments }
/// #   impl Related<super::comments::Entity> for Entity {
/// #     fn to() -> RelationDef { Relation::Comments.def() } }
/// #   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 post_id: i32 }
/// #   #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
/// #   pub enum Relation {
/// #     #[sea_orm(belongs_to = "super::posts::Entity", from = "Column::PostId", to = "super::posts::Column::Id")]
/// #     Post }
/// #   impl Related<super::posts::Entity> for Entity {
/// #     fn to() -> RelationDef { Relation::Post.def() } }
/// #   impl ActiveModelBehavior for ActiveModel {} }
/// use sea_orm::{DatabaseConnection, DbErr, EntityTrait, PaginatorTrait};
/// use sea_orm_relations_kit::count_related;
///
/// async fn page(db: &DatabaseConnection) -> Result<(), DbErr> {
///     let posts = posts::Entity::find().all(db).await?;
///     let comments = count_related::<comments::Entity, _, _>(db, &posts).await?;
///     for (post, count) in posts.iter().zip(comments) {
///         println!("{}: {count} comments", post.id);
///     }
///     Ok(())
/// }
/// # fn main() {}
/// ```
///
/// # Errors
///
/// On a database error, or when the relation is keyed by several columns.
pub async fn count_related<R, O, Db>(db: &Db, owners: &[O]) -> Result<Vec<u64>, DbErr>
where
    R: EntityTrait,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    let totals = grouped::<R, O, Db>(db, owners, None, Expr::cust("COUNT(*)")).await?;
    totals.per_owner(0, read_count)
}

/// [`count_related`] counting only the related rows `related` matches.
///
/// # Errors
///
/// On a database error, or when the relation is keyed by several columns.
pub async fn count_related_with<R, O, Db>(
    db: &Db,
    owners: &[O],
    related: Select<R>,
) -> Result<Vec<u64>, DbErr>
where
    R: EntityTrait,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    let totals = grouped::<R, O, Db>(db, owners, Some(related), Expr::cust("COUNT(*)")).await?;
    totals.per_owner(0, read_count)
}

/// Whether each owner has any related row.
///
/// # Errors
///
/// On a database error, or when the relation is keyed by several columns.
pub async fn exists_related<R, O, Db>(db: &Db, owners: &[O]) -> Result<Vec<bool>, DbErr>
where
    R: EntityTrait,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    Ok(count_related::<R, O, Db>(db, owners)
        .await?
        .into_iter()
        .map(|count| count > 0)
        .collect())
}

/// `SUM`, `AVG`, `MIN` or `MAX` of `column` over each owner's related rows, as `f64`;
/// `None` for an owner without related rows.
///
/// # Errors
///
/// On a database error, or when the relation is keyed by several columns.
pub async fn aggregate_related<R, O, Db>(
    db: &Db,
    owners: &[O],
    column: R::Column,
    aggregate: Aggregate,
) -> Result<Vec<Option<f64>>, DbErr>
where
    R: EntityTrait,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    let path = Path::of::<O::Entity, R>()?;
    let target = if path.junction.is_some() {
        Expr::col((R::default(), column))
    } else {
        Expr::col((ROWS, column))
    };
    let total = as_double(db.get_database_backend(), aggregate.of(target));
    let totals = grouped::<R, O, Db>(db, owners, None, total).await?;
    totals.per_owner(None, |row| row.try_get::<Option<f64>>("", "total"))
}

/// For each owner, the related row with the largest (`Pick::Max`) or smallest
/// (`Pick::Min`) `column`, in one query. Only for direct relations (`has_many`).
///
/// # Errors
///
/// On a database error, or when the relation goes through a junction table or is
/// keyed by several columns.
pub async fn of_many<R, O, Db>(
    db: &Db,
    owners: &[O],
    column: R::Column,
    pick: Pick,
) -> Result<Vec<Option<R::Model>>, DbErr>
where
    R: EntityTrait,
    R::Model: Sync,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    let path = Path::of::<O::Entity, R>()?;
    if path.junction.is_some() {
        return Err(DbErr::Custom(
            "one-of-many picks from a direct relation, not one through a junction table".into(),
        ));
    }
    let owner_column = R::Column::from_str(&path.column.to_string()).map_err(|_| {
        DbErr::Custom(format!(
            "`{}` is not a column of the related entity",
            path.column
        ))
    })?;
    let (values, keys) = owner_values(owners, &path)?;
    let source = Source::<R> {
        owner_column,
        scope: None,
    };
    of_many::pick(db, &source, values, &keys, column, pick).await
}

/// The latest related row of each owner by `column`: [`of_many`] with [`Pick::Max`].
///
/// # Errors
///
/// As [`of_many`].
pub async fn latest_of_many<R, O, Db>(
    db: &Db,
    owners: &[O],
    column: R::Column,
) -> Result<Vec<Option<R::Model>>, DbErr>
where
    R: EntityTrait,
    R::Model: Sync,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    of_many::<R, O, Db>(db, owners, column, Pick::Max).await
}

/// The oldest related row of each owner by `column`: [`of_many`] with [`Pick::Min`].
///
/// # Errors
///
/// As [`of_many`].
pub async fn oldest_of_many<R, O, Db>(
    db: &Db,
    owners: &[O],
    column: R::Column,
) -> Result<Vec<Option<R::Model>>, DbErr>
where
    R: EntityTrait,
    R::Model: Sync,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    of_many::<R, O, Db>(db, owners, column, Pick::Min).await
}

/// The alias of the counted table in the grouped queries.
const ROWS: &str = "related_rows";

/// The rows to count for a relation and how they point at the owner.
struct Path {
    /// The owner's column the related rows point at (usually its primary key).
    owner_column: DynIden,
    /// The table holding the rows to count: the related table, or the junction.
    table: TableRef,
    /// The column of `table` holding the owner's key.
    column: DynIden,
    /// Through a junction: the junction's column pointing at the related table, and
    /// the related table's column it points at.
    junction: Option<(DynIden, DynIden)>,
}

impl Path {
    fn of<E: Related<R>, R: EntityTrait>() -> Result<Self, DbErr> {
        let Some(via) = E::via() else {
            let to = E::to();
            return Ok(Self {
                owner_column: single(&to.from_col)?,
                table: to.to_tbl,
                column: single(&to.to_col)?,
                junction: None,
            });
        };
        Ok(Self {
            owner_column: single(&via.from_col)?,
            table: via.to_tbl,
            column: single(&via.to_col)?,
            junction: Some((single(&E::to().from_col)?, single(&E::to().to_col)?)),
        })
    }
}

fn single(identity: &Identity) -> Result<DynIden, DbErr> {
    match identity {
        Identity::Unary(column) => Ok(column.clone()),
        _ => Err(DbErr::Custom(
            "relations keyed by several columns are not supported".into(),
        )),
    }
}

/// The values of the owners' linking column, for `IN (...)`, and their keys. A `NULL`
/// link (an optional `belongs_to`) has no related rows; a value that cannot be a key
/// is an error rather than a silent zero.
fn owner_values<O: ModelTrait>(
    owners: &[O],
    path: &Path,
) -> Result<(Vec<Value>, Vec<Option<Key>>), DbErr> {
    let name = path.owner_column.to_string();
    let column = <O::Entity as EntityTrait>::Column::from_str(&name)
        .map_err(|_| DbErr::Custom(format!("`{name}` is not a column of the owner entity")))?;
    let mut values = Vec::with_capacity(owners.len());
    let mut keys = Vec::with_capacity(owners.len());
    for owner in owners {
        let value = owner.get(column);
        if value.is_some() {
            keys.push(Some(key_or_error(&value, &name)?));
            values.push(value);
        } else {
            keys.push(None);
        }
    }
    Ok((values, keys))
}

/// `SELECT owner AS owner_key, <total> AS total FROM rows WHERE owner IN (...) GROUP BY
/// owner`, one result per owner (or `None` when it has no rows).
async fn grouped<R, O, Db>(
    db: &Db,
    owners: &[O],
    related: Option<Select<R>>,
    total: Expr,
) -> Result<Grouped, DbErr>
where
    R: EntityTrait,
    O: ModelTrait<Entity: Related<R>> + Sync,
    Db: ConnectionTrait,
{
    let path = Path::of::<O::Entity, R>()?;
    let (values, keys) = owner_values(owners, &path)?;
    if values.is_empty() {
        return Ok(Grouped {
            keys,
            rows: HashMap::new(),
        });
    }

    let owner = (ROWS, path.column.clone());
    let mut query: SelectStatement = Query::select();
    query
        .expr_as(Expr::col(owner.clone()), "owner_key")
        .expr_as(total, "total")
        .from_as(path.table.clone(), ROWS.into_iden())
        .and_where(Expr::col(owner.clone()).is_in(values))
        .group_by_col(owner);
    if let Some((junction, target)) = &path.junction {
        query.join(
            JoinType::InnerJoin,
            R::default(),
            Expr::col((ROWS, junction.clone())).equals((R::default(), target.clone())),
        );
    }
    if let Some(related) = related {
        // Through a junction, its column points at a column of the related rows;
        // otherwise the counted rows are the related rows themselves.
        let condition = match &path.junction {
            Some((junction, target)) => Expr::col((ROWS, junction.clone())).in_subquery(
                related
                    .select_only()
                    .expr(Expr::col(target.clone()))
                    .into_query(),
            ),
            None => Expr::col((ROWS, primary_column::<R>())).in_subquery(keys_of(related)),
        };
        query.and_where(condition);
    }

    let mut rows = HashMap::new();
    for row in db.query_all(&query).await? {
        rows.insert(Key::read(&row, "owner_key")?, row);
    }
    Ok(Grouped { keys, rows })
}

/// The result rows of a grouped query, keyed by owner, and the owners' keys in order.
struct Grouped {
    keys: Vec<Option<Key>>,
    rows: HashMap<Key, QueryResult>,
}

impl Grouped {
    /// `read` applied to each owner's row, in the order of the owners; `missing` for
    /// owners without one.
    fn per_owner<T>(
        &self,
        missing: T,
        read: impl Fn(&QueryResult) -> Result<T, DbErr>,
    ) -> Result<Vec<T>, DbErr>
    where
        T: Clone,
    {
        self.keys
            .iter()
            .map(|key| {
                key.as_ref()
                    .and_then(|key| self.rows.get(key))
                    .map_or_else(|| Ok(missing.clone()), &read)
            })
            .collect()
    }
}

fn read_count(row: &QueryResult) -> Result<u64, DbErr> {
    row.try_get::<i64>("", "total").map(i64::unsigned_abs)
}

/// `CAST(expr AS DOUBLE PRECISION)`, so every backend returns a float for any
/// numeric column.
pub fn as_double(backend: DbBackend, expr: Expr) -> Expr {
    let double = match backend {
        DbBackend::MySql => "DOUBLE",
        _ => "DOUBLE PRECISION",
    };
    Func::cast_as(expr, double).into()
}