1use 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
35pub(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
61pub(crate) struct AutoloadGroup<M: Model> {
65 records: tokio::sync::Mutex<Vec<Record<M>>>,
66}
67
68pub(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 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#[derive(Clone, Debug, PartialEq, Eq)]
117pub struct LazyLoadingViolation {
118 model: &'static str,
119 relation: String,
120}
121
122impl LazyLoadingViolation {
123 pub fn model(&self) -> &'static str {
125 self.model
126 }
127
128 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
144type ViolationHandler = Arc<dyn Fn(&LazyLoadingViolation) -> Result<()> + Send + Sync>;
146
147#[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 pub fn new() -> Self {
197 LazyLoading::default()
198 }
199
200 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 pub fn prevented(mut self) -> Self {
224 self.prevent = true;
225 self
226 }
227
228 pub fn automatic(mut self) -> Self {
231 self.automatic = true;
232 self
233 }
234
235 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 pub fn is_prevented(&self) -> bool {
248 self.prevent
249 }
250
251 pub fn is_automatic(&self) -> bool {
253 self.automatic
254 }
255
256 pub fn install(self) {
258 *installed()
259 .write()
260 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(self);
261 }
262
263 pub async fn scope<F: Future>(self, future: F) -> F::Output {
265 SCOPED.scope(self, future).await
266 }
267
268 pub fn current() -> LazyLoading {
272 LazyLoading::chosen()
273 .unwrap_or_else(|| LazyLoading::from_strictness(crate::strict::current()))
274 }
275
276 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 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 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
322pub(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
337pub(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
351fn 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
365pub(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
414pub(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
443pub(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
471pub(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
482async 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 pub fn relation<T: 'static>(&self, name: &str) -> Option<&T> {
565 self.relations.get::<T>(name)
566 }
567
568 pub fn relation_mut<T: 'static>(&mut self, name: &str) -> Option<&mut T> {
570 self.relations.get_mut::<T>(name)
571 }
572
573 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 pub fn relation_loaded(&self, name: &str) -> bool {
580 self.relations.is_loaded(name)
581 }
582
583 pub fn unset_relation(&mut self, name: &str) {
585 self.relations.unset(name);
586 }
587
588 pub fn set_relations(&mut self, relations: Relations) {
590 self.relations = relations;
591 }
592
593 pub fn unset_relations(&mut self) {
595 self.relations.clear();
596 }
597
598 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn with_relationship_autoloading(mut self) -> Self {
1002 group_records(std::iter::once(&mut self));
1003 self
1004 }
1005
1006 pub fn pivot(&self) -> Option<&Pivot> {
1009 self.relations.get::<Pivot>("pivot")
1010 }
1011
1012 pub fn pivot_as<P: Model>(&self) -> Option<&Record<P>> {
1015 self.relations.get::<Record<P>>("pivot")
1016 }
1017
1018 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
1036pub trait Associate<M: Model, X> {
1038 #[doc(hidden)]
1040 fn associate_with(&self, child: &mut Record<M>, related: &X) -> Result<()>;
1041}
1042
1043pub trait Dissociate<M: Model> {
1045 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn with_relationship_autoloading(mut self) -> Self {
1291 group_records(self.iter_mut());
1292 self
1293 }
1294}
1295
1296pub 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 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
1349pub(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}