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
//! The owner of a polymorphic child, which can be one of several entities.

use std::future::Future;

use sea_orm::{ColumnTrait, ConnectionTrait, DbErr, QueryFilter};

use crate::key::{primary_column, values_for, Key};
use crate::morph::Morphable;

/// The possible owners of a polymorphic child, as one enum.
///
/// A comment's owner may be a post or a video, so the result is an enum with one
/// variant per owner entity. Declare it with [`morph_target!`](crate::morph_target), which
/// writes this impl for you.
pub trait MorphTarget: Sized + Send {
    /// The morph types this enum covers.
    fn morph_types() -> Vec<&'static str>;

    /// Loads the owners of one morph type by key, in one query.
    ///
    /// # Errors
    ///
    /// On a database error, or when `morph_type` is not one of [`Self::morph_types`].
    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;
}

/// Declares the possible owners of a polymorphic child as an enum, and implements
/// [`MorphTarget`] for it.
///
/// ```
/// # 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 {} }
/// # mod videos { use sea_orm::entity::prelude::*;
/// #   #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
/// #   #[sea_orm(table_name = "videos")]
/// #   pub struct Model { #[sea_orm(primary_key)] pub id: i64 }
/// #   #[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"; }
/// # impl Morphable for videos::Entity { const MORPH_TYPE: &'static str = "video"; }
/// sea_orm_relations_kit::morph_target! {
///     /// Whatever a comment can be left on.
///     #[derive(Clone, Debug)]
///     pub enum Commentable {
///         Post(posts::Entity),
///         Video(videos::Entity),
///     }
/// }
///
/// let owner = Commentable::Post(posts::Model { id: 1 });
/// assert_eq!(owner.morph_type(), "post");
/// ```
#[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 {
            /// The morph type of this owner, as stored in the `*_type` column.
            #[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(),
                    ))
                }
            }
        }
    };
}

/// The rows of `E` with the given keys, each with its key.
#[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())
}

/// The error for a stored morph type the owner enum does not cover: a typo or a
/// missing variant should fail loudly, not read as "no owner".
#[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(", ")
    ))
}