sea_orm_relations_kit/target.rs
1//! The owner of a polymorphic child, which can be one of several entities.
2
3use std::future::Future;
4
5use sea_orm::{ColumnTrait, ConnectionTrait, DbErr, QueryFilter};
6
7use crate::key::{primary_column, values_for, Key};
8use crate::morph::Morphable;
9
10/// The possible owners of a polymorphic child, as one enum.
11///
12/// A comment's owner may be a post or a video, so the result is an enum with one
13/// variant per owner entity. Declare it with [`morph_target!`](crate::morph_target), which
14/// writes this impl for you.
15pub trait MorphTarget: Sized + Send {
16 /// The morph types this enum covers.
17 fn morph_types() -> Vec<&'static str>;
18
19 /// Loads the owners of one morph type by key, in one query.
20 ///
21 /// # Errors
22 ///
23 /// On a database error, or when `morph_type` is not one of [`Self::morph_types`].
24 fn load_type<'a, Db: ConnectionTrait>(
25 db: &'a Db,
26 morph_type: &'a str,
27 keys: Vec<Key>,
28 ) -> impl Future<Output = Result<Vec<(Key, Self)>, DbErr>> + Send + 'a;
29}
30
31/// Declares the possible owners of a polymorphic child as an enum, and implements
32/// [`MorphTarget`] for it.
33///
34/// ```
35/// # mod posts { use sea_orm::entity::prelude::*;
36/// # #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
37/// # #[sea_orm(table_name = "posts")]
38/// # pub struct Model { #[sea_orm(primary_key)] pub id: i32 }
39/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
40/// # impl ActiveModelBehavior for ActiveModel {} }
41/// # mod videos { use sea_orm::entity::prelude::*;
42/// # #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
43/// # #[sea_orm(table_name = "videos")]
44/// # pub struct Model { #[sea_orm(primary_key)] pub id: i64 }
45/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {}
46/// # impl ActiveModelBehavior for ActiveModel {} }
47/// # use sea_orm_relations_kit::Morphable;
48/// # impl Morphable for posts::Entity { const MORPH_TYPE: &'static str = "post"; }
49/// # impl Morphable for videos::Entity { const MORPH_TYPE: &'static str = "video"; }
50/// sea_orm_relations_kit::morph_target! {
51/// /// Whatever a comment can be left on.
52/// #[derive(Clone, Debug)]
53/// pub enum Commentable {
54/// Post(posts::Entity),
55/// Video(videos::Entity),
56/// }
57/// }
58///
59/// let owner = Commentable::Post(posts::Model { id: 1 });
60/// assert_eq!(owner.morph_type(), "post");
61/// ```
62#[macro_export]
63macro_rules! morph_target {
64 (
65 $(#[$meta:meta])*
66 $vis:vis enum $name:ident {
67 $($variant:ident($entity:path)),+ $(,)?
68 }
69 ) => {
70 $(#[$meta])*
71 $vis enum $name {
72 $(
73 #[allow(missing_docs)]
74 $variant(<$entity as $crate::__private::EntityTrait>::Model),
75 )+
76 }
77
78 impl $name {
79 /// The morph type of this owner, as stored in the `*_type` column.
80 #[allow(dead_code)]
81 pub fn morph_type(&self) -> &'static str {
82 match self {
83 $(Self::$variant(_) => <$entity as $crate::Morphable>::MORPH_TYPE,)+
84 }
85 }
86 }
87
88 impl $crate::MorphTarget for $name {
89 fn morph_types() -> ::std::vec::Vec<&'static str> {
90 ::std::vec![$(<$entity as $crate::Morphable>::MORPH_TYPE),+]
91 }
92
93 fn load_type<'a, Db: $crate::__private::ConnectionTrait>(
94 db: &'a Db,
95 morph_type: &'a str,
96 keys: ::std::vec::Vec<$crate::Key>,
97 ) -> impl ::std::future::Future<
98 Output = ::std::result::Result<
99 ::std::vec::Vec<($crate::Key, Self)>,
100 $crate::__private::DbErr,
101 >,
102 > + Send + 'a {
103 async move {
104 $(
105 if morph_type == <$entity as $crate::Morphable>::MORPH_TYPE {
106 let rows = $crate::__private::find_by_keys::<$entity, Db>(db, &keys).await?;
107 return Ok(rows
108 .into_iter()
109 .map(|(key, row)| (key, Self::$variant(row)))
110 .collect());
111 }
112 )+
113 Err($crate::__private::unknown_type(
114 morph_type,
115 &<Self as $crate::MorphTarget>::morph_types(),
116 ))
117 }
118 }
119 }
120 };
121}
122
123/// The rows of `E` with the given keys, each with its key.
124#[doc(hidden)]
125pub async fn find_by_keys<E, Db>(db: &Db, keys: &[Key]) -> Result<Vec<(Key, E::Model)>, DbErr>
126where
127 E: Morphable,
128 Db: ConnectionTrait,
129{
130 if keys.is_empty() {
131 return Ok(Vec::new());
132 }
133 let column = primary_column::<E>();
134 let rows = E::find()
135 .filter(column.is_in(values_for(keys, column)?))
136 .all(db)
137 .await?;
138 Ok(rows
139 .into_iter()
140 .filter_map(|row| Key::of(&row).map(|key| (key, row)))
141 .collect())
142}
143
144/// The error for a stored morph type the owner enum does not cover: a typo or a
145/// missing variant should fail loudly, not read as "no owner".
146#[doc(hidden)]
147#[must_use]
148pub fn unknown_type(morph_type: &str, known: &[&str]) -> DbErr {
149 DbErr::Type(format!(
150 "unknown morph type `{morph_type}`; this relation knows {}",
151 known.join(", ")
152 ))
153}