1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Aggregate {
26 Sum,
28 Avg,
30 Min,
32 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
47pub 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
97pub 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
116pub 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
134pub 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
162pub 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
201pub 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
220pub 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
239const ROWS: &str = "related_rows";
241
242struct Path {
244 owner_column: DynIden,
246 table: TableRef,
248 column: DynIden,
250 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
284fn 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
308async 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 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
367struct Grouped {
369 keys: Vec<Option<Key>>,
370 rows: HashMap<Key, QueryResult>,
371}
372
373impl Grouped {
374 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
399pub 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}