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};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Aggregate {
Sum,
Avg,
Min,
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(),
}
}
}
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)
}
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)
}
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())
}
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"))
}
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
}
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
}
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
}
const ROWS: &str = "related_rows";
struct Path {
owner_column: DynIden,
table: TableRef,
column: DynIden,
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(),
)),
}
}
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))
}
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 {
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 })
}
struct Grouped {
keys: Vec<Option<Key>>,
rows: HashMap<Key, QueryResult>,
}
impl Grouped {
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)
}
pub fn as_double(backend: DbBackend, expr: Expr) -> Expr {
let double = match backend {
DbBackend::MySql => "DOUBLE",
_ => "DOUBLE PRECISION",
};
Func::cast_as(expr, double).into()
}