1use std::any::TypeId;
7use std::borrow::Cow;
8use std::fmt;
9use std::marker::PhantomData;
10use std::sync::Arc;
11
12use navree_kernel::BoxFuture;
13
14use crate::collection::Collection;
15use crate::column::Filter;
16use crate::error::{OrmError, Result};
17use crate::exec::{Access, Executor, Target};
18use crate::ir::{Boolean, Expr, Operator, QueryIr, Where, WhereClause};
19use crate::model::{Model, ModelMeta};
20use crate::query::filters::HasWheres;
21use crate::query::{Builder, WhereGroup};
22use crate::record::Record;
23use crate::relations::access::AccessConstraint;
24use crate::relations::any::AnyRecord;
25use crate::relations::core::{column_value, qualified};
26use crate::relations::eager::{Constraint, ConstraintFn, EagerNode, EagerTree};
27use crate::relations::existence::{
28 ExistsRequest, ExistsSelect, Refine, build_subquery, columns_equal,
29};
30use crate::relations::keys::{RelationKey, distinct_keys, in_keys, in_keys_on, key_of};
31use crate::relations::morph_map::{MorphMap, type_name_of};
32use crate::relations::path::{ParsedPath, RelationPath};
33use crate::relations::registry::{ErasedRelation, RelationKind, RelationMeta, find};
34use crate::relations::{Relation, private};
35use crate::value::{Value, is_null};
36
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub(crate) enum Trashed {
40 #[default]
42 Without,
43 With,
45 Only,
47}
48
49impl Trashed {
50 fn apply<M: Model>(self, query: Builder<M>) -> Builder<M> {
51 match self {
52 Trashed::Without => query,
53 Trashed::With => query.with_trashed(),
54 Trashed::Only => match M::meta().deleted_at() {
55 Some(column) => query.with_trashed().where_(Filter::from(Where::Null {
56 expr: Expr::Column(qualified(M::meta().table(), column)),
57 not: true,
58 })),
59 None => query,
60 },
61 }
62 }
63}
64
65#[derive(Clone, Debug)]
67pub struct MorphTypeLoads {
68 type_id: TypeId,
69 model: &'static str,
70 with: EagerTree,
71 counts: Vec<String>,
72 constraints: Vec<Constraint>,
73 errors: Vec<String>,
74}
75
76impl MorphTypeLoads {
77 fn new<M: Model>() -> Self {
78 MorphTypeLoads {
79 type_id: TypeId::of::<M>(),
80 model: M::meta().name(),
81 with: EagerTree::default(),
82 counts: Vec::new(),
83 constraints: Vec::new(),
84 errors: Vec::new(),
85 }
86 }
87
88 fn merge(&mut self, other: &MorphTypeLoads) {
89 self.with.merge(&other.with);
90 self.counts.extend(other.counts.iter().cloned());
91 self.constraints.extend(other.constraints.iter().cloned());
92 self.errors.extend(other.errors.iter().cloned());
93 }
94
95 fn apply<M: Model>(&self, mut query: Builder<M>) -> Result<Builder<M>> {
97 if let Some(error) = self.errors.first() {
98 return Err(OrmError::invalid(error.clone()));
99 }
100 for constraint in &self.constraints {
101 match constraint
102 .closure
103 .downcast_ref::<ConstraintFn<Builder<M>>>()
104 {
105 Some(apply) => query = (apply.0)(query),
106 None => {
107 return Err(OrmError::invalid(format!(
108 "a morph constraint for {} takes `{}`",
109 self.model, constraint.takes
110 )));
111 }
112 }
113 }
114 query.eager.tree.merge(&self.with);
115 for count in &self.counts {
116 query = query.with_count(count.as_str());
117 }
118 Ok(query)
119 }
120}
121
122#[derive(Clone, Debug, Default)]
145pub struct MorphWith {
146 types: Vec<MorphTypeLoads>,
147}
148
149impl MorphWith {
150 pub fn new() -> Self {
152 MorphWith::default()
153 }
154
155 fn loads<M: Model>(&mut self) -> &mut MorphTypeLoads {
156 let index = match self
157 .types
158 .iter()
159 .position(|loads| loads.type_id == TypeId::of::<M>())
160 {
161 Some(index) => index,
162 None => {
163 self.types.push(MorphTypeLoads::new::<M>());
164 self.types.len() - 1
165 }
166 };
167 &mut self.types[index]
168 }
169
170 pub fn on<M: Model>(mut self, paths: impl IntoIterator<Item = impl RelationPath<M>>) -> Self {
172 let loads = self.loads::<M>();
173 for path in paths {
174 let text = path.relation_path().into_owned();
175 match ParsedPath::parse(&text) {
176 Ok(parsed) => {
177 let node = loads.with.entry(&parsed.segments);
178 if parsed.columns.is_some() {
179 node.columns = parsed.columns;
180 }
181 }
182 Err(error) => loads.errors.push(error.to_string()),
183 }
184 }
185 self
186 }
187
188 pub fn count_on<M: Model>(
191 mut self,
192 paths: impl IntoIterator<Item = impl RelationPath<M>>,
193 ) -> Self {
194 let loads = self.loads::<M>();
195 for path in paths {
196 loads.counts.push(path.relation_path().into_owned());
197 }
198 self
199 }
200
201 pub fn constrain<M: Model>(
203 mut self,
204 constraint: impl Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
205 ) -> Self {
206 self.loads::<M>()
207 .constraints
208 .push(Constraint::new(constraint));
209 self
210 }
211
212 pub(crate) fn merge(&mut self, other: &MorphWith) {
214 for loads in &other.types {
215 match self
216 .types
217 .iter_mut()
218 .find(|existing| existing.type_id == loads.type_id)
219 {
220 Some(existing) => existing.merge(loads),
221 None => self.types.push(loads.clone()),
222 }
223 }
224 }
225
226 pub(crate) fn for_type(&self, type_id: TypeId) -> Option<&MorphTypeLoads> {
228 self.types.iter().find(|loads| loads.type_id == type_id)
229 }
230}
231
232pub struct MorphLoad<'a> {
234 pub(crate) owner_key: Option<&'a str>,
236 pub(crate) keys: &'a [(RelationKey, Value)],
238 pub(crate) loads: Option<&'a MorphTypeLoads>,
240 pub(crate) children: &'a EagerTree,
242 pub(crate) conditions: &'a [Filter],
244 pub(crate) access: &'a [AccessConstraint],
246 pub(crate) trashed: Trashed,
248}
249
250pub struct MorphExists<'a> {
252 pub(crate) parent: &'static ModelMeta,
254 pub(crate) id_column: &'a str,
256 pub(crate) owner_key: Option<&'a str>,
258 pub(crate) depth: u32,
260 pub(crate) select: ExistsSelect,
262 pub(crate) condition: Option<Filter>,
264 pub(crate) trashed: Trashed,
266}
267
268pub trait MorphTarget: Send + Sync + 'static {
270 fn type_id(&self) -> TypeId;
272
273 fn morph_name(&self) -> Cow<'static, str>;
275
276 fn normalize_key(&self, value: Value, owner_key: Option<&str>) -> Value;
279
280 fn load<'a, 'b>(
282 &'a self,
283 target: &'a Target<'b>,
284 request: MorphLoad<'a>,
285 ) -> BoxFuture<'a, Result<Vec<(RelationKey, AnyRecord)>>>;
286
287 fn load_into<'a, 'b>(
290 &'a self,
291 target: &'a Target<'b>,
292 records: Vec<AnyRecord>,
293 loads: &'a MorphTypeLoads,
294 aggregate: Option<&'a crate::relations::aggregates::AggregateSpec>,
295 ) -> BoxFuture<'a, Result<Vec<AnyRecord>>>;
296
297 fn load_missing_into<'a, 'b>(
299 &'a self,
300 target: &'a Target<'b>,
301 records: Vec<AnyRecord>,
302 rest: &'a EagerTree,
303 ) -> BoxFuture<'a, Result<Vec<AnyRecord>>>;
304
305 fn exists_query(&self, request: MorphExists<'_>) -> Result<QueryIr>;
307}
308
309fn typed_records<M: Model>(records: Vec<AnyRecord>) -> Result<Vec<Record<M>>> {
311 records
312 .into_iter()
313 .map(|record| {
314 record.downcast::<M>().map_err(|other| {
315 OrmError::invalid(format!(
316 "a {} among the {} records of a morph load",
317 other.model_name(),
318 M::meta().name()
319 ))
320 })
321 })
322 .collect()
323}
324
325pub(crate) struct MorphTargetOf<M: Model>(PhantomData<fn() -> M>);
327
328impl<M: Model> MorphTargetOf<M> {
329 pub(crate) fn new() -> Self {
330 MorphTargetOf(PhantomData)
331 }
332}
333
334impl<M: Model> MorphTarget for MorphTargetOf<M> {
335 fn type_id(&self) -> TypeId {
336 TypeId::of::<M>()
337 }
338
339 fn morph_name(&self) -> Cow<'static, str> {
340 M::morph_name()
341 }
342
343 fn normalize_key(&self, value: Value, owner_key: Option<&str>) -> Value {
344 match owner_key {
345 Some(column) if column != M::meta().key_column() => value,
346 _ => match <M::Key as crate::Field>::from_value(value.clone()) {
347 Ok(key) => crate::Field::to_value(&key),
348 Err(_) => value,
349 },
350 }
351 }
352
353 fn load<'a, 'b>(
354 &'a self,
355 target: &'a Target<'b>,
356 request: MorphLoad<'a>,
357 ) -> BoxFuture<'a, Result<Vec<(RelationKey, AnyRecord)>>> {
358 Box::pin(async move {
359 let meta = M::meta();
360 let keys = distinct_keys(
361 request
362 .keys
363 .iter()
364 .map(|(_, value)| self.normalize_key(value.clone(), request.owner_key)),
365 );
366 let owner_key = request.owner_key.unwrap_or(meta.key_column());
367 let mut query = request
368 .trashed
369 .apply(Builder::<M>::new().with_relation_defaults());
370 if let Some(loads) = request.loads {
371 query = loads.apply(query)?;
372 }
373 for condition in request.conditions {
374 query = query.where_(condition.clone());
375 }
376 for access in request.access {
377 query = access.apply(query)?;
378 }
379 query.eager.tree.merge(request.children);
380 let query = query.where_(Filter::from(in_keys_on(
381 target,
382 qualified(meta.table(), owner_key),
383 &keys,
384 )));
385 let records = query.fetch(target).await?;
386 let mut found = Vec::with_capacity(records.len());
387 for record in records {
388 let value = column_value(&record.model, owner_key, "morph_to")?;
389 if let Some(key) = key_of(&value) {
390 found.push((key, AnyRecord::new(record)));
391 }
392 }
393 Ok(found)
394 })
395 }
396
397 fn load_into<'a, 'b>(
398 &'a self,
399 target: &'a Target<'b>,
400 records: Vec<AnyRecord>,
401 loads: &'a MorphTypeLoads,
402 aggregate: Option<&'a crate::relations::aggregates::AggregateSpec>,
403 ) -> BoxFuture<'a, Result<Vec<AnyRecord>>> {
404 Box::pin(async move {
405 let mut typed = typed_records::<M>(records)?;
406 match aggregate {
407 None => {
408 crate::relations::eager::load_tree(target, &mut typed, &loads.with).await?;
409 if !loads.counts.is_empty() {
410 let count = crate::relations::aggregates::AggregateSpec::count();
411 crate::relations::aggregates::load_aggregate_on(
412 target,
413 &mut typed,
414 &loads.counts,
415 &count,
416 )
417 .await?;
418 }
419 }
420 Some(spec) => {
421 let mut paths: Vec<String> = loads
424 .with
425 .paths()
426 .into_iter()
427 .filter(|path| !path.contains('.'))
428 .collect();
429 for counted in &loads.counts {
430 if !paths.contains(counted) {
431 paths.push(counted.clone());
432 }
433 }
434 crate::relations::aggregates::load_aggregate_on(
435 target, &mut typed, &paths, spec,
436 )
437 .await?;
438 }
439 }
440 Ok(typed.into_iter().map(AnyRecord::new).collect())
441 })
442 }
443
444 fn load_missing_into<'a, 'b>(
445 &'a self,
446 target: &'a Target<'b>,
447 records: Vec<AnyRecord>,
448 rest: &'a EagerTree,
449 ) -> BoxFuture<'a, Result<Vec<AnyRecord>>> {
450 Box::pin(async move {
451 let mut typed = typed_records::<M>(records)?;
452 crate::relations::lazy::load_missing_tree(target, &mut typed, rest).await?;
453 Ok(typed.into_iter().map(AnyRecord::new).collect())
454 })
455 }
456
457 fn exists_query(&self, request: MorphExists<'_>) -> Result<QueryIr> {
458 let meta = M::meta();
459 let owner_key = request.owner_key.unwrap_or(meta.key_column()).to_owned();
460 let aliased = (meta.table() == request.parent.table()).then_some(meta.table());
461 let definition = request.trashed.apply(Builder::<M>::new());
462 let refine = match request.condition {
463 Some(filter) => Refine::Filter(filter),
464 None => Refine::None,
465 };
466 let outer = qualified(request.parent.table(), request.id_column);
467 build_subquery::<M>(
468 request.parent,
469 &definition,
470 ExistsRequest {
471 depth: request.depth,
472 select: request.select,
473 refine,
474 },
475 "morph_to",
476 aliased,
477 |query, _| query,
478 |alias| {
479 vec![columns_equal(
480 outer,
481 qualified(alias.unwrap_or(meta.table()), &owner_key),
482 )]
483 },
484 )
485 }
486}
487
488pub trait MorphTargets {
491 #[doc(hidden)]
492 fn morph_targets() -> Vec<Arc<dyn MorphTarget>>;
493}
494
495macro_rules! morph_targets {
496 ($($model:ident),+) => {
497 impl<$($model: Model),+> MorphTargets for ($($model,)+) {
498 fn morph_targets() -> Vec<Arc<dyn MorphTarget>> {
499 vec![$(Arc::new(MorphTargetOf::<$model>::new()) as Arc<dyn MorphTarget>),+]
500 }
501 }
502 };
503}
504
505morph_targets!(A);
506morph_targets!(A, B);
507morph_targets!(A, B, C);
508morph_targets!(A, B, C, D);
509morph_targets!(A, B, C, D, E);
510morph_targets!(A, B, C, D, E, F);
511morph_targets!(A, B, C, D, E, F, G);
512morph_targets!(A, B, C, D, E, F, G, H);
513
514pub struct MorphTo<P: Model> {
536 pub(crate) name: Cow<'static, str>,
537 pub(crate) parent: Option<P>,
538 pub(crate) type_column: Cow<'static, str>,
539 pub(crate) id_column: Cow<'static, str>,
540 pub(crate) owner_key: Option<Cow<'static, str>>,
541 pub(crate) targets: Vec<Arc<dyn MorphTarget>>,
542 pub(crate) trashed: Trashed,
543 pub(crate) with: MorphWith,
544}
545
546impl<P: Model> Clone for MorphTo<P> {
547 fn clone(&self) -> Self {
548 MorphTo {
549 name: self.name.clone(),
550 parent: self.parent.clone(),
551 type_column: self.type_column.clone(),
552 id_column: self.id_column.clone(),
553 owner_key: self.owner_key.clone(),
554 targets: self.targets.clone(),
555 trashed: self.trashed,
556 with: self.with.clone(),
557 }
558 }
559}
560
561impl<P: Model> fmt::Debug for MorphTo<P> {
562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 f.debug_struct("MorphTo")
564 .field("parent", &P::meta().name())
565 .field("name", &self.name)
566 .field("type_column", &self.type_column)
567 .field("id_column", &self.id_column)
568 .finish_non_exhaustive()
569 }
570}
571
572impl<P: Model> MorphTo<P> {
573 pub(crate) fn new(parent: Option<P>, name: &str) -> Self {
576 MorphTo {
577 name: Cow::Owned(name.to_owned()),
578 parent,
579 type_column: Cow::Owned(format!("{name}_type")),
580 id_column: Cow::Owned(format!("{name}_id")),
581 owner_key: None,
582 targets: Vec::new(),
583 trashed: Trashed::Without,
584 with: MorphWith::new(),
585 }
586 }
587
588 pub fn named(mut self, name: impl Into<Cow<'static, str>>) -> Self {
590 self.name = name.into();
591 self
592 }
593
594 pub fn type_column(mut self, column: impl Into<Cow<'static, str>>) -> Self {
596 self.type_column = column.into();
597 self
598 }
599
600 pub fn id_column(mut self, column: impl Into<Cow<'static, str>>) -> Self {
602 self.id_column = column.into();
603 self
604 }
605
606 pub fn owner_key(mut self, column: impl Into<Cow<'static, str>>) -> Self {
609 self.owner_key = Some(column.into());
610 self
611 }
612
613 pub fn target<M: Model>(mut self) -> Self {
615 self.targets
616 .retain(|target| target.type_id() != TypeId::of::<M>());
617 self.targets.push(Arc::new(MorphTargetOf::<M>::new()));
618 self
619 }
620
621 pub fn targets<T: MorphTargets>(mut self) -> Self {
623 for target in T::morph_targets() {
624 self.targets
625 .retain(|existing| existing.type_id() != target.type_id());
626 self.targets.push(target);
627 }
628 self
629 }
630
631 pub fn with_trashed(mut self) -> Self {
633 self.trashed = Trashed::With;
634 self
635 }
636
637 pub fn without_trashed(mut self) -> Self {
639 self.trashed = Trashed::Without;
640 self
641 }
642
643 pub fn only_trashed(mut self) -> Self {
645 self.trashed = Trashed::Only;
646 self
647 }
648
649 pub fn morph_with(mut self, with: MorphWith) -> Self {
651 self.with.merge(&with);
652 self
653 }
654
655 pub fn constrain<M: Model>(
657 mut self,
658 constraint: impl Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
659 ) -> Self {
660 self.with = std::mem::take(&mut self.with).constrain(constraint);
661 self
662 }
663
664 pub fn relation_name(&self) -> &str {
666 &self.name
667 }
668
669 pub fn morph_type(&self) -> &str {
671 &self.type_column
672 }
673
674 pub fn foreign_key_name(&self) -> &str {
676 &self.id_column
677 }
678
679 pub fn qualified_foreign_key_name(&self) -> String {
681 format!("{}.{}", P::meta().table(), self.id_column)
682 }
683
684 pub fn owner_key_name(&self) -> Option<&str> {
687 self.owner_key.as_deref()
688 }
689
690 pub(crate) fn resolve(&self, name: &str) -> Result<Arc<dyn MorphTarget>> {
693 if let Some(target) = self
694 .targets
695 .iter()
696 .find(|target| target.morph_name() == name)
697 {
698 return Ok(Arc::clone(target));
699 }
700 match MorphMap::current().entry(name) {
701 Some(entry) => Ok(Arc::clone(&entry.target)),
702 None => Err(OrmError::UnknownMorph {
703 name: name.to_owned(),
704 }),
705 }
706 }
707
708 pub(crate) fn all_targets(&self) -> Vec<Arc<dyn MorphTarget>> {
711 if !self.targets.is_empty() {
712 return self.targets.clone();
713 }
714 MorphMap::current()
715 .entries()
716 .iter()
717 .map(|entry| Arc::clone(&entry.target))
718 .collect()
719 }
720
721 pub async fn get<E: Executor + ?Sized>(self, exec: &E) -> Result<Option<AnyRecord>> {
723 let parent = match &self.parent {
724 Some(parent) => parent.clone(),
725 None => {
726 return Err(OrmError::invalid(format!(
727 "the relation `{}` of {} was not made from a record",
728 self.name,
729 P::meta().name()
730 )));
731 }
732 };
733 let target = exec.target(Access::Read).await?;
734 let mut records = [Record::stored(parent)];
735 let node = EagerNode {
736 name: self.name.to_string(),
737 ..EagerNode::default()
738 };
739 self.load_into(&target, &mut records, &node).await?;
740 let [record] = records;
741 Ok(record
742 .relations
743 .get::<Option<AnyRecord>>(&self.name)
744 .cloned()
745 .flatten())
746 }
747
748 pub fn is<M: Model>(&self, record: &Record<M>) -> bool {
751 let Some(parent) = &self.parent else {
752 return false;
753 };
754 let (Ok(stored_type), Ok(stored_id)) = (
755 column_value(parent, &self.type_column, &self.name),
756 column_value(parent, &self.id_column, &self.name),
757 ) else {
758 return false;
759 };
760 let owner = match &self.owner_key {
761 Some(column) => match record.model.value(column) {
762 Ok(Some(value)) => value,
763 _ => return false,
764 },
765 None => crate::Field::to_value(&record.key()),
766 };
767 let type_matches = match &stored_type {
768 Value::String(stored) => *stored == M::morph_name(),
769 _ => false,
770 };
771 type_matches
772 && key_of(&stored_id).is_some()
773 && key_of(&stored_id) == key_of(&owner)
774 && M::meta().connection_name() == P::meta().connection_name()
775 }
776
777 pub fn is_not<M: Model>(&self, record: &Record<M>) -> bool {
779 !self.is(record)
780 }
781
782 async fn load_into(
784 &self,
785 target: &Target<'_>,
786 parents: &mut [Record<P>],
787 node: &EagerNode,
788 ) -> Result<()> {
789 let mut relation = self.clone();
790 let mut conditions: Vec<Filter> = Vec::new();
791 let mut access: Vec<AccessConstraint> = Vec::new();
792 for constraint in &node.constraints {
793 if let Some(filter) = constraint.filter() {
794 conditions.push(filter.clone());
795 continue;
796 }
797 if let Some(constraint) = constraint.access() {
798 access.push(constraint.clone());
799 continue;
800 }
801 match constraint
802 .closure
803 .downcast_ref::<ConstraintFn<MorphTo<P>>>()
804 {
805 Some(apply) => relation = (apply.0)(relation),
806 None => {
807 return Err(OrmError::invalid(format!(
808 "the constraint on morph_to relation `{}` of {} takes `{}`: constrain a MorphTo<{}>, or each model with MorphWith::constrain",
809 node.name,
810 P::meta().name(),
811 constraint.takes,
812 P::meta().name()
813 )));
814 }
815 }
816 }
817 let mut with = relation.with.clone();
818 if let Some(per_type) = &node.morph {
819 with.merge(per_type);
820 }
821 let mut groups: Vec<(String, Vec<(usize, Value)>)> = Vec::new();
824 for (index, parent) in parents.iter().enumerate() {
825 let stored_type = column_value(&parent.model, &relation.type_column, &relation.name)?;
826 let id = column_value(&parent.model, &relation.id_column, &relation.name)?;
827 let name = match stored_type {
828 Value::String(name) if !name.is_empty() => name,
829 _ => continue,
830 };
831 if is_null(&id) {
832 continue;
833 }
834 match groups.iter_mut().find(|(existing, _)| *existing == name) {
835 Some((_, members)) => members.push((index, id)),
836 None => groups.push((name, vec![(index, id)])),
837 }
838 }
839 let mut found: Vec<Option<AnyRecord>> = vec![None; parents.len()];
840 for (name, members) in groups {
841 let morph_target = relation.resolve(&name)?;
842 let keys = distinct_keys(members.iter().map(|(_, id)| id.clone()));
843 let records = morph_target
844 .load(
845 target,
846 MorphLoad {
847 owner_key: relation.owner_key.as_deref(),
848 keys: &keys,
849 loads: with.for_type(morph_target.type_id()),
850 children: &node.children,
851 conditions: &conditions,
852 access: &access,
853 trashed: relation.trashed,
854 },
855 )
856 .await?;
857 for (index, id) in members {
858 let key = key_of(&morph_target.normalize_key(id, relation.owner_key.as_deref()));
859 if let Some((_, record)) = records
860 .iter()
861 .find(|(found_key, _)| Some(found_key) == key.as_ref())
862 {
863 found[index] = Some(record.clone());
864 }
865 }
866 }
867 for (parent, value) in parents.iter_mut().zip(found) {
868 parent.relations.set_relation(node.name.clone(), value);
869 }
870 Ok(())
871 }
872
873 pub(crate) fn has_morph_where(
877 &self,
878 depth: u32,
879 types: Option<&[String]>,
880 op: Operator,
881 count: u64,
882 refine: &mut dyn FnMut(&str) -> Option<Filter>,
883 ) -> Result<Where> {
884 let targets = match types {
885 Some(names) => names
886 .iter()
887 .map(|name| self.resolve(name))
888 .collect::<Result<Vec<_>>>()?,
889 None => self.all_targets(),
890 };
891 let count_i = i64::try_from(count).unwrap_or(i64::MAX);
892 let check_null = types.is_none()
893 && match op {
894 Operator::Lt => count >= 1,
895 Operator::Lte => true,
896 Operator::Eq => count == 0,
897 Operator::Ne => count >= 1,
898 _ => false,
899 };
900 if targets.is_empty() {
901 return Ok(Where::Compare {
903 left: Expr::Value(Value::I64(0)),
904 op,
905 right: Expr::Value(Value::I64(count_i)),
906 });
907 }
908 let exists = count == 1 && matches!(op, Operator::Gte | Operator::Lt);
909 let parent = P::meta();
910 let mut alternatives = Vec::with_capacity(targets.len() + 1);
911 for target in targets {
912 let name = target.morph_name();
913 let query = target.exists_query(MorphExists {
914 parent,
915 id_column: &self.id_column,
916 owner_key: self.owner_key.as_deref(),
917 depth,
918 select: if exists {
919 ExistsSelect::One
920 } else {
921 ExistsSelect::Count
922 },
923 condition: refine(&name),
924 trashed: self.trashed,
925 })?;
926 let check = if exists {
927 Where::Exists {
928 query: Box::new(query),
929 not: op == Operator::Lt,
930 }
931 } else {
932 Where::Compare {
933 left: Expr::Subquery(Box::new(query)),
934 op: op.clone(),
935 right: Expr::Value(Value::I64(count_i)),
936 }
937 };
938 alternatives.push(WhereClause::or(Where::Group(vec![
939 WhereClause::and(Where::Compare {
940 left: Expr::Column(qualified(parent.table(), &self.type_column)),
941 op: Operator::Eq,
942 right: Expr::Value(Value::from(name.into_owned())),
943 }),
944 WhereClause::and(check),
945 ])));
946 }
947 if check_null {
948 alternatives.push(WhereClause::or(Where::Null {
949 expr: Expr::Column(qualified(parent.table(), &self.type_column)),
950 not: false,
951 }));
952 }
953 Ok(Where::Group(alternatives))
954 }
955}
956
957pub trait MorphToOps<P: Model>: Send + Sync {
959 fn has_morph(
962 &self,
963 depth: u32,
964 types: Option<&[String]>,
965 op: Operator,
966 count: u64,
967 refine: &mut dyn FnMut(&str) -> Option<Filter>,
968 ) -> Result<Where>;
969
970 #[doc(hidden)]
972 fn target_for(&self, name: &str) -> Result<Arc<dyn MorphTarget>>;
973}
974
975impl<P: Model> MorphToOps<P> for MorphTo<P> {
976 fn has_morph(
977 &self,
978 depth: u32,
979 types: Option<&[String]>,
980 op: Operator,
981 count: u64,
982 refine: &mut dyn FnMut(&str) -> Option<Filter>,
983 ) -> Result<Where> {
984 self.has_morph_where(depth, types, op, count, refine)
985 }
986
987 fn target_for(&self, name: &str) -> Result<Arc<dyn MorphTarget>> {
988 self.resolve(name)
989 }
990}
991
992impl<P: Model> private::Erase<P> for MorphTo<P> {
993 fn erase(self) -> Arc<dyn ErasedRelation<P>> {
994 let mut unbound = self;
995 unbound.parent = None;
996 Arc::new(unbound)
997 }
998
999 fn rename(&mut self, name: Cow<'static, str>) {
1000 self.name = name;
1001 }
1002}
1003
1004impl<P: Model> Relation<P> for MorphTo<P> {
1005 type Value = Option<AnyRecord>;
1006
1007 fn name(&self) -> &str {
1008 &self.name
1009 }
1010
1011 fn kind(&self) -> RelationKind {
1012 RelationKind::MorphTo
1013 }
1014
1015 fn meta(&self) -> RelationMeta {
1016 let mut meta = RelationMeta::new::<P>(&self.name, RelationKind::MorphTo);
1017 meta.foreign_key = Some(self.id_column.to_string());
1018 meta.owner_key = self.owner_key.as_ref().map(ToString::to_string);
1019 meta.morph_type = Some(self.type_column.to_string());
1020 meta
1021 }
1022}
1023
1024impl<P: Model> ErasedRelation<P> for MorphTo<P> {
1025 fn name(&self) -> &str {
1026 &self.name
1027 }
1028
1029 fn meta(&self) -> RelationMeta {
1030 Relation::meta(self)
1031 }
1032
1033 fn related_type(&self) -> Option<TypeId> {
1034 None
1035 }
1036
1037 fn eager_load<'a, 'b>(
1038 &'a self,
1039 target: &'a Target<'b>,
1040 parents: &'a mut [Record<P>],
1041 node: &'a EagerNode,
1042 ) -> BoxFuture<'a, Result<()>> {
1043 Box::pin(async move { self.load_into(target, parents, node).await })
1044 }
1045
1046 fn exists_query(&self, _request: ExistsRequest) -> Result<QueryIr> {
1047 Err(OrmError::invalid(format!(
1048 "`{}` of {} is a morph_to relation whose model varies: count or aggregate each type through its own relations",
1049 self.name,
1050 P::meta().name()
1051 )))
1052 }
1053
1054 fn touch<'a, 'b>(
1055 &'a self,
1056 target: &'a Target<'b>,
1057 parent: &'a Record<P>,
1058 ) -> BoxFuture<'a, Result<()>> {
1059 Box::pin(async move {
1060 let stored_type = column_value(&parent.model, &self.type_column, &self.name)?;
1061 let id = column_value(&parent.model, &self.id_column, &self.name)?;
1062 let (Value::String(name), false) = (&stored_type, is_null(&id)) else {
1063 return Ok(());
1064 };
1065 let morph_target = self.resolve(name)?;
1066 let keys = distinct_keys([id]);
1067 let records = morph_target
1068 .load(
1069 target,
1070 MorphLoad {
1071 owner_key: self.owner_key.as_deref(),
1072 keys: &keys,
1073 loads: None,
1074 children: &EagerTree::default(),
1075 conditions: &[],
1076 access: &[],
1077 trashed: Trashed::With,
1078 },
1079 )
1080 .await?;
1081 for (_, mut record) in records {
1082 crate::relations::touch::touch_any(target, &mut record).await?;
1083 }
1084 Ok(())
1085 })
1086 }
1087
1088 fn load_nested_missing<'a, 'b>(
1089 &'a self,
1090 target: &'a Target<'b>,
1091 parents: &'a mut [Record<P>],
1092 rest: &'a EagerTree,
1093 ) -> BoxFuture<'a, Result<()>> {
1094 Box::pin(async move {
1095 let mut taken: Vec<Option<AnyRecord>> = parents
1098 .iter_mut()
1099 .map(|parent| {
1100 parent
1101 .relations
1102 .take::<Option<AnyRecord>>(&self.name)
1103 .flatten()
1104 })
1105 .collect();
1106 let mut model_types: Vec<TypeId> = Vec::new();
1107 let mut targets: Vec<Arc<dyn MorphTarget>> = Vec::new();
1108 for record in taken.iter().flatten() {
1109 let name = record.morph_name();
1110 let morph_target = self.resolve(&name)?;
1111 if !model_types.contains(&morph_target.type_id()) {
1112 model_types.push(morph_target.type_id());
1113 targets.push(morph_target);
1114 }
1115 }
1116 for morph_target in targets {
1117 let indexes: Vec<usize> = taken
1118 .iter()
1119 .enumerate()
1120 .filter(|(_, record)| {
1121 record
1122 .as_ref()
1123 .is_some_and(|record| record.morph_name() == morph_target.morph_name())
1124 })
1125 .map(|(index, _)| index)
1126 .collect();
1127 let records: Vec<AnyRecord> = indexes
1128 .iter()
1129 .filter_map(|index| taken[*index].take())
1130 .collect();
1131 let loaded = crate::relations::lazy::load_missing_any(
1132 target,
1133 morph_target.as_ref(),
1134 records,
1135 rest,
1136 )
1137 .await?;
1138 for (index, record) in indexes.into_iter().zip(loaded) {
1139 taken[index] = Some(record);
1140 }
1141 }
1142 for (parent, record) in parents.iter_mut().zip(taken) {
1143 parent.relations.set_relation(self.name.clone(), record);
1144 }
1145 Ok(())
1146 })
1147 }
1148
1149 fn morph_to(&self) -> Option<&dyn MorphToOps<P>> {
1150 Some(self)
1151 }
1152}
1153
1154#[derive(Clone, Debug, Default)]
1167pub struct MorphTypes {
1168 names: Option<Vec<String>>,
1169}
1170
1171impl MorphTypes {
1172 pub fn all() -> Self {
1174 MorphTypes { names: None }
1175 }
1176
1177 pub fn named(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
1179 MorphTypes {
1180 names: Some(names.into_iter().map(Into::into).collect()),
1181 }
1182 }
1183
1184 pub fn of<M: Model>() -> Self {
1186 MorphTypes::named([M::morph_name().into_owned()])
1187 }
1188
1189 pub fn and<M: Model>(mut self) -> Self {
1191 self.names
1192 .get_or_insert_with(Vec::new)
1193 .push(M::morph_name().into_owned());
1194 self
1195 }
1196}
1197
1198impl From<&[&str]> for MorphTypes {
1199 fn from(names: &[&str]) -> Self {
1200 MorphTypes::named(names.iter().copied())
1201 }
1202}
1203
1204impl<const N: usize> From<[&str; N]> for MorphTypes {
1205 fn from(names: [&str; N]) -> Self {
1206 MorphTypes::named(names)
1207 }
1208}
1209
1210impl From<Vec<String>> for MorphTypes {
1211 fn from(names: Vec<String>) -> Self {
1212 MorphTypes { names: Some(names) }
1213 }
1214}
1215
1216#[derive(Clone, Debug)]
1233pub struct MorphRef {
1234 kind: MorphRefKind,
1235}
1236
1237#[derive(Clone, Debug)]
1238enum MorphRefKind {
1239 Records(Vec<AnyRecord>),
1240 Type(String),
1241 Null,
1242}
1243
1244impl MorphRef {
1245 pub fn type_of<M: Model>() -> Self {
1247 MorphRef {
1248 kind: MorphRefKind::Type(M::morph_name().into_owned()),
1249 }
1250 }
1251
1252 pub fn named(name: impl Into<String>) -> Self {
1254 MorphRef {
1255 kind: MorphRefKind::Type(name.into()),
1256 }
1257 }
1258
1259 pub fn null() -> Self {
1261 MorphRef {
1262 kind: MorphRefKind::Null,
1263 }
1264 }
1265}
1266
1267impl<M: Model> From<&Record<M>> for MorphRef {
1268 fn from(record: &Record<M>) -> Self {
1269 MorphRef {
1270 kind: MorphRefKind::Records(vec![AnyRecord::new(record.without_relations())]),
1271 }
1272 }
1273}
1274
1275impl<M: Model> From<&Collection<M>> for MorphRef {
1276 fn from(records: &Collection<M>) -> Self {
1277 MorphRef {
1278 kind: MorphRefKind::Records(
1279 records
1280 .iter()
1281 .map(|record| AnyRecord::new(record.without_relations()))
1282 .collect(),
1283 ),
1284 }
1285 }
1286}
1287
1288impl From<&AnyRecord> for MorphRef {
1289 fn from(record: &AnyRecord) -> Self {
1290 MorphRef {
1291 kind: MorphRefKind::Records(vec![record.clone()]),
1292 }
1293 }
1294}
1295
1296impl<M: Model> Builder<M> {
1297 #[allow(clippy::too_many_arguments)]
1299 fn push_has_morph(
1300 mut self,
1301 boolean: Boolean,
1302 path: &str,
1303 types: MorphTypes,
1304 op: Operator,
1305 count: u64,
1306 refine: &mut dyn FnMut(&str) -> Option<Filter>,
1307 ) -> Self {
1308 let relation = match find::<M>(path) {
1309 Ok(relation) => relation,
1310 Err(error) => return self.with_error(error.to_string()),
1311 };
1312 let Some(morph) = relation.inner.morph_to() else {
1313 return self.with_error(format!(
1314 "`{path}` of {} is a {}, not a morph_to relation",
1315 M::meta().name(),
1316 relation.kind()
1317 ));
1318 };
1319 match morph.has_morph(self.eager.depth, types.names.as_deref(), op, count, refine) {
1320 Ok(filter) => {
1321 self.push_where(boolean, false, filter);
1322 self
1323 }
1324 Err(error) => self.with_error(error.to_string()),
1325 }
1326 }
1327
1328 pub fn has_morph(self, path: impl RelationPath<M>, types: impl Into<MorphTypes>) -> Self {
1332 let text = path.relation_path().into_owned();
1333 self.push_has_morph(
1334 Boolean::And,
1335 &text,
1336 types.into(),
1337 Operator::Gte,
1338 1,
1339 &mut |_| None,
1340 )
1341 }
1342
1343 pub fn or_has_morph(self, path: impl RelationPath<M>, types: impl Into<MorphTypes>) -> Self {
1346 let text = path.relation_path().into_owned();
1347 self.push_has_morph(
1348 Boolean::Or,
1349 &text,
1350 types.into(),
1351 Operator::Gte,
1352 1,
1353 &mut |_| None,
1354 )
1355 }
1356
1357 pub fn doesnt_have_morph(
1362 self,
1363 path: impl RelationPath<M>,
1364 types: impl Into<MorphTypes>,
1365 ) -> Self {
1366 let text = path.relation_path().into_owned();
1367 self.push_has_morph(
1368 Boolean::And,
1369 &text,
1370 types.into(),
1371 Operator::Lt,
1372 1,
1373 &mut |_| None,
1374 )
1375 }
1376
1377 pub fn or_doesnt_have_morph(
1380 self,
1381 path: impl RelationPath<M>,
1382 types: impl Into<MorphTypes>,
1383 ) -> Self {
1384 let text = path.relation_path().into_owned();
1385 self.push_has_morph(
1386 Boolean::Or,
1387 &text,
1388 types.into(),
1389 Operator::Lt,
1390 1,
1391 &mut |_| None,
1392 )
1393 }
1394
1395 pub fn where_has_morph(
1408 self,
1409 path: impl RelationPath<M>,
1410 types: impl Into<MorphTypes>,
1411 mut constraint: impl FnMut(WhereGroup, &str) -> WhereGroup,
1412 ) -> Self {
1413 let text = path.relation_path().into_owned();
1414 self.push_has_morph(
1415 Boolean::And,
1416 &text,
1417 types.into(),
1418 Operator::Gte,
1419 1,
1420 &mut |ty| group_filter(constraint(WhereGroup::new(), ty)),
1421 )
1422 }
1423
1424 pub fn or_where_has_morph(
1427 self,
1428 path: impl RelationPath<M>,
1429 types: impl Into<MorphTypes>,
1430 mut constraint: impl FnMut(WhereGroup, &str) -> WhereGroup,
1431 ) -> Self {
1432 let text = path.relation_path().into_owned();
1433 self.push_has_morph(
1434 Boolean::Or,
1435 &text,
1436 types.into(),
1437 Operator::Gte,
1438 1,
1439 &mut |ty| group_filter(constraint(WhereGroup::new(), ty)),
1440 )
1441 }
1442
1443 pub fn where_doesnt_have_morph(
1446 self,
1447 path: impl RelationPath<M>,
1448 types: impl Into<MorphTypes>,
1449 mut constraint: impl FnMut(WhereGroup, &str) -> WhereGroup,
1450 ) -> Self {
1451 let text = path.relation_path().into_owned();
1452 self.push_has_morph(
1453 Boolean::And,
1454 &text,
1455 types.into(),
1456 Operator::Lt,
1457 1,
1458 &mut |ty| group_filter(constraint(WhereGroup::new(), ty)),
1459 )
1460 }
1461
1462 pub fn or_where_doesnt_have_morph(
1465 self,
1466 path: impl RelationPath<M>,
1467 types: impl Into<MorphTypes>,
1468 mut constraint: impl FnMut(WhereGroup, &str) -> WhereGroup,
1469 ) -> Self {
1470 let text = path.relation_path().into_owned();
1471 self.push_has_morph(
1472 Boolean::Or,
1473 &text,
1474 types.into(),
1475 Operator::Lt,
1476 1,
1477 &mut |ty| group_filter(constraint(WhereGroup::new(), ty)),
1478 )
1479 }
1480
1481 pub fn where_morph_relation(
1484 self,
1485 path: impl RelationPath<M>,
1486 types: impl Into<MorphTypes>,
1487 filter: impl Into<Filter>,
1488 ) -> Self {
1489 let text = path.relation_path().into_owned();
1490 let filter = filter.into();
1491 self.push_has_morph(
1492 Boolean::And,
1493 &text,
1494 types.into(),
1495 Operator::Gte,
1496 1,
1497 &mut |_| Some(filter.clone()),
1498 )
1499 }
1500
1501 pub fn or_where_morph_relation(
1503 self,
1504 path: impl RelationPath<M>,
1505 types: impl Into<MorphTypes>,
1506 filter: impl Into<Filter>,
1507 ) -> Self {
1508 let text = path.relation_path().into_owned();
1509 let filter = filter.into();
1510 self.push_has_morph(
1511 Boolean::Or,
1512 &text,
1513 types.into(),
1514 Operator::Gte,
1515 1,
1516 &mut |_| Some(filter.clone()),
1517 )
1518 }
1519
1520 pub fn where_morph_doesnt_have_relation(
1523 self,
1524 path: impl RelationPath<M>,
1525 types: impl Into<MorphTypes>,
1526 filter: impl Into<Filter>,
1527 ) -> Self {
1528 let text = path.relation_path().into_owned();
1529 let filter = filter.into();
1530 self.push_has_morph(
1531 Boolean::And,
1532 &text,
1533 types.into(),
1534 Operator::Lt,
1535 1,
1536 &mut |_| Some(filter.clone()),
1537 )
1538 }
1539
1540 pub fn or_where_morph_doesnt_have_relation(
1543 self,
1544 path: impl RelationPath<M>,
1545 types: impl Into<MorphTypes>,
1546 filter: impl Into<Filter>,
1547 ) -> Self {
1548 let text = path.relation_path().into_owned();
1549 let filter = filter.into();
1550 self.push_has_morph(
1551 Boolean::Or,
1552 &text,
1553 types.into(),
1554 Operator::Lt,
1555 1,
1556 &mut |_| Some(filter.clone()),
1557 )
1558 }
1559
1560 pub fn where_morphed_to(self, path: impl RelationPath<M>, target: impl Into<MorphRef>) -> Self {
1573 let text = path.relation_path().into_owned();
1574 self.push_morphed_to(Boolean::And, &text, target.into(), false)
1575 }
1576
1577 pub fn where_not_morphed_to(
1579 self,
1580 path: impl RelationPath<M>,
1581 target: impl Into<MorphRef>,
1582 ) -> Self {
1583 let text = path.relation_path().into_owned();
1584 self.push_morphed_to(Boolean::And, &text, target.into(), true)
1585 }
1586
1587 pub fn or_where_morphed_to(
1589 self,
1590 path: impl RelationPath<M>,
1591 target: impl Into<MorphRef>,
1592 ) -> Self {
1593 let text = path.relation_path().into_owned();
1594 self.push_morphed_to(Boolean::Or, &text, target.into(), false)
1595 }
1596
1597 pub fn or_where_not_morphed_to(
1599 self,
1600 path: impl RelationPath<M>,
1601 target: impl Into<MorphRef>,
1602 ) -> Self {
1603 let text = path.relation_path().into_owned();
1604 self.push_morphed_to(Boolean::Or, &text, target.into(), true)
1605 }
1606
1607 fn push_morphed_to(
1608 mut self,
1609 boolean: Boolean,
1610 path: &str,
1611 target: MorphRef,
1612 not: bool,
1613 ) -> Self {
1614 match morphed_to_filter::<M>(path, target, not) {
1615 Ok(filter) => {
1616 self.push_where(boolean, false, filter);
1617 self
1618 }
1619 Err(error) => self.with_error(error.to_string()),
1620 }
1621 }
1622
1623 pub fn with_morph(mut self, path: impl RelationPath<M>, with: MorphWith) -> Self {
1625 let text = path.relation_path().into_owned();
1626 match ParsedPath::parse(&text) {
1627 Ok(parsed) => {
1628 let node = self.eager.tree.entry(&parsed.segments);
1629 match &mut node.morph {
1630 Some(existing) => existing.merge(&with),
1631 None => node.morph = Some(with),
1632 }
1633 self
1634 }
1635 Err(error) => self.with_error(error.to_string()),
1636 }
1637 }
1638}
1639
1640fn group_filter(group: WhereGroup) -> Option<Filter> {
1642 let clauses = group.into_clauses();
1643 (!clauses.is_empty()).then(|| Filter::from(Where::Group(clauses)))
1644}
1645
1646fn morphed_to_filter<M: Model>(path: &str, target: MorphRef, not: bool) -> Result<Where> {
1649 let relation = find::<M>(path)?;
1650 let meta = relation.meta();
1651 if meta.kind != RelationKind::MorphTo {
1652 return Err(OrmError::invalid(format!(
1653 "`{path}` of {} is a {}, not a morph_to relation",
1654 M::meta().name(),
1655 meta.kind
1656 )));
1657 }
1658 let table = M::meta().table();
1659 let (Some(type_column), Some(id_column)) = (meta.morph_type, meta.foreign_key) else {
1660 return Err(OrmError::invalid(format!(
1661 "the morph_to relation `{path}` of {} has no columns",
1662 M::meta().name()
1663 )));
1664 };
1665 let type_op = if not {
1666 Operator::NullSafeEq
1667 } else {
1668 Operator::Eq
1669 };
1670 let condition = match target.kind {
1671 MorphRefKind::Null => Where::Null {
1672 expr: Expr::Column(qualified(table, &type_column)),
1673 not,
1674 },
1675 MorphRefKind::Type(name) => {
1676 let check = Where::Compare {
1677 left: Expr::Column(qualified(table, &type_column)),
1678 op: type_op,
1679 right: Expr::Value(Value::from(name)),
1680 };
1681 if not {
1682 Where::Group(vec![WhereClause {
1683 boolean: Boolean::And,
1684 negated: true,
1685 filter: check,
1686 }])
1687 } else {
1688 check
1689 }
1690 }
1691 MorphRefKind::Records(records) => {
1692 if records.is_empty() {
1693 return Err(OrmError::invalid(format!(
1694 "where_morphed_to(`{path}`) was given no records"
1695 )));
1696 }
1697 let mut by_type: Vec<(String, Vec<Value>)> = Vec::new();
1699 for record in &records {
1700 let name = record.morph_name().into_owned();
1701 let key = match &meta.owner_key {
1702 Some(column) => record.value(column)?.ok_or_else(|| {
1703 OrmError::invalid(format!(
1704 "{} has no column `{column}`, which `{path}` points at",
1705 record.model_name()
1706 ))
1707 })?,
1708 None => record.key(),
1709 };
1710 match by_type.iter_mut().find(|(existing, _)| *existing == name) {
1711 Some((_, keys)) => keys.push(key),
1712 None => by_type.push((name, vec![key])),
1713 }
1714 }
1715 let alternatives = by_type
1716 .into_iter()
1717 .map(|(name, keys)| {
1718 let keys = distinct_keys(keys);
1719 WhereClause::or(Where::Group(vec![
1720 WhereClause::and(Where::Compare {
1721 left: Expr::Column(qualified(table, &type_column)),
1722 op: type_op.clone(),
1723 right: Expr::Value(Value::from(name)),
1724 }),
1725 WhereClause::and(in_keys(qualified(table, &id_column), &keys)),
1726 ]))
1727 })
1728 .collect();
1729 let any = Where::Group(alternatives);
1730 if not {
1731 Where::Group(vec![WhereClause {
1732 boolean: Boolean::And,
1733 negated: true,
1734 filter: any,
1735 }])
1736 } else {
1737 any
1738 }
1739 }
1740 };
1741 Ok(condition)
1742}
1743
1744pub(crate) fn stored_type_of<M: Model>() -> Result<Value> {
1747 Ok(Value::from(type_name_of::<M>()?.into_owned()))
1748}