Skip to main content

navree_orm/relations/
lazy.rs

1//! Loading relations after the query: onto a record or a collection
2//! (`load`, `load_missing`, `load_count`, `load_morph`, ...), one record at
3//! a time (`relation_or_load`), the lazy-loading rules ([`LazyLoading`]:
4//! prevent it, or load for the whole result at once), and what records do
5//! with loaded relations (`push`, `associate`, `dissociate`, pivots).
6
7use std::borrow::Cow;
8use std::fmt;
9use std::future::Future;
10use std::sync::{Arc, OnceLock, RwLock};
11
12use navree_kernel::BoxFuture;
13
14use crate::collection::Collection;
15use crate::column::IntoExpr;
16use crate::error::{OrmError, Result};
17use crate::exec::{Access, ExecContext, Executor, Target};
18use crate::ir::AggregateFunction;
19use crate::model::Model;
20use crate::record::Record;
21use crate::relations::Relation;
22use crate::relations::aggregates::{AggregateSpec, load_aggregate_on};
23use crate::relations::any::AnyRecord;
24use crate::relations::belongs_to::BelongsTo;
25use crate::relations::core::column_value;
26use crate::relations::eager::{Constraint, EagerNode, EagerTree, load_tree};
27use crate::relations::morph::{MorphTarget, MorphTo, MorphWith};
28use crate::relations::path::{ConstrainPath, ParsedPath, RelationPath};
29use crate::relations::pivot::Pivot;
30use crate::relations::registry::{self, DynRelation};
31use crate::relations::store::{RelationValue, Relations};
32use crate::strict::{Strictness, Violation};
33use crate::value::{Field, Kind, Value};
34
35/// What a record knows about lazy loading: whether it came from a result
36/// of several records while lazy loading is prevented, and the group of
37/// records it loads relations with (automatic eager loading).
38pub(crate) struct LoadState<M: Model> {
39    pub(crate) prevent: bool,
40    pub(crate) autoload: Option<(Arc<AutoloadGroup<M>>, usize)>,
41}
42
43impl<M: Model> Default for LoadState<M> {
44    fn default() -> Self {
45        LoadState {
46            prevent: false,
47            autoload: None,
48        }
49    }
50}
51
52impl<M: Model> Clone for LoadState<M> {
53    fn clone(&self) -> Self {
54        LoadState {
55            prevent: self.prevent,
56            autoload: self.autoload.clone(),
57        }
58    }
59}
60
61/// Records that load each relation together: the first lazy load of a
62/// relation on one of them loads it for all (one query), and the others
63/// find it here.
64pub(crate) struct AutoloadGroup<M: Model> {
65    records: tokio::sync::Mutex<Vec<Record<M>>>,
66}
67
68/// Gives `records` one automatic-loading group.
69pub(crate) fn group_records<'a, M: Model>(records: impl Iterator<Item = &'a mut Record<M>>) {
70    let mut records: Vec<&mut Record<M>> = records.collect();
71    if records.is_empty() {
72        return;
73    }
74    let snapshots: Vec<Record<M>> = records
75        .iter()
76        .map(|record| record.without_relations())
77        .collect();
78    let group = Arc::new(AutoloadGroup {
79        records: tokio::sync::Mutex::new(snapshots),
80    });
81    for (index, record) in records.iter_mut().enumerate() {
82        record.loading.autoload = Some((Arc::clone(&group), index));
83    }
84}
85
86impl<M: Model> AutoloadGroup<M> {
87    /// Relation `name` of the group's record `index`, loading it for every
88    /// record of the group the first time.
89    async fn load(
90        &self,
91        target: &Target<'_>,
92        relation: &DynRelation<M>,
93        name: &str,
94        index: usize,
95        into: &mut Relations,
96    ) -> Result<()> {
97        let mut records = self.records.lock().await;
98        if !records[index].relations.is_loaded(name) {
99            let node = EagerNode {
100                name: name.to_owned(),
101                autoload: true,
102                ..EagerNode::default()
103            };
104            relation
105                .inner
106                .eager_load(target, &mut records, &node)
107                .await?;
108        }
109        into.copy_from(&records[index].relations, name);
110        Ok(())
111    }
112}
113
114/// A lazy load that the lazy-loading rules flagged: relation `relation` of
115/// a `model` record that came from a result of several records.
116#[derive(Clone, Debug, PartialEq, Eq)]
117pub struct LazyLoadingViolation {
118    model: &'static str,
119    relation: String,
120}
121
122impl LazyLoadingViolation {
123    /// The model.
124    pub fn model(&self) -> &'static str {
125        self.model
126    }
127
128    /// The relation.
129    pub fn relation(&self) -> &str {
130        &self.relation
131    }
132}
133
134impl fmt::Display for LazyLoadingViolation {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        write!(
137            f,
138            "relation `{}` of {} was loaded lazily for a record of a multi-record result",
139            self.relation, self.model
140        )
141    }
142}
143
144/// Handles a lazy-loading violation: `Ok` lets the load go ahead.
145type ViolationHandler = Arc<dyn Fn(&LazyLoadingViolation) -> Result<()> + Send + Sync>;
146
147/// The lazy-loading rules: loading a relation one record at a time is how
148/// N+1 query problems start.
149///
150/// - [`prevented`](LazyLoading::prevented): a lazy load
151///   ([`Record::relation_or_load`]) on a record that came from a result of
152///   several records is an error, [`OrmError::LazyLoading`] (a record
153///   fetched alone may load lazily); [`on_violation`](LazyLoading::on_violation)
154///   handles it another way (log it and go ahead).
155/// - [`automatic`](LazyLoading::automatic): a lazy load on one record of a
156///   result loads the relation for every record of the result, in one
157///   query (`with_relationship_autoloading` does this for one collection).
158///
159/// Where the rules come from, first match wins: a [`scope`](LazyLoading::scope)
160/// around the running task; the rules [`install`](LazyLoading::install)ed
161/// process-wide; the [strict modes](crate::strict) of the operation (the
162/// `[orm]` options `prevent_lazy_loading` and `auto_eager_load`, and
163/// `OrmModule`'s `on_lazy_loading` handler; see
164/// [`from_strictness`](LazyLoading::from_strictness)).
165///
166/// ```no_run
167/// # use navree_orm::__doc_models::*;
168/// use navree_orm::relations::LazyLoading;
169///
170/// LazyLoading::new()
171///     .prevented()
172///     .on_violation(|violation| {
173///         eprintln!("N+1: {violation}");
174///         Ok(())
175///     })
176///     .install();
177/// ```
178#[derive(Clone, Default)]
179pub struct LazyLoading {
180    prevent: bool,
181    automatic: bool,
182    handler: Option<ViolationHandler>,
183}
184
185fn installed() -> &'static RwLock<Option<LazyLoading>> {
186    static INSTALLED: OnceLock<RwLock<Option<LazyLoading>>> = OnceLock::new();
187    INSTALLED.get_or_init(|| RwLock::new(None))
188}
189
190tokio::task_local! {
191    static SCOPED: LazyLoading;
192}
193
194impl LazyLoading {
195    /// Lazy loading allowed, nothing automatic.
196    pub fn new() -> Self {
197        LazyLoading::default()
198    }
199
200    /// The rules `strictness` describes: lazy loading prevented when its
201    /// `prevent_lazy_loading` mode is on (a violation is answered by the
202    /// strictness: its `on_lazy_loading` handler, else
203    /// [`OrmError::LazyLoading`]), automatic when `auto_eager_load` is.
204    pub fn from_strictness(strictness: Strictness) -> Self {
205        let prevent = strictness.prevents_lazy_loading();
206        let automatic = strictness.auto_eager_loads();
207        let handler = prevent.then(|| {
208            Arc::new(move |violation: &LazyLoadingViolation| {
209                strictness.check(Violation::LazyLoading {
210                    model: violation.model,
211                    relation: Cow::Owned(violation.relation.clone()),
212                })
213            }) as ViolationHandler
214        });
215        LazyLoading {
216            prevent,
217            automatic,
218            handler,
219        }
220    }
221
222    /// Lazy loads of records from multi-record results are violations.
223    pub fn prevented(mut self) -> Self {
224        self.prevent = true;
225        self
226    }
227
228    /// A lazy load on one record of a result loads the relation for the
229    /// whole result.
230    pub fn automatic(mut self) -> Self {
231        self.automatic = true;
232        self
233    }
234
235    /// Handles violations with `handler` (its `Ok` lets the load go ahead)
236    /// instead of failing with [`OrmError::LazyLoading`].
237    pub fn on_violation(
238        mut self,
239        handler: impl Fn(&LazyLoadingViolation) -> Result<()> + Send + Sync + 'static,
240    ) -> Self {
241        self.handler = Some(Arc::new(handler));
242        self
243    }
244
245    /// Whether lazy loads of records from multi-record results are
246    /// violations.
247    pub fn is_prevented(&self) -> bool {
248        self.prevent
249    }
250
251    /// Whether lazy loads load for the whole result.
252    pub fn is_automatic(&self) -> bool {
253        self.automatic
254    }
255
256    /// Makes these the process-wide rules (over the strict modes).
257    pub fn install(self) {
258        *installed()
259            .write()
260            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(self);
261    }
262
263    /// Runs `future` under these rules instead of the process-wide ones.
264    pub async fn scope<F: Future>(self, future: F) -> F::Output {
265        SCOPED.scope(self, future).await
266    }
267
268    /// The rules in effect for code without an executor: the scoped ones,
269    /// else the installed ones, else those of the strict modes
270    /// ([`strict::current`](crate::strict::current)).
271    pub fn current() -> LazyLoading {
272        LazyLoading::chosen()
273            .unwrap_or_else(|| LazyLoading::from_strictness(crate::strict::current()))
274    }
275
276    /// The rules for an operation in `ctx`: the scoped ones, else the
277    /// installed ones, else those of the strict modes of the executor's app
278    /// ([`ExecContext::strictness`]).
279    pub(crate) async fn for_context(ctx: &ExecContext) -> LazyLoading {
280        match LazyLoading::chosen() {
281            Some(rules) => rules,
282            None => LazyLoading::from_strictness(ctx.strictness().await),
283        }
284    }
285
286    /// The scoped rules, else the installed ones.
287    fn chosen() -> Option<LazyLoading> {
288        SCOPED.try_with(Clone::clone).ok().or_else(|| {
289            installed()
290                .read()
291                .unwrap_or_else(std::sync::PoisonError::into_inner)
292                .clone()
293        })
294    }
295
296    /// A violation: the handler's answer, or the error.
297    fn violation(&self, model: &'static str, relation: &str) -> Result<()> {
298        let violation = LazyLoadingViolation {
299            model,
300            relation: relation.to_owned(),
301        };
302        match &self.handler {
303            Some(handler) => handler(&violation),
304            None => Err(OrmError::LazyLoading {
305                model: Cow::Borrowed(model),
306                relation: Cow::Owned(relation.to_owned()),
307            }),
308        }
309    }
310}
311
312impl fmt::Debug for LazyLoading {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        f.debug_struct("LazyLoading")
315            .field("prevent", &self.prevent)
316            .field("automatic", &self.automatic)
317            .field("handler", &self.handler.is_some())
318            .finish()
319    }
320}
321
322/// Marks the records of one query's result for the lazy-loading `rules`.
323pub(crate) fn mark_result<M: Model>(records: &mut [Record<M>], rules: &LazyLoading) {
324    if records.len() < 2 {
325        return;
326    }
327    if rules.prevent {
328        for record in records.iter_mut() {
329            record.loading.prevent = true;
330        }
331    }
332    if rules.automatic {
333        group_records(records.iter_mut());
334    }
335}
336
337/// Saves `record`, then the records of its loaded relations
338/// (recursively); `false` when a hook cancelled a save.
339pub(crate) fn push_record<'a, 'b, M: Model>(
340    record: &'a mut Record<M>,
341    target: &'a Target<'b>,
342) -> BoxFuture<'a, Result<bool>> {
343    Box::pin(async move {
344        if !crate::persist::save(target, record).await? {
345            return Ok(false);
346        }
347        record.relations.push_all(target).await
348    })
349}
350
351/// The eager-load tree of `paths`.
352fn tree_of<M: Model>(paths: impl IntoIterator<Item = impl RelationPath<M>>) -> Result<EagerTree> {
353    let mut tree = EagerTree::default();
354    for path in paths {
355        let text = path.relation_path().into_owned();
356        let parsed = ParsedPath::parse(&text)?;
357        let node = tree.entry(&parsed.segments);
358        if parsed.columns.is_some() {
359            node.columns = parsed.columns;
360        }
361    }
362    Ok(tree)
363}
364
365/// Loads the relations of `tree` that `records` miss, and what is missing
366/// under the loaded ones.
367pub(crate) fn load_missing_tree<'a, 'b, M: Model>(
368    target: &'a Target<'b>,
369    records: &'a mut [Record<M>],
370    tree: &'a EagerTree,
371) -> BoxFuture<'a, Result<()>> {
372    Box::pin(async move {
373        if records.is_empty() {
374            return Ok(());
375        }
376        for node in &tree.nodes {
377            let relation = registry::find::<M>(&node.name)?;
378            let missing: Vec<usize> = records
379                .iter()
380                .enumerate()
381                .filter(|(_, record)| !record.relations.is_loaded(&node.name))
382                .map(|(index, _)| index)
383                .collect();
384            if !missing.is_empty() {
385                let mut snapshots: Vec<Record<M>> = missing
386                    .iter()
387                    .map(|index| records[*index].without_relations())
388                    .collect();
389                let shallow = EagerNode {
390                    children: EagerTree::default(),
391                    ..node.clone()
392                };
393                relation
394                    .inner
395                    .eager_load(target, &mut snapshots, &shallow)
396                    .await?;
397                for (index, snapshot) in missing.into_iter().zip(&snapshots) {
398                    records[index]
399                        .relations
400                        .copy_from(&snapshot.relations, &node.name);
401                }
402            }
403            if !node.children.is_empty() {
404                relation
405                    .inner
406                    .load_nested_missing(target, records, &node.children)
407                    .await?;
408            }
409        }
410        Ok(())
411    })
412}
413
414/// For the parents with `name` loaded as `Option<Record<R>>`: loads what
415/// `rest` misses into those records.
416pub(crate) async fn load_nested_one<P: Model, R: Model>(
417    target: &Target<'_>,
418    parents: &mut [Record<P>],
419    name: &str,
420    rest: &EagerTree,
421) -> Result<()> {
422    let mut owners = Vec::new();
423    let mut related = Vec::new();
424    for (index, parent) in parents.iter_mut().enumerate() {
425        if matches!(
426            parent.relations.get::<Option<Record<R>>>(name),
427            Some(Some(_))
428        ) && let Some(Some(record)) = parent.relations.take::<Option<Record<R>>>(name)
429        {
430            owners.push(index);
431            related.push(record);
432        }
433    }
434    let result = load_missing_tree(target, &mut related, rest).await;
435    for (index, record) in owners.into_iter().zip(related) {
436        parents[index]
437            .relations
438            .set_relation(name.to_owned(), Some(record));
439    }
440    result
441}
442
443/// For the parents with `name` loaded as a `Collection<R>`: loads what
444/// `rest` misses into those records.
445pub(crate) async fn load_nested_many<P: Model, R: Model>(
446    target: &Target<'_>,
447    parents: &mut [Record<P>],
448    name: &str,
449    rest: &EagerTree,
450) -> Result<()> {
451    let mut owners = Vec::new();
452    let mut related: Vec<Record<R>> = Vec::new();
453    for (index, parent) in parents.iter_mut().enumerate() {
454        if let Some(collection) = parent.relations.take::<Collection<R>>(name) {
455            let records = collection.into_vec();
456            owners.push((index, records.len()));
457            related.extend(records);
458        }
459    }
460    let result = load_missing_tree(target, &mut related, rest).await;
461    let mut records = related.into_iter();
462    for (index, count) in owners {
463        let collection: Collection<R> = records.by_ref().take(count).collect();
464        parents[index]
465            .relations
466            .set_relation(name.to_owned(), collection);
467    }
468    result
469}
470
471/// Loads what `rest` misses into `records`, all of `morph_target`'s
472/// model.
473pub(crate) async fn load_missing_any(
474    target: &Target<'_>,
475    morph_target: &dyn MorphTarget,
476    records: Vec<AnyRecord>,
477    rest: &EagerTree,
478) -> Result<Vec<AnyRecord>> {
479    morph_target.load_missing_into(target, records, rest).await
480}
481
482/// Loads `with`'s per-model loads (or, with `aggregate`, those aggregates
483/// of the relations it lists) into the records `morph_to` relation `name`
484/// holds on `records`, loading the relation first where it is missing.
485async fn load_morph_on<M: Model>(
486    target: &Target<'_>,
487    records: &mut [Record<M>],
488    name: &str,
489    with: &MorphWith,
490    aggregate: Option<&AggregateSpec>,
491) -> Result<()> {
492    let relation = registry::find::<M>(name)?;
493    let Some(morph) = relation.inner.morph_to() else {
494        return Err(OrmError::invalid(format!(
495            "`{name}` of {} is a {}, not a morph_to relation",
496            M::meta().name(),
497            relation.kind()
498        )));
499    };
500    let tree = tree_of::<M>([name])?;
501    load_missing_tree(target, records, &tree).await?;
502    let mut taken: Vec<Option<AnyRecord>> = records
503        .iter_mut()
504        .map(|record| record.relations.take::<Option<AnyRecord>>(name).flatten())
505        .collect();
506    let mut names: Vec<String> = Vec::new();
507    for record in taken.iter().flatten() {
508        let morph_name = record.morph_name().into_owned();
509        if !names.contains(&morph_name) {
510            names.push(morph_name);
511        }
512    }
513    let mut result = Ok(());
514    for morph_name in names {
515        let morph_target = match morph.target_for(&morph_name) {
516            Ok(morph_target) => morph_target,
517            Err(error) => {
518                result = Err(error);
519                break;
520            }
521        };
522        let Some(loads) = with.for_type(morph_target.type_id()) else {
523            continue;
524        };
525        let indexes: Vec<usize> = taken
526            .iter()
527            .enumerate()
528            .filter(|(_, record)| {
529                record
530                    .as_ref()
531                    .is_some_and(|record| record.morph_name() == morph_name)
532            })
533            .map(|(index, _)| index)
534            .collect();
535        let of_type: Vec<AnyRecord> = indexes
536            .iter()
537            .filter_map(|index| taken[*index].take())
538            .collect();
539        match morph_target
540            .load_into(target, of_type, loads, aggregate)
541            .await
542        {
543            Ok(loaded) => {
544                for (index, record) in indexes.into_iter().zip(loaded) {
545                    taken[index] = Some(record);
546                }
547            }
548            Err(error) => {
549                result = Err(error);
550                break;
551            }
552        }
553    }
554    for (record, value) in records.iter_mut().zip(taken) {
555        record.relations.set_relation(name.to_owned(), value);
556    }
557    result
558}
559
560impl<M: Model> Record<M> {
561    /// Relation `name`, when it is loaded as a `T` (`Option<Record<R>>` for
562    /// a to-one relation, `Collection<R>` for a to-many one,
563    /// `Option<AnyRecord>` for a `morph_to`).
564    pub fn relation<T: 'static>(&self, name: &str) -> Option<&T> {
565        self.relations.get::<T>(name)
566    }
567
568    /// Relation `name` for changes, when it is loaded as a `T`.
569    pub fn relation_mut<T: 'static>(&mut self, name: &str) -> Option<&mut T> {
570        self.relations.get_mut::<T>(name)
571    }
572
573    /// Sets relation `name` (as if it was loaded).
574    pub fn set_relation<V: RelationValue>(&mut self, name: impl Into<Cow<'static, str>>, value: V) {
575        self.relations.set_relation(name, value);
576    }
577
578    /// Whether relation `name` is loaded.
579    pub fn relation_loaded(&self, name: &str) -> bool {
580        self.relations.is_loaded(name)
581    }
582
583    /// Forgets relation `name`.
584    pub fn unset_relation(&mut self, name: &str) {
585        self.relations.unset(name);
586    }
587
588    /// Replaces the loaded relations.
589    pub fn set_relations(&mut self, relations: Relations) {
590        self.relations = relations;
591    }
592
593    /// Forgets every loaded relation.
594    pub fn unset_relations(&mut self) {
595        self.relations.clear();
596    }
597
598    /// A copy of the record without its loaded relations.
599    pub fn without_relations(&self) -> Record<M> {
600        Record {
601            model: self.model.clone(),
602            original: self.original.clone(),
603            exists: self.exists,
604            recently_created: self.recently_created,
605            changes: self.changes.clone(),
606            previous: self.previous.clone(),
607            extras: self.extras.clone(),
608            relations: Relations::new(),
609            force_deleting: self.force_deleting,
610            loading: LoadState::default(),
611            attributes: self.attributes.clone(),
612        }
613    }
614
615    /// A copy of the record without loaded relation `name`.
616    pub fn without_relation(&self, name: &str) -> Record<M> {
617        let mut copy = self.clone();
618        copy.relations.unset(name);
619        copy
620    }
621
622    /// The loaded value of `relation` (a relation method, `Deal::company`),
623    /// typed by the relation: no query.
624    ///
625    /// ```no_run
626    /// # use navree_orm::__doc_models::*;
627    /// # async fn demo(db: Db) -> Result<()> {
628    /// let deals = Deal::query().with("company").get(&db).await?;
629    /// let company: Option<&Record<Company>> = deals[0].loaded(Deal::company).and_then(Option::as_ref);
630    /// # Ok(()) }
631    /// ```
632    pub fn loaded<R: Relation<M>>(&self, relation: impl Fn(&M) -> R) -> Option<&R::Value> {
633        let name = relation(&self.model).name().to_owned();
634        self.relations.get::<R::Value>(&name)
635    }
636
637    /// Relation `name` as a `T`, loaded now if it is not loaded yet, under
638    /// the [`LazyLoading`] rules: with automatic loading, the load covers
639    /// the record's whole result; when lazy loading is prevented and the
640    /// record came from a result of several records, it is a violation.
641    pub async fn relation_or_load<T: 'static, E: Executor + ?Sized>(
642        &mut self,
643        exec: &E,
644        name: &str,
645    ) -> Result<&T> {
646        if !self.relations.is_loaded(name) {
647            let relation = registry::find::<M>(name)?;
648            let target = exec.target(Access::Read).await?;
649            match self.loading.autoload.clone() {
650                Some((group, index)) => {
651                    group
652                        .load(&target, &relation, name, index, &mut self.relations)
653                        .await?;
654                }
655                None => {
656                    if self.loading.prevent {
657                        LazyLoading::for_context(&target.context())
658                            .await
659                            .violation(M::meta().name(), name)?;
660                    }
661                    let node = EagerNode {
662                        name: name.to_owned(),
663                        ..EagerNode::default()
664                    };
665                    relation
666                        .inner
667                        .eager_load(&target, std::slice::from_mut(self), &node)
668                        .await?;
669                }
670            }
671        }
672        self.relations.get::<T>(name).ok_or_else(|| {
673            OrmError::invalid(format!(
674                "relation `{name}` of {} is loaded, but not as a {}",
675                M::meta().name(),
676                std::any::type_name::<T>()
677            ))
678        })
679    }
680
681    /// The value of `relation` (a relation method), loaded now if needed
682    /// (see [`relation_or_load`](Record::relation_or_load)).
683    pub async fn related<R: Relation<M>, E: Executor + ?Sized>(
684        &mut self,
685        exec: &E,
686        relation: impl Fn(&M) -> R,
687    ) -> Result<&R::Value> {
688        let name = relation(&self.model).name().to_owned();
689        self.relation_or_load::<R::Value, E>(exec, &name).await
690    }
691
692    /// Eager loads relation `path` onto the record (again, if it is
693    /// loaded).
694    pub async fn load<E: Executor + ?Sized>(
695        &mut self,
696        exec: &E,
697        path: impl RelationPath<M>,
698    ) -> Result<()> {
699        let tree = tree_of::<M>([path])?;
700        let target = exec.target(Access::Read).await?;
701        load_tree(&target, std::slice::from_mut(self), &tree).await
702    }
703
704    /// Eager loads every relation path of `paths` onto the record.
705    pub async fn load_all<E: Executor + ?Sized>(
706        &mut self,
707        exec: &E,
708        paths: impl IntoIterator<Item = impl RelationPath<M>>,
709    ) -> Result<()> {
710        let tree = tree_of::<M>(paths)?;
711        let target = exec.target(Access::Read).await?;
712        load_tree(&target, std::slice::from_mut(self), &tree).await
713    }
714
715    /// Eager loads relation `path`, constrained by `constraint` (see
716    /// [`Builder::with_constrained`](crate::Builder::with_constrained)).
717    pub async fn load_constrained<Q: 'static, E: Executor + ?Sized>(
718        &mut self,
719        exec: &E,
720        path: impl ConstrainPath<M, Q>,
721        constraint: impl Fn(Q) -> Q + Send + Sync + 'static,
722    ) -> Result<()> {
723        let text = path.relation_path().into_owned();
724        let parsed = ParsedPath::parse(&text)?;
725        let mut tree = EagerTree::default();
726        let node = tree.entry(&parsed.segments);
727        node.columns = parsed.columns;
728        node.constraints.push(Constraint::new(constraint));
729        let target = exec.target(Access::Read).await?;
730        load_tree(&target, std::slice::from_mut(self), &tree).await
731    }
732
733    /// Loads the relations of `paths` the record does not have loaded (and,
734    /// down a nested path, the ones its loaded records miss).
735    pub async fn load_missing<E: Executor + ?Sized>(
736        &mut self,
737        exec: &E,
738        paths: impl IntoIterator<Item = impl RelationPath<M>>,
739    ) -> Result<()> {
740        let tree = tree_of::<M>(paths)?;
741        let target = exec.target(Access::Read).await?;
742        load_missing_tree(&target, std::slice::from_mut(self), &tree).await
743    }
744
745    async fn load_aggregate_paths<E: Executor + ?Sized>(
746        &mut self,
747        exec: &E,
748        paths: Vec<String>,
749        spec: AggregateSpec,
750    ) -> Result<()> {
751        let target = exec.target(Access::Read).await?;
752        load_aggregate_on(&target, std::slice::from_mut(self), &paths, &spec).await
753    }
754
755    /// Loads `{relation}_count` of each relation of `paths` into the
756    /// record's extras.
757    pub async fn load_count<E: Executor + ?Sized>(
758        &mut self,
759        exec: &E,
760        paths: impl IntoIterator<Item = impl RelationPath<M>>,
761    ) -> Result<()> {
762        let paths = paths
763            .into_iter()
764            .map(|path| path.relation_path().into_owned())
765            .collect();
766        self.load_aggregate_paths(exec, paths, AggregateSpec::count())
767            .await
768    }
769
770    /// Loads `{relation}_exists` of each relation of `paths`.
771    pub async fn load_exists<E: Executor + ?Sized>(
772        &mut self,
773        exec: &E,
774        paths: impl IntoIterator<Item = impl RelationPath<M>>,
775    ) -> Result<()> {
776        let paths = paths
777            .into_iter()
778            .map(|path| path.relation_path().into_owned())
779            .collect();
780        self.load_aggregate_paths(exec, paths, AggregateSpec::exists())
781            .await
782    }
783
784    /// Loads `function` of related `column` of relation `path`
785    /// (`{relation}_{function}_{column}`).
786    pub async fn load_aggregate<E: Executor + ?Sized>(
787        &mut self,
788        exec: &E,
789        path: impl RelationPath<M>,
790        column: impl IntoExpr,
791        function: AggregateFunction,
792    ) -> Result<()> {
793        let spec = AggregateSpec::function(function, column)?;
794        let paths = vec![path.relation_path().into_owned()];
795        self.load_aggregate_paths(exec, paths, spec).await
796    }
797
798    /// Loads `{relation}_sum_{column}`.
799    pub async fn load_sum<E: Executor + ?Sized>(
800        &mut self,
801        exec: &E,
802        path: impl RelationPath<M>,
803        column: impl IntoExpr,
804    ) -> Result<()> {
805        self.load_aggregate(exec, path, column, AggregateFunction::Sum)
806            .await
807    }
808
809    /// Loads `{relation}_avg_{column}`.
810    pub async fn load_avg<E: Executor + ?Sized>(
811        &mut self,
812        exec: &E,
813        path: impl RelationPath<M>,
814        column: impl IntoExpr,
815    ) -> Result<()> {
816        self.load_aggregate(exec, path, column, AggregateFunction::Avg)
817            .await
818    }
819
820    /// Loads `{relation}_min_{column}`.
821    pub async fn load_min<E: Executor + ?Sized>(
822        &mut self,
823        exec: &E,
824        path: impl RelationPath<M>,
825        column: impl IntoExpr,
826    ) -> Result<()> {
827        self.load_aggregate(exec, path, column, AggregateFunction::Min)
828            .await
829    }
830
831    /// Loads `{relation}_max_{column}`.
832    pub async fn load_max<E: Executor + ?Sized>(
833        &mut self,
834        exec: &E,
835        path: impl RelationPath<M>,
836        column: impl IntoExpr,
837    ) -> Result<()> {
838        self.load_aggregate(exec, path, column, AggregateFunction::Max)
839            .await
840    }
841
842    /// Loads `morph_to` relation `name` (if missing), then `with`'s
843    /// per-model loads into the record it holds.
844    pub async fn load_morph<E: Executor + ?Sized>(
845        &mut self,
846        exec: &E,
847        name: &str,
848        with: MorphWith,
849    ) -> Result<()> {
850        let target = exec.target(Access::Read).await?;
851        load_morph_on(&target, std::slice::from_mut(self), name, &with, None).await
852    }
853
854    /// Loads, onto the record `morph_to` relation `name` holds, the counts
855    /// of the relations `with` lists for its model (with `on` or
856    /// `count_on`): `{relation}_count`.
857    ///
858    /// ```no_run
859    /// # use navree_orm::__doc_models::*;
860    /// use navree_orm::relations::MorphWith;
861    ///
862    /// # async fn demo(db: Db, mut note: Record<Note>) -> Result<()> {
863    /// note.load_morph_count(&db, "notable", MorphWith::new().count_on::<Deal>(["activities"]))
864    ///     .await?;
865    /// # Ok(()) }
866    /// ```
867    pub async fn load_morph_count<E: Executor + ?Sized>(
868        &mut self,
869        exec: &E,
870        name: &str,
871        with: MorphWith,
872    ) -> Result<()> {
873        let target = exec.target(Access::Read).await?;
874        let spec = AggregateSpec::count();
875        load_morph_on(
876            &target,
877            std::slice::from_mut(self),
878            name,
879            &with,
880            Some(&spec),
881        )
882        .await
883    }
884
885    /// Loads `function` of `column` of the relations `with` lists for its
886    /// model (with `on` or `count_on`), onto the record `morph_to`
887    /// relation `name` holds: `{relation}_{function}_{column}`.
888    pub async fn load_morph_aggregate<E: Executor + ?Sized>(
889        &mut self,
890        exec: &E,
891        name: &str,
892        with: MorphWith,
893        column: impl IntoExpr,
894        function: AggregateFunction,
895    ) -> Result<()> {
896        let target = exec.target(Access::Read).await?;
897        let spec = AggregateSpec::function(function, column)?;
898        load_morph_on(
899            &target,
900            std::slice::from_mut(self),
901            name,
902            &with,
903            Some(&spec),
904        )
905        .await
906    }
907
908    /// [`load_morph_aggregate`](Record::load_morph_aggregate) with `SUM`.
909    pub async fn load_morph_sum<E: Executor + ?Sized>(
910        &mut self,
911        exec: &E,
912        name: &str,
913        with: MorphWith,
914        column: impl IntoExpr,
915    ) -> Result<()> {
916        self.load_morph_aggregate(exec, name, with, column, AggregateFunction::Sum)
917            .await
918    }
919
920    /// [`load_morph_aggregate`](Record::load_morph_aggregate) with `AVG`.
921    pub async fn load_morph_avg<E: Executor + ?Sized>(
922        &mut self,
923        exec: &E,
924        name: &str,
925        with: MorphWith,
926        column: impl IntoExpr,
927    ) -> Result<()> {
928        self.load_morph_aggregate(exec, name, with, column, AggregateFunction::Avg)
929            .await
930    }
931
932    /// [`load_morph_aggregate`](Record::load_morph_aggregate) with `MIN`.
933    pub async fn load_morph_min<E: Executor + ?Sized>(
934        &mut self,
935        exec: &E,
936        name: &str,
937        with: MorphWith,
938        column: impl IntoExpr,
939    ) -> Result<()> {
940        self.load_morph_aggregate(exec, name, with, column, AggregateFunction::Min)
941            .await
942    }
943
944    /// [`load_morph_aggregate`](Record::load_morph_aggregate) with `MAX`.
945    pub async fn load_morph_max<E: Executor + ?Sized>(
946        &mut self,
947        exec: &E,
948        name: &str,
949        with: MorphWith,
950        column: impl IntoExpr,
951    ) -> Result<()> {
952        self.load_morph_aggregate(exec, name, with, column, AggregateFunction::Max)
953            .await
954    }
955
956    /// Saves the record, then every record of its loaded relations, and
957    /// theirs (`false` when a hook cancelled a save; the records before it
958    /// stay saved).
959    pub async fn push<E: Executor + ?Sized>(&mut self, exec: &E) -> Result<bool> {
960        let target = exec.target(Access::Write).await?;
961        push_record(self, &target).await
962    }
963
964    /// [`push`](Record::push) without model events.
965    pub async fn push_quietly<E: Executor + ?Sized>(&mut self, exec: &E) -> Result<bool> {
966        crate::events::without_events(self.push(exec)).await
967    }
968
969    /// Points `relation` (a `belongs_to` or `morph_to` relation method,
970    /// `Deal::company`) at `related`: sets the foreign key (and the type of
971    /// a `morph_to`) and the loaded relation. Saving is separate.
972    ///
973    /// ```no_run
974    /// # use navree_orm::__doc_models::*;
975    /// # async fn demo(uow: Uow, mut deal: Record<Deal>, agra: Record<Company>) -> Result<()> {
976    /// deal.associate(Deal::company, &agra)?;
977    /// assert_eq!(deal.company_id, Some(agra.id));
978    /// deal.save(&uow).await?;
979    /// # Ok(()) }
980    /// ```
981    pub fn associate<R, X>(&mut self, relation: impl Fn(&M) -> R, related: &X) -> Result<&mut Self>
982    where
983        R: Associate<M, X>,
984    {
985        relation(&self.model).associate_with(self, related)?;
986        Ok(self)
987    }
988
989    /// Clears `relation` (a `belongs_to` or `morph_to` relation method):
990    /// the foreign key (and type) NULL, the loaded relation `None`.
991    pub fn dissociate<R>(&mut self, relation: impl Fn(&M) -> R) -> Result<&mut Self>
992    where
993        R: Dissociate<M>,
994    {
995        relation(&self.model).dissociate_from(self)?;
996        Ok(self)
997    }
998
999    /// Gives the record an automatic-loading group of its own: relations
1000    /// loaded lazily on its loaded records load for all of them at once.
1001    pub fn with_relationship_autoloading(mut self) -> Self {
1002        group_records(std::iter::once(&mut self));
1003        self
1004    }
1005
1006    /// The pivot row a many-to-many relation loaded the record with (under
1007    /// `pivot`).
1008    pub fn pivot(&self) -> Option<&Pivot> {
1009        self.relations.get::<Pivot>("pivot")
1010    }
1011
1012    /// The typed pivot record (`.using::<P>()`) the record was loaded with
1013    /// (under `pivot`).
1014    pub fn pivot_as<P: Model>(&self) -> Option<&Record<P>> {
1015        self.relations.get::<Record<P>>("pivot")
1016    }
1017
1018    /// Column `column` of the pivot row the record was loaded with (under
1019    /// `pivot`) read as `T`: from a [`Pivot`], or a typed pivot record's
1020    /// columns. `None` when there is no pivot or no such column.
1021    pub fn pivot_value<T: Field>(&self, column: &str) -> Result<Option<T>> {
1022        match self.relations.column("pivot", column) {
1023            Some(value) => T::from_value(value).map(Some).map_err(|error| {
1024                crate::row::decode_error(
1025                    format!("the pivot of {}", M::meta().name()),
1026                    column,
1027                    T::type_name(),
1028                    &error,
1029                )
1030            }),
1031            None => Ok(None),
1032        }
1033    }
1034}
1035
1036/// A relation that can point a record at another (`associate`).
1037pub trait Associate<M: Model, X> {
1038    /// Points `child`'s relation at `related`.
1039    #[doc(hidden)]
1040    fn associate_with(&self, child: &mut Record<M>, related: &X) -> Result<()>;
1041}
1042
1043/// A relation that can be cleared (`dissociate`).
1044pub trait Dissociate<M: Model> {
1045    /// Clears `child`'s relation.
1046    #[doc(hidden)]
1047    fn dissociate_from(&self, child: &mut Record<M>) -> Result<()>;
1048}
1049
1050impl<M: Model, R: Model> Associate<M, Record<R>> for BelongsTo<M, R> {
1051    fn associate_with(&self, child: &mut Record<M>, related: &Record<R>) -> Result<()> {
1052        let owner = column_value(&related.model, &self.owner_key, &self.core.name)?;
1053        child.model.set_value(&self.foreign_key, owner)?;
1054        child
1055            .relations
1056            .set_relation(self.core.name.to_string(), Some(related.clone()));
1057        Ok(())
1058    }
1059}
1060
1061impl<M: Model, R: Model> Dissociate<M> for BelongsTo<M, R> {
1062    fn dissociate_from(&self, child: &mut Record<M>) -> Result<()> {
1063        child
1064            .model
1065            .set_value(&self.foreign_key, Value::Null(Kind::String))?;
1066        child
1067            .relations
1068            .set_relation(self.core.name.to_string(), None::<Record<R>>);
1069        Ok(())
1070    }
1071}
1072
1073impl<M: Model, X: Model> Associate<M, Record<X>> for MorphTo<M> {
1074    fn associate_with(&self, child: &mut Record<M>, related: &Record<X>) -> Result<()> {
1075        let id = match &self.owner_key {
1076            Some(column) => column_value(&related.model, column, &self.name)?,
1077            None => related.key().to_value(),
1078        };
1079        child.model.set_value(&self.id_column, id)?;
1080        child.model.set_value(
1081            &self.type_column,
1082            crate::relations::morph::stored_type_of::<X>()?,
1083        )?;
1084        child
1085            .relations
1086            .set_relation(self.name.to_string(), Some(AnyRecord::new(related.clone())));
1087        Ok(())
1088    }
1089}
1090
1091impl<M: Model> Dissociate<M> for MorphTo<M> {
1092    fn dissociate_from(&self, child: &mut Record<M>) -> Result<()> {
1093        child
1094            .model
1095            .set_value(&self.id_column, Value::Null(Kind::String))?;
1096        child
1097            .model
1098            .set_value(&self.type_column, Value::Null(Kind::String))?;
1099        child
1100            .relations
1101            .set_relation(self.name.to_string(), None::<AnyRecord>);
1102        Ok(())
1103    }
1104}
1105
1106impl<M: Model> Collection<M> {
1107    async fn load_tree_into<E: Executor + ?Sized>(
1108        &mut self,
1109        exec: &E,
1110        tree: &EagerTree,
1111    ) -> Result<()> {
1112        let target = exec.target(Access::Read).await?;
1113        load_tree(&target, self, tree).await
1114    }
1115
1116    /// Eager loads relation `path` onto every record (one query per
1117    /// relation and level).
1118    pub async fn load<E: Executor + ?Sized>(
1119        &mut self,
1120        exec: &E,
1121        path: impl RelationPath<M>,
1122    ) -> Result<()> {
1123        let tree = tree_of::<M>([path])?;
1124        self.load_tree_into(exec, &tree).await
1125    }
1126
1127    /// Eager loads every relation path of `paths` onto every record.
1128    pub async fn load_all<E: Executor + ?Sized>(
1129        &mut self,
1130        exec: &E,
1131        paths: impl IntoIterator<Item = impl RelationPath<M>>,
1132    ) -> Result<()> {
1133        let tree = tree_of::<M>(paths)?;
1134        self.load_tree_into(exec, &tree).await
1135    }
1136
1137    /// Eager loads relation `path` onto every record, constrained by
1138    /// `constraint`.
1139    pub async fn load_constrained<Q: 'static, E: Executor + ?Sized>(
1140        &mut self,
1141        exec: &E,
1142        path: impl ConstrainPath<M, Q>,
1143        constraint: impl Fn(Q) -> Q + Send + Sync + 'static,
1144    ) -> Result<()> {
1145        let text = path.relation_path().into_owned();
1146        let parsed = ParsedPath::parse(&text)?;
1147        let mut tree = EagerTree::default();
1148        let node = tree.entry(&parsed.segments);
1149        node.columns = parsed.columns;
1150        node.constraints.push(Constraint::new(constraint));
1151        self.load_tree_into(exec, &tree).await
1152    }
1153
1154    /// Loads the relations of `paths` the records miss (and, down nested
1155    /// paths, what their loaded records miss).
1156    pub async fn load_missing<E: Executor + ?Sized>(
1157        &mut self,
1158        exec: &E,
1159        paths: impl IntoIterator<Item = impl RelationPath<M>>,
1160    ) -> Result<()> {
1161        let tree = tree_of::<M>(paths)?;
1162        let target = exec.target(Access::Read).await?;
1163        load_missing_tree(&target, self, &tree).await
1164    }
1165
1166    async fn load_aggregate_paths<E: Executor + ?Sized>(
1167        &mut self,
1168        exec: &E,
1169        paths: Vec<String>,
1170        spec: AggregateSpec,
1171    ) -> Result<()> {
1172        let target = exec.target(Access::Read).await?;
1173        load_aggregate_on(&target, self, &paths, &spec).await
1174    }
1175
1176    /// Loads `{relation}_count` of each relation of `paths` onto every
1177    /// record (one query).
1178    pub async fn load_count<E: Executor + ?Sized>(
1179        &mut self,
1180        exec: &E,
1181        paths: impl IntoIterator<Item = impl RelationPath<M>>,
1182    ) -> Result<()> {
1183        let paths = paths
1184            .into_iter()
1185            .map(|path| path.relation_path().into_owned())
1186            .collect();
1187        self.load_aggregate_paths(exec, paths, AggregateSpec::count())
1188            .await
1189    }
1190
1191    /// Loads `{relation}_exists` of each relation of `paths`.
1192    pub async fn load_exists<E: Executor + ?Sized>(
1193        &mut self,
1194        exec: &E,
1195        paths: impl IntoIterator<Item = impl RelationPath<M>>,
1196    ) -> Result<()> {
1197        let paths = paths
1198            .into_iter()
1199            .map(|path| path.relation_path().into_owned())
1200            .collect();
1201        self.load_aggregate_paths(exec, paths, AggregateSpec::exists())
1202            .await
1203    }
1204
1205    /// Loads `function` of related `column` of relation `path`.
1206    pub async fn load_aggregate<E: Executor + ?Sized>(
1207        &mut self,
1208        exec: &E,
1209        path: impl RelationPath<M>,
1210        column: impl IntoExpr,
1211        function: AggregateFunction,
1212    ) -> Result<()> {
1213        let spec = AggregateSpec::function(function, column)?;
1214        let paths = vec![path.relation_path().into_owned()];
1215        self.load_aggregate_paths(exec, paths, spec).await
1216    }
1217
1218    /// Loads `{relation}_sum_{column}`.
1219    pub async fn load_sum<E: Executor + ?Sized>(
1220        &mut self,
1221        exec: &E,
1222        path: impl RelationPath<M>,
1223        column: impl IntoExpr,
1224    ) -> Result<()> {
1225        self.load_aggregate(exec, path, column, AggregateFunction::Sum)
1226            .await
1227    }
1228
1229    /// Loads `{relation}_avg_{column}`.
1230    pub async fn load_avg<E: Executor + ?Sized>(
1231        &mut self,
1232        exec: &E,
1233        path: impl RelationPath<M>,
1234        column: impl IntoExpr,
1235    ) -> Result<()> {
1236        self.load_aggregate(exec, path, column, AggregateFunction::Avg)
1237            .await
1238    }
1239
1240    /// Loads `{relation}_min_{column}`.
1241    pub async fn load_min<E: Executor + ?Sized>(
1242        &mut self,
1243        exec: &E,
1244        path: impl RelationPath<M>,
1245        column: impl IntoExpr,
1246    ) -> Result<()> {
1247        self.load_aggregate(exec, path, column, AggregateFunction::Min)
1248            .await
1249    }
1250
1251    /// Loads `{relation}_max_{column}`.
1252    pub async fn load_max<E: Executor + ?Sized>(
1253        &mut self,
1254        exec: &E,
1255        path: impl RelationPath<M>,
1256        column: impl IntoExpr,
1257    ) -> Result<()> {
1258        self.load_aggregate(exec, path, column, AggregateFunction::Max)
1259            .await
1260    }
1261
1262    /// Loads `morph_to` relation `name` where missing, then `with`'s
1263    /// per-model loads into the records it holds (one query per model and
1264    /// relation).
1265    pub async fn load_morph<E: Executor + ?Sized>(
1266        &mut self,
1267        exec: &E,
1268        name: &str,
1269        with: MorphWith,
1270    ) -> Result<()> {
1271        let target = exec.target(Access::Read).await?;
1272        load_morph_on(&target, self, name, &with, None).await
1273    }
1274
1275    /// Loads the counts of the relations `with` lists (with `on` or
1276    /// `count_on`) onto the records `morph_to` relation `name` holds.
1277    pub async fn load_morph_count<E: Executor + ?Sized>(
1278        &mut self,
1279        exec: &E,
1280        name: &str,
1281        with: MorphWith,
1282    ) -> Result<()> {
1283        let target = exec.target(Access::Read).await?;
1284        let spec = AggregateSpec::count();
1285        load_morph_on(&target, self, name, &with, Some(&spec)).await
1286    }
1287
1288    /// Gives the records one automatic-loading group: a relation loaded
1289    /// lazily on one of them loads for all of them (one query).
1290    pub fn with_relationship_autoloading(mut self) -> Self {
1291        group_records(self.iter_mut());
1292        self
1293    }
1294}
1295
1296/// Loads the relations of `paths` that the records of model `M` among
1297/// `records` miss (a `morph_to`'s mixed results); records of other models
1298/// are left alone.
1299///
1300/// ```no_run
1301/// # use navree_orm::__doc_models::*;
1302/// # async fn demo(db: Db, mut notables: Vec<navree_orm::relations::AnyRecord>) -> Result<()> {
1303/// navree_orm::relations::load_missing_chain::<Deal, _>(&db, &mut notables, ["company"]).await?;
1304/// # Ok(()) }
1305/// ```
1306pub async fn load_missing_chain<M: Model, E: Executor + ?Sized>(
1307    exec: &E,
1308    records: &mut [AnyRecord],
1309    paths: impl IntoIterator<Item = impl RelationPath<M>>,
1310) -> Result<()> {
1311    let tree = tree_of::<M>(paths)?;
1312    let indexes: Vec<usize> = records
1313        .iter()
1314        .enumerate()
1315        .filter(|(_, record)| record.is::<M>())
1316        .map(|(index, _)| index)
1317        .collect();
1318    if indexes.is_empty() {
1319        return Ok(());
1320    }
1321    let mut typed: Vec<Record<M>> = Vec::with_capacity(indexes.len());
1322    for index in &indexes {
1323        let placeholder = AnyRecord::new(Record::<M>::stored_placeholder(&records[*index])?);
1324        let record = std::mem::replace(&mut records[*index], placeholder);
1325        match record.downcast::<M>() {
1326            Ok(record) => typed.push(record),
1327            Err(_) => unreachable!("the model type was checked"),
1328        }
1329    }
1330    let target = exec.target(Access::Read).await?;
1331    let result = load_missing_tree(&target, &mut typed, &tree).await;
1332    for (index, record) in indexes.into_iter().zip(typed) {
1333        records[index] = AnyRecord::new(record);
1334    }
1335    result
1336}
1337
1338impl<M: Model> Record<M> {
1339    /// A stand-in for `record` while its model's record is taken out of
1340    /// it: the same record, cloned without relations.
1341    fn stored_placeholder(record: &AnyRecord) -> Result<Record<M>> {
1342        record
1343            .downcast_ref::<M>()
1344            .map(Record::without_relations)
1345            .ok_or_else(|| OrmError::invalid(format!("not a {}", M::meta().name())))
1346    }
1347}
1348
1349/// Loads again the relations `record` has loaded that are relations of
1350/// its model (what `refresh` does after reloading the columns); pivots and
1351/// values set by hand are left as they are.
1352pub(crate) async fn reload_relations<M: Model>(
1353    target: &Target<'_>,
1354    record: &mut Record<M>,
1355) -> Result<()> {
1356    let names: Vec<String> = record
1357        .relations
1358        .names()
1359        .filter(|name| M::relation(name).is_some())
1360        .map(str::to_owned)
1361        .collect();
1362    if names.is_empty() {
1363        return Ok(());
1364    }
1365    let mut tree = EagerTree::default();
1366    for name in &names {
1367        tree.entry(std::slice::from_ref(name));
1368    }
1369    load_tree(target, std::slice::from_mut(record), &tree).await
1370}