Skip to main content

navree_orm/relations/
morph.rs

1//! Polymorphic relations: `morph_to` ([`MorphTo`]: a comment's
2//! `commentable` is a deal or a contact), the per-type loads of its eager
3//! loads ([`MorphWith`]), and the existence checks per type (`has_morph`,
4//! `where_has_morph`, `where_morphed_to`, ...).
5
6use 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/// Which soft-deleted records a `morph_to` loads.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub(crate) enum Trashed {
40    /// Not the soft-deleted ones (the default).
41    #[default]
42    Without,
43    /// Soft-deleted ones too.
44    With,
45    /// Only soft-deleted ones (of models that soft-delete).
46    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/// What a `morph_to` eager load does for one of its models.
66#[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    /// `query` with these loads: constraints, eager loads and counts.
96    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/// What a `morph_to` eager load loads into each of its models: nested
123/// relations ([`on`](MorphWith::on)), relation counts
124/// ([`count_on`](MorphWith::count_on)) and constraints
125/// ([`constrain`](MorphWith::constrain)), per model.
126///
127/// ```no_run
128/// # use navree_orm::__doc_models::*;
129/// use navree_orm::relations::MorphWith;
130///
131/// # async fn demo(db: Db) -> Result<()> {
132/// let notes = Note::query()
133///     .with_morph(
134///         "notable",
135///         MorphWith::new()
136///             .on::<Deal>(["company"])
137///             .count_on::<Deal>(["activities"])
138///             .constrain::<Company>(|q| q.where_(Company::ACTIVE.eq(true))),
139///     )
140///     .get(&db)
141///     .await?;
142/// # Ok(()) }
143/// ```
144#[derive(Clone, Debug, Default)]
145pub struct MorphWith {
146    types: Vec<MorphTypeLoads>,
147}
148
149impl MorphWith {
150    /// Nothing per type yet.
151    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    /// Eager loads `paths` into the loaded records of model `M`.
171    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    /// Counts the related records of `paths` on the loaded records of
189    /// model `M` (`{relation}_count` extras).
190    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    /// Constrains the query of model `M`'s records.
202    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    /// Adds `other`'s loads.
213    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    /// The loads of the model with type id `type_id`.
227    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
232/// What a `morph_to` load asks of one of its models.
233pub struct MorphLoad<'a> {
234    /// The column the stored ids point at; the model's key when `None`.
235    pub(crate) owner_key: Option<&'a str>,
236    /// The ids, distinct.
237    pub(crate) keys: &'a [(RelationKey, Value)],
238    /// The per-type loads.
239    pub(crate) loads: Option<&'a MorphTypeLoads>,
240    /// Loads that apply to every type (nested paths of the eager load).
241    pub(crate) children: &'a EagerTree,
242    /// Conditions that apply to every type.
243    pub(crate) conditions: &'a [Filter],
244    /// Access filters, asked for each type's condition.
245    pub(crate) access: &'a [AccessConstraint],
246    /// Soft-deleted records.
247    pub(crate) trashed: Trashed,
248}
249
250/// What a `morph_to` existence check asks of one of its models.
251pub struct MorphExists<'a> {
252    /// The model the `morph_to` is declared on.
253    pub(crate) parent: &'static ModelMeta,
254    /// The id column on the parent.
255    pub(crate) id_column: &'a str,
256    /// The column the ids point at; the model's key when `None`.
257    pub(crate) owner_key: Option<&'a str>,
258    /// How deep the outer query is nested.
259    pub(crate) depth: u32,
260    /// What the subquery selects.
261    pub(crate) select: ExistsSelect,
262    /// A condition on the model's records.
263    pub(crate) condition: Option<Filter>,
264    /// Soft-deleted records.
265    pub(crate) trashed: Trashed,
266}
267
268/// One model a `morph_to` can load, with its type erased.
269pub trait MorphTarget: Send + Sync + 'static {
270    /// The model's type id.
271    fn type_id(&self) -> TypeId;
272
273    /// The name the model's records are stored under in a type column.
274    fn morph_name(&self) -> Cow<'static, str>;
275
276    /// A stored id as the model's key stores it (an id column of text
277    /// holding `"5"` for an integer key), so it binds and matches as one.
278    fn normalize_key(&self, value: Value, owner_key: Option<&str>) -> Value;
279
280    /// The records whose owner key is one of `request.keys`, by key.
281    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    /// Loads `paths` (eager loads, or aggregates when `aggregate` is set)
288    /// into `records` (all of this model).
289    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    /// Loads what `rest` misses into `records` (all of this model).
298    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    /// The existence subquery of this model's records.
306    fn exists_query(&self, request: MorphExists<'_>) -> Result<QueryIr>;
307}
308
309/// `records` as records of `M` (an error names a record of another model).
310fn 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
325/// The [`MorphTarget`] of model `M`.
326pub(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                    // The relations listed for the model, with `on` (first
422                    // steps) or `count_on`.
423                    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
488/// The models a `morph_to` lists itself: tuples of models,
489/// `.targets::<(Deal, Contact)>()`.
490pub 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
514/// A polymorphic belongs-to: the parent holds the type and the key of one
515/// record of any model (`commentable_type` and `commentable_id`). Loaded,
516/// it holds an `Option<AnyRecord>`.
517///
518/// The models it can load come from its own list
519/// ([`target`](MorphTo::target), [`targets`](MorphTo::targets)), else from
520/// the process-wide [`MorphMap`].
521///
522/// ```no_run
523/// # use navree_orm::__doc_models::*;
524/// # async fn demo(db: Db, note: Record<Note>) -> Result<()> {
525/// // #[relations] impl Note {
526/// //     fn notable(&self) -> MorphTo<Note> { self.morph_to("notable").targets::<(Deal, Company)>() }
527/// // }
528/// if let Some(notable) = note.notable().get(&db).await? {
529///     if let Some(deal) = notable.downcast_ref::<Deal>() {
530///         println!("a note on deal {}", deal.title);
531///     }
532/// }
533/// # Ok(()) }
534/// ```
535pub 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    /// The `morph_to` named `name` of `parent`: columns `{name}_type` and
574    /// `{name}_id`.
575    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    /// Names the relation (what it is loaded under).
589    pub fn named(mut self, name: impl Into<Cow<'static, str>>) -> Self {
590        self.name = name.into();
591        self
592    }
593
594    /// The type column, when it is not `{name}_type`.
595    pub fn type_column(mut self, column: impl Into<Cow<'static, str>>) -> Self {
596        self.type_column = column.into();
597        self
598    }
599
600    /// The id column, when it is not `{name}_id`.
601    pub fn id_column(mut self, column: impl Into<Cow<'static, str>>) -> Self {
602        self.id_column = column.into();
603        self
604    }
605
606    /// The column of the related models the ids point at, when it is not
607    /// their key.
608    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    /// Lists model `M` among the models the relation loads.
614    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    /// Lists the models of tuple `T` (`(Deal, Contact)`).
622    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    /// Loads soft-deleted records too, of every model.
632    pub fn with_trashed(mut self) -> Self {
633        self.trashed = Trashed::With;
634        self
635    }
636
637    /// Leaves soft-deleted records out (the default).
638    pub fn without_trashed(mut self) -> Self {
639        self.trashed = Trashed::Without;
640        self
641    }
642
643    /// Loads only soft-deleted records (of models that soft-delete).
644    pub fn only_trashed(mut self) -> Self {
645        self.trashed = Trashed::Only;
646        self
647    }
648
649    /// Per-model loads of every load of this relation.
650    pub fn morph_with(mut self, with: MorphWith) -> Self {
651        self.with.merge(&with);
652        self
653    }
654
655    /// Constrains the query of model `M`'s records.
656    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    /// The relation's name.
665    pub fn relation_name(&self) -> &str {
666        &self.name
667    }
668
669    /// The type column.
670    pub fn morph_type(&self) -> &str {
671        &self.type_column
672    }
673
674    /// The id column.
675    pub fn foreign_key_name(&self) -> &str {
676        &self.id_column
677    }
678
679    /// The id column qualified by the parent's table.
680    pub fn qualified_foreign_key_name(&self) -> String {
681        format!("{}.{}", P::meta().table(), self.id_column)
682    }
683
684    /// The column the ids point at, when it is not the related models'
685    /// key.
686    pub fn owner_key_name(&self) -> Option<&str> {
687        self.owner_key.as_deref()
688    }
689
690    /// The model registered under `name`: the relation's own list first,
691    /// then the morph map.
692    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    /// Every model the relation can load: its own list, else the morph
709    /// map's.
710    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    /// The related record of the parent, if any.
722    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    /// Whether `record` is the parent's related record (same type name and
749    /// key; no query).
750    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    /// Whether `record` is not the parent's related record.
778    pub fn is_not<M: Model>(&self, record: &Record<M>) -> bool {
779        !self.is(record)
780    }
781
782    /// Loads the relation into `parents`, one query per stored type.
783    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        // The stored type and id of each parent, grouped by type in the
822        // order the types first appear.
823        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    /// The condition of a polymorphic existence check: per type, the type
874    /// column holds the type's name and its records exist (or not); for
875    /// "none" over every type, a NULL type too.
876    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            // No model to check: compare a constant, as a count of zero.
902            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
957/// The polymorphic operations of a `morph_to`, for relation names.
958pub trait MorphToOps<P: Model>: Send + Sync {
959    /// The condition of a polymorphic existence check over `types` (every
960    /// known type when `None`), with a condition per type from `refine`.
961    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    /// The model registered under morph name `name`.
971    #[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            // Gather the loaded records by model, load what each misses,
1096            // and put them back in place.
1097            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/// The models a polymorphic existence check covers: listed by name,
1155/// listed by model, or every known model.
1156///
1157/// ```
1158/// # use navree_orm::__doc_models::*;
1159/// use navree_orm::relations::MorphTypes;
1160///
1161/// let deals_or_companies = MorphTypes::of::<Deal>().and::<Company>();
1162/// let by_name: MorphTypes = ["deal", "company"].into();
1163/// let notes = Note::query().has_morph("notable", deals_or_companies);
1164/// # let _ = (by_name, notes, MorphTypes::all());
1165/// ```
1166#[derive(Clone, Debug, Default)]
1167pub struct MorphTypes {
1168    names: Option<Vec<String>>,
1169}
1170
1171impl MorphTypes {
1172    /// Every model the relation knows (its list, else the morph map).
1173    pub fn all() -> Self {
1174        MorphTypes { names: None }
1175    }
1176
1177    /// The models registered under `names`.
1178    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    /// Model `M` alone.
1185    pub fn of<M: Model>() -> Self {
1186        MorphTypes::named([M::morph_name().into_owned()])
1187    }
1188
1189    /// These models and model `M`.
1190    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/// What a `morph_to` points at, for [`where_morphed_to`](Builder::where_morphed_to):
1217/// a record (`&deal`), several records of one model (`&deals`), any record
1218/// of a model ([`MorphRef::type_of`]), or nothing ([`MorphRef::null`]).
1219///
1220/// ```
1221/// # use navree_orm::__doc_models::*;
1222/// use navree_orm::relations::MorphRef;
1223///
1224/// let sql = Note::query()
1225///     .where_morphed_to("notable", MorphRef::type_of::<Deal>())
1226///     .to_sql(Dialect::Sqlite)
1227///     .unwrap();
1228/// assert!(sql.sql.contains(r#"WHERE "notes"."notable_type" = ?"#));
1229/// let loose = Note::query().where_morphed_to("notable", MorphRef::null());
1230/// # let _ = loose;
1231/// ```
1232#[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    /// Any record of model `M`.
1246    pub fn type_of<M: Model>() -> Self {
1247        MorphRef {
1248            kind: MorphRefKind::Type(M::morph_name().into_owned()),
1249        }
1250    }
1251
1252    /// Any record of the model registered under `name`.
1253    pub fn named(name: impl Into<String>) -> Self {
1254        MorphRef {
1255            kind: MorphRefKind::Type(name.into()),
1256        }
1257    }
1258
1259    /// No record: the type column is NULL.
1260    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    /// Adds a polymorphic existence check of `morph_to` relation `path`.
1298    #[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    /// Only records whose `morph_to` relation `path` points at an existing
1329    /// record of one of `types` (`["deal", "company"]`,
1330    /// `MorphTypes::of::<Deal>()`, or `MorphTypes::all()`).
1331    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    /// `OR` records whose `morph_to` points at an existing record of one
1344    /// of `types`.
1345    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    /// Only records whose `morph_to` relation `path` is of one of `types`
1358    /// but points at no existing record (a note about a deleted deal).
1359    /// Records of other types are left out; over every type
1360    /// (`MorphTypes::all()`), records with a NULL type are included.
1361    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    /// `OR` records whose `morph_to` is of one of `types` but points at no
1378    /// existing record.
1379    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    /// Only records whose `morph_to` points at a record of one of `types`
1396    /// matching `constraint`, which gets the conditions to fill and the
1397    /// type's name.
1398    ///
1399    /// ```
1400    /// # use navree_orm::__doc_models::*;
1401    /// let notes = Note::query().where_has_morph("notable", ["deal", "company"], |q, ty| match ty {
1402    ///     "deal" => q.where_(Deal::STAGE.eq(Stage::Won)),
1403    ///     _ => q.where_(Company::ACTIVE.eq(true)),
1404    /// });
1405    /// # let _ = notes;
1406    /// ```
1407    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    /// `OR` records whose `morph_to` points at a record matching
1425    /// `constraint`.
1426    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    /// Only records whose `morph_to` is of one of `types` but points at no
1444    /// record matching `constraint` (over every type, NULL types too).
1445    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    /// `OR` records whose `morph_to` is of one of `types` but points at no
1463    /// record matching `constraint`.
1464    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    /// Only records whose `morph_to` points at a record of one of `types`
1482    /// matching `filter`.
1483    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    /// `OR` records whose `morph_to` points at a record matching `filter`.
1502    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    /// Only records whose `morph_to` is of one of `types` but points at no
1521    /// record matching `filter`.
1522    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    /// `OR` records whose `morph_to` is of one of `types` but points at no
1541    /// record matching `filter`.
1542    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    /// Only records whose `morph_to` relation `path` points at `target`: a
1561    /// record, the records of a collection, any record of a model
1562    /// ([`MorphRef::type_of`]), or none ([`MorphRef::null`]). No query of
1563    /// the related table: the type and id columns are compared.
1564    ///
1565    /// ```
1566    /// # use navree_orm::__doc_models::*;
1567    /// use navree_orm::relations::MorphRef;
1568    ///
1569    /// let on_deals = Note::query().where_morphed_to("notable", MorphRef::type_of::<Deal>());
1570    /// # let _ = on_deals;
1571    /// ```
1572    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    /// Only records whose `morph_to` does not point at `target`.
1578    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    /// `OR` records whose `morph_to` points at `target`.
1588    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    /// `OR` records whose `morph_to` does not point at `target`.
1598    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    /// Eager loads `morph_to` relation `path` with per-model loads.
1624    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
1640/// The conditions of a group, as one filter (`None` when it has none).
1641fn group_filter(group: WhereGroup) -> Option<Filter> {
1642    let clauses = group.into_clauses();
1643    (!clauses.is_empty()).then(|| Filter::from(Where::Group(clauses)))
1644}
1645
1646/// The condition of `where_morphed_to`: per model, the type column holds
1647/// its name and the id column one of its records' keys.
1648fn 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            // By model, in the order the models first appear.
1698            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
1744/// The value a `morph_to` stores for `record`'s model: its morph name
1745/// (checked against a required morph map).
1746pub(crate) fn stored_type_of<M: Model>() -> Result<Value> {
1747    Ok(Value::from(type_name_of::<M>()?.into_owned()))
1748}