Skip to main content

navree_orm/factory/
sources.rs

1//! Where related records come from: [`ParentSource`] (a factory, a lazy
2//! factory or a stored record), [`IntoRecords`] (stored records to recycle
3//! or attach), [`LazyFactory`] and the recycle pool.
4
5use std::any::{Any, TypeId};
6use std::fmt;
7use std::sync::Arc;
8
9use navree_kernel::BoxFuture;
10use tokio::sync::OnceCell;
11
12use crate::collection::Collection;
13use crate::error::{OrmError, Result};
14use crate::exec::{Access, Executor, Target};
15use crate::factory::{Factory, ModelFactory};
16use crate::model::Model;
17use crate::record::Record;
18use crate::value::{Field, Value};
19
20/// Stored records of model `P` a factory can use: one record, several, or
21/// a collection. [`Factory::recycle`](crate::factory::Factory::recycle) and
22/// [`Factory::has_attached`](crate::factory::Factory::has_attached) take
23/// these.
24pub trait IntoRecords<P: Model> {
25    /// The records.
26    fn into_records(self) -> Vec<Record<P>>;
27}
28
29impl<P: Model> IntoRecords<P> for Record<P> {
30    fn into_records(self) -> Vec<Record<P>> {
31        vec![self]
32    }
33}
34
35impl<P: Model> IntoRecords<P> for &Record<P> {
36    fn into_records(self) -> Vec<Record<P>> {
37        vec![self.clone()]
38    }
39}
40
41impl<P: Model> IntoRecords<P> for Collection<P> {
42    fn into_records(self) -> Vec<Record<P>> {
43        self.into_vec()
44    }
45}
46
47impl<P: Model> IntoRecords<P> for &Collection<P> {
48    fn into_records(self) -> Vec<Record<P>> {
49        self.to_vec()
50    }
51}
52
53impl<P: Model> IntoRecords<P> for Vec<Record<P>> {
54    fn into_records(self) -> Vec<Record<P>> {
55        self
56    }
57}
58
59impl<P: Model> IntoRecords<P> for &[Record<P>] {
60    fn into_records(self) -> Vec<Record<P>> {
61        self.to_vec()
62    }
63}
64
65/// Records kept by the factories of one `create` (or `make`) call to use
66/// instead of creating new parents: model type → its records.
67#[derive(Clone, Default)]
68pub(crate) struct Recycle {
69    pools: Vec<(TypeId, &'static str, Arc<dyn Any + Send + Sync>)>,
70}
71
72impl Recycle {
73    /// Adds `records` to the pool of their model.
74    pub(crate) fn add<P: Model>(&mut self, records: Vec<Record<P>>) {
75        if records.is_empty() {
76            return;
77        }
78        let type_id = TypeId::of::<P>();
79        match self.pools.iter_mut().find(|(id, _, _)| *id == type_id) {
80            Some((_, _, pool)) => {
81                let mut merged: Vec<Record<P>> = pool
82                    .downcast_ref::<Vec<Record<P>>>()
83                    .cloned()
84                    .unwrap_or_default();
85                merged.extend(records);
86                *pool = Arc::new(merged);
87            }
88            None => self
89                .pools
90                .push((type_id, P::meta().name(), Arc::new(records))),
91        }
92    }
93
94    /// Adds every pool of `other` (the parent factory's pool reaches its
95    /// nested factories).
96    pub(crate) fn extend(&mut self, other: &Recycle) {
97        for (type_id, name, pool) in &other.pools {
98            if !self.pools.iter().any(|(id, _, _)| id == type_id) {
99                self.pools.push((*type_id, name, pool.clone()));
100            }
101        }
102    }
103
104    /// The recycled records of `P`.
105    pub(crate) fn records<P: Model>(&self) -> Option<&[Record<P>]> {
106        self.pools
107            .iter()
108            .find(|(id, _, _)| *id == TypeId::of::<P>())
109            .and_then(|(_, _, pool)| pool.downcast_ref::<Vec<Record<P>>>())
110            .map(Vec::as_slice)
111            .filter(|records| !records.is_empty())
112    }
113
114    /// One recycled record of `P` chosen with `pick` (a random number).
115    pub(crate) fn pick<P: Model>(&self, pick: u64) -> Option<Record<P>> {
116        let records = self.records::<P>()?;
117        let index = (pick % records.len() as u64) as usize;
118        Some(records[index].clone())
119    }
120
121    /// The names of the recycled models (for `Debug`).
122    fn names(&self) -> Vec<&'static str> {
123        self.pools.iter().map(|(_, name, _)| *name).collect()
124    }
125}
126
127impl fmt::Debug for Recycle {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.debug_list().entries(self.names()).finish()
130    }
131}
132
133/// A parent record for [`Factory::for_`](crate::factory::Factory::for_) and
134/// [`FactoryContext::belongs_to`](crate::factory::FactoryContext::belongs_to):
135/// a [`Factory`] (a parent is created, or recycled), a [`LazyFactory`] (one
136/// parent created on first use and shared), or a stored [`Record`].
137///
138/// Implemented by those types only.
139pub trait ParentSource: Send + Sync + sealed::Sealed {
140    /// The parent's model.
141    type Parent: Model;
142
143    /// The source, type-erased (what factories keep).
144    #[doc(hidden)]
145    fn into_parent(self) -> ParentHandle;
146}
147
148mod sealed {
149    /// Keeps [`ParentSource`](super::ParentSource) to the factory types.
150    pub trait Sealed {}
151}
152
153impl<F: ModelFactory> sealed::Sealed for Factory<F> {}
154impl<F: ModelFactory> sealed::Sealed for LazyFactory<F> {}
155impl<P: Model> sealed::Sealed for Record<P> {}
156impl<P: Model> sealed::Sealed for &Record<P> {}
157
158/// A parent source, type-erased. Not API.
159#[doc(hidden)]
160pub struct ParentHandle(pub(crate) Arc<dyn ResolveParent>);
161
162impl fmt::Debug for ParentHandle {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.debug_tuple("ParentHandle")
165            .field(&self.0.model_name())
166            .finish()
167    }
168}
169
170/// A source of one parent record, type-erased.
171pub(crate) trait ResolveParent: Send + Sync {
172    /// The parent model's name.
173    fn model_name(&self) -> &'static str;
174
175    /// The value of `column` (the key when `None`) of a parent known
176    /// without the database: a stored record, a lazily created one that
177    /// exists, or a recycled one (chosen with `pick`). Factories have none.
178    fn known(&self, column: Option<&str>, recycle: &Recycle, pick: u64) -> Result<Option<Value>>;
179
180    /// The value of `column` (the key when `None`) of the parent, created on
181    /// `target` when needed (unless `expand` is false: then `None`).
182    fn resolve<'a>(
183        &'a self,
184        column: Option<&'a str>,
185        target: &'a Target<'a>,
186        recycle: &'a Recycle,
187        pick: u64,
188        expand: bool,
189    ) -> BoxFuture<'a, Result<Option<Value>>>;
190}
191
192/// The value of `column` (the key when `None`) of `record`.
193fn column_value<P: Model>(record: &Record<P>, column: Option<&str>) -> Result<Value> {
194    match column {
195        None => Ok(record.key().to_value()),
196        Some(column) => record
197            .model()
198            .value(column)?
199            .ok_or_else(|| crate::model::derive_support::unknown_column::<P>(column)),
200    }
201}
202
203impl<F: ModelFactory> ParentSource for Factory<F> {
204    type Parent = F::Model;
205
206    fn into_parent(self) -> ParentHandle {
207        ParentHandle(Arc::new(self))
208    }
209}
210
211impl<F: ModelFactory> ResolveParent for Factory<F> {
212    fn model_name(&self) -> &'static str {
213        F::Model::meta().name()
214    }
215
216    fn known(&self, column: Option<&str>, recycle: &Recycle, pick: u64) -> Result<Option<Value>> {
217        recycle
218            .pick::<F::Model>(pick)
219            .map(|record| column_value(&record, column))
220            .transpose()
221    }
222
223    fn resolve<'a>(
224        &'a self,
225        column: Option<&'a str>,
226        target: &'a Target<'a>,
227        recycle: &'a Recycle,
228        pick: u64,
229        expand: bool,
230    ) -> BoxFuture<'a, Result<Option<Value>>> {
231        Box::pin(async move {
232            if let Some(record) = recycle.pick::<F::Model>(pick) {
233                return column_value(&record, column).map(Some);
234            }
235            if !expand {
236                return Ok(None);
237            }
238            let mut factory = self.clone().count(1);
239            factory.recycle.extend(recycle);
240            let created = factory.create_on(target).await?;
241            let record = created.into_vec().into_iter().next().ok_or_else(|| {
242                OrmError::factory(
243                    F::Model::meta().name(),
244                    "the parent factory created no record",
245                )
246            })?;
247            column_value(&record, column).map(Some)
248        })
249    }
250}
251
252impl<P: Model> ParentSource for Record<P> {
253    type Parent = P;
254
255    fn into_parent(self) -> ParentHandle {
256        ParentHandle(Arc::new(StoredParent(self)))
257    }
258}
259
260impl<P: Model> ParentSource for &Record<P> {
261    type Parent = P;
262
263    fn into_parent(self) -> ParentHandle {
264        ParentHandle(Arc::new(StoredParent(self.clone())))
265    }
266}
267
268/// A stored record as a parent.
269struct StoredParent<P: Model>(Record<P>);
270
271impl<P: Model> ResolveParent for StoredParent<P> {
272    fn model_name(&self) -> &'static str {
273        P::meta().name()
274    }
275
276    fn known(&self, column: Option<&str>, _recycle: &Recycle, _pick: u64) -> Result<Option<Value>> {
277        column_value(&self.0, column).map(Some)
278    }
279
280    fn resolve<'a>(
281        &'a self,
282        column: Option<&'a str>,
283        _target: &'a Target<'a>,
284        _recycle: &'a Recycle,
285        _pick: u64,
286        _expand: bool,
287    ) -> BoxFuture<'a, Result<Option<Value>>> {
288        Box::pin(async move { column_value(&self.0, column).map(Some) })
289    }
290}
291
292/// A factory whose record is created the first time it is needed, then
293/// shared: give one to several definitions or `for_` calls and they all
294/// point at the same parent. Made with [`Factory::lazy`](crate::factory::Factory::lazy).
295///
296/// ```no_run
297/// # use navree_orm::__doc_factories::*;
298/// # async fn demo(db: Db) -> Result<()> {
299/// let agra = Company::factory().set(Company::NAME, "Agra").lazy();
300/// // Three deals, one company (created with the first deal).
301/// let deals = Deal::factory().count(3).for_(agra.clone(), Deal::COMPANY_ID).create(&db).await?;
302/// let company = agra.get(&db).await?;
303/// assert!(deals.iter().all(|deal| deal.company_id == Some(company.id)));
304/// # Ok(()) }
305/// ```
306pub struct LazyFactory<F: ModelFactory> {
307    factory: Factory<F>,
308    record: Arc<OnceCell<Record<F::Model>>>,
309}
310
311impl<F: ModelFactory> LazyFactory<F> {
312    pub(crate) fn new(factory: Factory<F>) -> Self {
313        LazyFactory {
314            factory: factory.count(1),
315            record: Arc::new(OnceCell::new()),
316        }
317    }
318
319    /// The record: created on `exec` by the first call, the same record
320    /// afterwards.
321    pub async fn get<E: Executor + ?Sized>(&self, exec: &E) -> Result<Record<F::Model>> {
322        let target = exec.target(Access::Write).await?;
323        self.get_on(&target, &Recycle::default()).await
324    }
325
326    /// The record, if it was created already.
327    pub fn created(&self) -> Option<&Record<F::Model>> {
328        self.record.get()
329    }
330
331    async fn get_on(&self, target: &Target<'_>, recycle: &Recycle) -> Result<Record<F::Model>> {
332        self.record
333            .get_or_try_init(|| async {
334                let mut factory = self.factory.clone();
335                factory.recycle.extend(recycle);
336                let created = factory.create_on(target).await?;
337                created.into_vec().into_iter().next().ok_or_else(|| {
338                    OrmError::factory(
339                        F::Model::meta().name(),
340                        "the lazy factory created no record",
341                    )
342                })
343            })
344            .await
345            .cloned()
346    }
347}
348
349impl<F: ModelFactory> Clone for LazyFactory<F> {
350    fn clone(&self) -> Self {
351        LazyFactory {
352            factory: self.factory.clone(),
353            record: self.record.clone(),
354        }
355    }
356}
357
358impl<F: ModelFactory> fmt::Debug for LazyFactory<F> {
359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360        f.debug_struct("LazyFactory")
361            .field("model", &F::Model::meta().name())
362            .field("created", &self.record.initialized())
363            .finish()
364    }
365}
366
367impl<F: ModelFactory> ParentSource for LazyFactory<F> {
368    type Parent = F::Model;
369
370    fn into_parent(self) -> ParentHandle {
371        ParentHandle(Arc::new(self))
372    }
373}
374
375impl<F: ModelFactory> ResolveParent for LazyFactory<F> {
376    fn model_name(&self) -> &'static str {
377        F::Model::meta().name()
378    }
379
380    fn known(&self, column: Option<&str>, _recycle: &Recycle, _pick: u64) -> Result<Option<Value>> {
381        self.record
382            .get()
383            .map(|record| column_value(record, column))
384            .transpose()
385    }
386
387    fn resolve<'a>(
388        &'a self,
389        column: Option<&'a str>,
390        target: &'a Target<'a>,
391        recycle: &'a Recycle,
392        _pick: u64,
393        _expand: bool,
394    ) -> BoxFuture<'a, Result<Option<Value>>> {
395        Box::pin(async move {
396            let record = self.get_on(target, recycle).await?;
397            column_value(&record, column).map(Some)
398        })
399    }
400}