use std::future::Future;
use sea_orm::{ColumnTrait, ConnectionTrait, DbErr, QueryFilter};
use crate::key::{primary_column, values_for, Key};
use crate::morph::Morphable;
pub trait MorphTarget: Sized + Send {
fn morph_types() -> Vec<&'static str>;
fn load_type<'a, Db: ConnectionTrait>(
db: &'a Db,
morph_type: &'a str,
keys: Vec<Key>,
) -> impl Future<Output = Result<Vec<(Key, Self)>, DbErr>> + Send + 'a;
}
#[macro_export]
macro_rules! morph_target {
(
$(#[$meta:meta])*
$vis:vis enum $name:ident {
$($variant:ident($entity:path)),+ $(,)?
}
) => {
$(#[$meta])*
$vis enum $name {
$(
#[allow(missing_docs)]
$variant(<$entity as $crate::__private::EntityTrait>::Model),
)+
}
impl $name {
#[allow(dead_code)]
pub fn morph_type(&self) -> &'static str {
match self {
$(Self::$variant(_) => <$entity as $crate::Morphable>::MORPH_TYPE,)+
}
}
}
impl $crate::MorphTarget for $name {
fn morph_types() -> ::std::vec::Vec<&'static str> {
::std::vec![$(<$entity as $crate::Morphable>::MORPH_TYPE),+]
}
fn load_type<'a, Db: $crate::__private::ConnectionTrait>(
db: &'a Db,
morph_type: &'a str,
keys: ::std::vec::Vec<$crate::Key>,
) -> impl ::std::future::Future<
Output = ::std::result::Result<
::std::vec::Vec<($crate::Key, Self)>,
$crate::__private::DbErr,
>,
> + Send + 'a {
async move {
$(
if morph_type == <$entity as $crate::Morphable>::MORPH_TYPE {
let rows = $crate::__private::find_by_keys::<$entity, Db>(db, &keys).await?;
return Ok(rows
.into_iter()
.map(|(key, row)| (key, Self::$variant(row)))
.collect());
}
)+
Err($crate::__private::unknown_type(
morph_type,
&<Self as $crate::MorphTarget>::morph_types(),
))
}
}
}
};
}
#[doc(hidden)]
pub async fn find_by_keys<E, Db>(db: &Db, keys: &[Key]) -> Result<Vec<(Key, E::Model)>, DbErr>
where
E: Morphable,
Db: ConnectionTrait,
{
if keys.is_empty() {
return Ok(Vec::new());
}
let column = primary_column::<E>();
let rows = E::find()
.filter(column.is_in(values_for(keys, column)?))
.all(db)
.await?;
Ok(rows
.into_iter()
.filter_map(|row| Key::of(&row).map(|key| (key, row)))
.collect())
}
#[doc(hidden)]
#[must_use]
pub fn unknown_type(morph_type: &str, known: &[&str]) -> DbErr {
DbErr::Type(format!(
"unknown morph type `{morph_type}`; this relation knows {}",
known.join(", ")
))
}