Skip to main content

navree_orm/factory/
mod.rs

1//! Model factories: records for tests and seeders, built from a definition
2//! with fake data, states, sequences and relationships.
3//!
4//! A factory implements [`ModelFactory`] for one model; `#[model(factory =
5//! DealFactory)]` links the two, so `Deal::factory()` starts a [`Factory`]
6//! builder:
7//!
8//! ```no_run
9//! # use navree_orm::__doc_factories::*;
10//! # async fn demo(db: Db) -> Result<()> {
11//! // Three won deals of one new company, each with two activities.
12//! let deals = Deal::factory()
13//!     .count(3)
14//!     .state(DealFactory::won)
15//!     .for_(Company::factory().set(Company::NAME, "Agra"), Deal::COMPANY_ID)
16//!     .has(Activity::factory().count(2), Activity::DEAL_ID)
17//!     .create(&db)
18//!     .await?;
19//!
20//! // Unsaved records, no database involved.
21//! let draft = Deal::factory().set(Deal::TITLE, "Draft").make_one()?;
22//! assert!(!draft.exists());
23//! # Ok(()) }
24//! ```
25//!
26//! - **Definitions** build one model from a [`FactoryContext`]: its index in
27//!   the batch, fake data ([`Faker`], seeded with [`Factory::seed`] for
28//!   reproducible runs), the current time and the parents it belongs to
29//!   ([`FactoryContext::belongs_to`]).
30//! - **States** change the model after the definition, in order:
31//!   closures and named functions ([`Factory::state`]), single columns
32//!   ([`Factory::set`]), [`Sequence`]s, soft-deleted records
33//!   ([`Factory::trashed`]).
34//! - **Relationships**: parents shared by the batch ([`Factory::for_`]),
35//!   children of each record ([`Factory::has`]), many-to-many attachments
36//!   ([`Factory::has_attached`]), stored records reused instead of new
37//!   parents ([`Factory::recycle`]), by typed columns or by the names a
38//!   factory declares in [`ModelFactory::relationships`].
39//! - **Results**: unsaved records ([`Factory::make`]), generated values only
40//!   ([`Factory::raw`]), stored records with their relationships
41//!   ([`Factory::create`], with model events or quietly), or one bulk
42//!   `INSERT` ([`Factory::insert`]); hooks run after making and after
43//!   creating.
44//!
45//! Records are created through the executor given (a `Db`, a `Uow`, ...),
46//! so they join the unit of work, record change events and fill the
47//! current workspace like any other save.
48
49mod bulk;
50mod context;
51mod faker;
52pub(crate) mod quiet;
53mod relationships;
54mod sequence;
55mod sources;
56
57use std::borrow::Cow;
58use std::fmt;
59use std::sync::Arc;
60
61use chrono::{DateTime, Duration, Utc};
62use navree_db::Db;
63use navree_kernel::BoxFuture;
64
65pub use context::{Attributes, FactoryContext};
66pub use faker::{FakeNumber, Faker};
67pub use relationships::{BelongsTo, HasMany, Pivot, RelationshipInfo, Relationships};
68pub use sequence::{Sequence, SequenceIndex};
69pub use sources::{IntoRecords, LazyFactory, ParentHandle, ParentSource};
70
71use crate::collection::Collection;
72use crate::column::{Assignment, Column};
73use crate::error::{OrmError, Result};
74use crate::exec::{Access, Executor, Target, truncate_to_micros};
75use crate::model::{Model, PrimaryKey};
76use crate::persist;
77use crate::record::Record;
78use crate::value::{Value, ValueFor};
79
80use self::context::PendingParent;
81use self::relationships::{AttachRelated, Attachable, ChildLink, HasChildren};
82use self::sources::{Recycle, ResolveParent};
83
84/// A factory of one model: its default state, plus optional defaults for
85/// every builder ([`configure`](ModelFactory::configure)) and the
86/// relationships builders can name ([`relationships`](ModelFactory::relationships)).
87///
88/// ```
89/// use chrono::{DateTime, Utc};
90/// use navree_orm::factory::{Factory, FactoryContext, ModelFactory};
91/// use navree_orm::prelude::*;
92///
93/// #[derive(Model, Clone, Debug, Default, serde::Serialize)]
94/// #[model(timestamps, factory = TaskFactory)]
95/// pub struct Task {
96///     id: i64,
97///     title: String,
98///     done: bool,
99///     created_at: DateTime<Utc>,
100///     updated_at: DateTime<Utc>,
101/// }
102///
103/// #[derive(Default)]
104/// pub struct TaskFactory;
105///
106/// impl ModelFactory for TaskFactory {
107///     type Model = Task;
108///
109///     fn definition(&self, ctx: &mut FactoryContext<'_, Task>) -> Task {
110///         Task { title: ctx.fake().sentence(), ..Task::default() }
111///     }
112/// }
113///
114/// impl TaskFactory {
115///     /// A named state: `Task::factory().state(TaskFactory::done)`.
116///     pub fn done(task: &mut Task) {
117///         task.done = true;
118///     }
119/// }
120///
121/// let tasks = Task::factory().count(2).state(TaskFactory::done).make()?;
122/// assert!(tasks.iter().all(|task| task.done && !task.title.is_empty()));
123/// # Ok::<(), navree_orm::OrmError>(())
124/// ```
125pub trait ModelFactory: Send + Sync + Sized + 'static {
126    /// The model this factory builds.
127    type Model: Model;
128
129    /// The model's default state: one new model, usually with fake data
130    /// from `ctx.fake()`. Keys and timestamps left empty are filled when the
131    /// record is saved.
132    fn definition(&self, ctx: &mut FactoryContext<'_, Self::Model>) -> Self::Model;
133
134    /// Defaults for every builder of this factory (`Model::factory()`,
135    /// [`Factory::of`]): hooks, states. Returns the builder unchanged by
136    /// default.
137    fn configure(factory: Factory<Self>) -> Factory<Self> {
138        factory
139    }
140
141    /// The relationships of the model that builders may name in
142    /// [`Factory::has`], [`Factory::for_`] and [`Factory::has_attached`]
143    /// (`.has(Activity::factory(), "activities")`). None by default; typed
144    /// columns work without declaring anything.
145    fn relationships(relationships: &mut Relationships<Self::Model>) {
146        let _ = relationships;
147    }
148}
149
150/// A model with a factory, linked by `#[model(factory = DealFactory)]`,
151/// which also gives the model an inherent `factory()`.
152pub trait HasFactory: Model {
153    /// The model's factory.
154    type Factory: ModelFactory<Model = Self> + Default;
155
156    /// A builder of the model's factory.
157    fn factory() -> Factory<Self::Factory> {
158        Factory::new()
159    }
160}
161
162/// Defaults for the factories of an app: register a value with
163/// `override_value(Arc::new(FactoryOptions { .. }))` (or a provider), and
164/// factories creating records through an executor of that app read it.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166#[non_exhaustive]
167pub struct FactoryOptions {
168    /// Whether `create` makes the parents that definitions declare with
169    /// [`FactoryContext::belongs_to`] (default `true`;
170    /// [`Factory::without_parents`] turns it off for one builder).
171    pub expand_relationships: bool,
172    /// The seed of every factory that has none of its own, for runs that
173    /// generate the same data every time (default `None`: random).
174    pub seed: Option<u64>,
175}
176
177impl FactoryOptions {
178    /// The defaults: parents are created, seeds are random.
179    pub const fn new() -> Self {
180        FactoryOptions {
181            expand_relationships: true,
182            seed: None,
183        }
184    }
185
186    /// Whether definitions' parents are created.
187    pub const fn expand_relationships(mut self, expand: bool) -> Self {
188        self.expand_relationships = expand;
189        self
190    }
191
192    /// The default seed.
193    pub const fn seed(mut self, seed: u64) -> Self {
194        self.seed = Some(seed);
195        self
196    }
197}
198
199impl Default for FactoryOptions {
200    fn default() -> Self {
201        FactoryOptions::new()
202    }
203}
204
205/// A state: changes a model after its definition.
206type StateFn<M> =
207    Arc<dyn Fn(&mut M, &mut FactoryContext<'_, M>) -> Result<()> + Send + Sync + 'static>;
208
209/// A hook after a record is made.
210type AfterMaking<M> = Arc<dyn Fn(&mut Record<M>) + Send + Sync + 'static>;
211
212/// A hook after a record is created.
213type AfterCreating<M> = Arc<
214    dyn for<'a> Fn(&'a mut Record<M>, &'a Target<'a>) -> BoxFuture<'a, Result<()>>
215        + Send
216        + Sync
217        + 'static,
218>;
219
220/// A parent of the whole batch (`for_`): where it comes from and how
221/// records point at it.
222struct ParentLink {
223    source: Arc<dyn ResolveParent>,
224    owner_key: Option<Cow<'static, str>>,
225    foreign_key: Cow<'static, str>,
226    morph: Option<(Cow<'static, str>, Cow<'static, str>)>,
227}
228
229impl Clone for ParentLink {
230    fn clone(&self) -> Self {
231        ParentLink {
232            source: self.source.clone(),
233            owner_key: self.owner_key.clone(),
234            foreign_key: self.foreign_key.clone(),
235            morph: self.morph.clone(),
236        }
237    }
238}
239
240impl ParentLink {
241    /// The column values pointing a record at the parent whose key (or
242    /// owner key) is `value`.
243    fn assignments(&self, value: Value) -> Vec<(Cow<'static, str>, Value)> {
244        let mut values = vec![(self.foreign_key.clone(), value)];
245        if let Some((column, morph_type)) = &self.morph {
246            values.push((column.clone(), Value::from(morph_type.to_string())));
247        }
248        values
249    }
250}
251
252/// Builds records of `F::Model` with factory `F`: start one with
253/// `Model::factory()` (or [`Factory::new`] / [`Factory::of`]), chain
254/// counts, states, sequences and relationships, then
255/// [`make`](Factory::make), [`create`](Factory::create),
256/// [`raw`](Factory::raw) or [`insert`](Factory::insert).
257///
258/// Builders are values: every method returns a new builder, and a builder
259/// can be cloned and reused.
260pub struct Factory<F: ModelFactory> {
261    factory: Arc<F>,
262    count: Option<usize>,
263    states: Vec<StateFn<F::Model>>,
264    parents: Vec<ParentLink>,
265    children: Vec<Arc<dyn ChildLink<F::Model>>>,
266    pub(crate) recycle: Recycle,
267    after_making: Vec<AfterMaking<F::Model>>,
268    after_creating: Vec<AfterCreating<F::Model>>,
269    expand_parents: Option<bool>,
270    excluded_parents: Vec<Cow<'static, str>>,
271    connection: Option<Cow<'static, str>>,
272    seed: Option<u64>,
273    errors: Vec<String>,
274}
275
276impl<F: ModelFactory + Default> Factory<F> {
277    /// A builder of `F::default()`, configured by [`ModelFactory::configure`]
278    /// (what `Model::factory()` returns).
279    pub fn new() -> Self {
280        Factory::of(F::default())
281    }
282}
283
284impl<F: ModelFactory + Default> Default for Factory<F> {
285    fn default() -> Self {
286        Factory::new()
287    }
288}
289
290impl<F: ModelFactory> Factory<F> {
291    /// A builder of `factory` (a factory with fields of its own),
292    /// configured by [`ModelFactory::configure`].
293    pub fn of(factory: F) -> Self {
294        F::configure(Factory {
295            factory: Arc::new(factory),
296            count: None,
297            states: Vec::new(),
298            parents: Vec::new(),
299            children: Vec::new(),
300            recycle: Recycle::default(),
301            after_making: Vec::new(),
302            after_creating: Vec::new(),
303            expand_parents: None,
304            excluded_parents: Vec::new(),
305            connection: None,
306            seed: None,
307            errors: Vec::new(),
308        })
309    }
310
311    /// The factory.
312    pub fn definition(&self) -> &F {
313        &self.factory
314    }
315
316    // ---------------------------------------------------------------------
317    // How many, and how
318    // ---------------------------------------------------------------------
319
320    /// Builds `count` records (one by default).
321    pub fn count(mut self, count: usize) -> Self {
322        self.count = Some(count);
323        self
324    }
325
326    /// Changes each model after its definition (and the states before
327    /// this one): a closure or a named function of the factory.
328    ///
329    /// ```
330    /// # use navree_orm::__doc_factories::*;
331    /// let won = Deal::factory().state(DealFactory::won).state(|d| d.amount_cents = 50_000).make_one()?;
332    /// assert_eq!((won.stage, won.amount_cents), (Stage::Won, 50_000));
333    /// # Ok::<(), navree_orm::OrmError>(())
334    /// ```
335    pub fn state(self, state: impl Fn(&mut F::Model) + Send + Sync + 'static) -> Self {
336        self.push_state(move |model, _| {
337            state(model);
338            Ok(())
339        })
340    }
341
342    /// Like [`state`](Factory::state), with the [`FactoryContext`]: the
343    /// record's index, fake data, the time, parents.
344    pub fn state_with(
345        self,
346        state: impl Fn(&mut F::Model, &mut FactoryContext<'_, F::Model>) + Send + Sync + 'static,
347    ) -> Self {
348        self.push_state(move |model, ctx| {
349            state(model, ctx);
350            Ok(())
351        })
352    }
353
354    /// A state applied before every state added so far (right after the
355    /// definition).
356    pub fn prepend_state(mut self, state: impl Fn(&mut F::Model) + Send + Sync + 'static) -> Self {
357        self.states.insert(
358            0,
359            Arc::new(move |model, _| {
360                state(model);
361                Ok(())
362            }),
363        );
364        self
365    }
366
367    /// Sets `column` to `value` on every record.
368    pub fn set<T>(self, column: Column<F::Model, T>, value: impl ValueFor<T>) -> Self {
369        let assignment = column.set(value);
370        self.push_state(move |model, _| apply_assignment::<F::Model>(model, &assignment))
371    }
372
373    /// Records take the states of `sequence` in turn: the first record the
374    /// first state, and so on, starting over after the last. Fixed states
375    /// can be given as an array of functions (or closures without
376    /// captures).
377    ///
378    /// ```
379    /// # use navree_orm::__doc_factories::*;
380    /// use navree_orm::factory::Sequence;
381    ///
382    /// let deals = Deal::factory()
383    ///     .count(3)
384    ///     .sequence([DealFactory::won, DealFactory::lost])
385    ///     .sequence(Sequence::column(Deal::TITLE, ["A", "B", "C"]))
386    ///     .make()?;
387    /// let stages: Vec<Stage> = deals.iter().map(|d| d.stage).collect();
388    /// assert_eq!(stages, [Stage::Won, Stage::Lost, Stage::Won]);
389    /// assert_eq!(deals[2].title, "C");
390    /// # Ok::<(), navree_orm::OrmError>(())
391    /// ```
392    pub fn sequence(self, sequence: impl Into<Sequence<F::Model>>) -> Self {
393        let sequence = sequence.into();
394        self.push_state(move |model, ctx| sequence.apply(model, ctx.index()))
395    }
396
397    /// A [`sequence`](Factory::sequence) that also sets the count to its
398    /// length: one record per state.
399    pub fn for_each_sequence(self, sequence: impl Into<Sequence<F::Model>>) -> Self {
400        let sequence = sequence.into();
401        let count = sequence.len();
402        self.sequence(sequence).count(count)
403    }
404
405    /// Records take every combination of one state from each of
406    /// `sequences` in turn (see [`Sequence::cross_join`]); with no count
407    /// set, one record per combination.
408    pub fn cross_join_sequence(
409        self,
410        sequences: impl IntoIterator<Item = Sequence<F::Model>>,
411    ) -> Self {
412        let joined = Sequence::cross_join(sequences);
413        let count = joined.len();
414        let factory = self.sequence(joined);
415        match factory.count {
416            Some(_) => factory,
417            None => factory.count(count),
418        }
419    }
420
421    /// Soft-deleted records: the deleted-at column is set to a day before
422    /// now. Fails when the model does not soft-delete.
423    pub fn trashed(self) -> Self {
424        self.trashed_with(None)
425    }
426
427    /// Soft-deleted records, deleted at `at`.
428    pub fn trashed_at(self, at: DateTime<Utc>) -> Self {
429        self.trashed_with(Some(at))
430    }
431
432    fn trashed_with(self, at: Option<DateTime<Utc>>) -> Self {
433        let meta = F::Model::meta();
434        let Some(column) = meta.deleted_at() else {
435            let name = meta.name();
436            return self.with_error(format!(
437                "{name} does not soft-delete: trashed() needs #[model(soft_deletes)] on {name}"
438            ));
439        };
440        self.push_state(move |model, ctx| {
441            let at = at.unwrap_or_else(|| ctx.now() - Duration::days(1));
442            model.touch_timestamp(column, at)
443        })
444    }
445
446    /// Applies `then` when `condition` holds.
447    pub fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
448        if condition { then(self) } else { self }
449    }
450
451    /// The seed of the fake data, so every run builds the same records
452    /// (unseeded factories use a random seed per call).
453    pub fn seed(mut self, seed: u64) -> Self {
454        self.seed = Some(seed);
455        self
456    }
457
458    /// Creates the records on the app's database connection `name` (a
459    /// named `Db` provider of the executor's app) instead of the executor
460    /// given to `create`.
461    pub fn connection(mut self, name: impl Into<Cow<'static, str>>) -> Self {
462        self.connection = Some(name.into());
463        self
464    }
465
466    // ---------------------------------------------------------------------
467    // Hooks
468    // ---------------------------------------------------------------------
469
470    /// Runs `hook` on each record once it is made (by `make` and by
471    /// `create`, before saving).
472    pub fn after_making(
473        mut self,
474        hook: impl Fn(&mut Record<F::Model>) + Send + Sync + 'static,
475    ) -> Self {
476        self.after_making.push(Arc::new(hook));
477        self
478    }
479
480    /// Runs `hook` on each record once it is created, with the executor it
481    /// was created on (to create related records in the same transaction).
482    ///
483    /// ```no_run
484    /// # use navree_orm::__doc_factories::*;
485    /// # async fn demo(db: Db) -> Result<()> {
486    /// let deals = Deal::factory()
487    ///     .after_creating(|deal, exec| Box::pin(async move {
488    ///         Activity::factory().set(Activity::DEAL_ID, deal.id).create(exec).await?;
489    ///         Ok(())
490    ///     }))
491    ///     .create(&db)
492    ///     .await?;
493    /// # Ok(()) }
494    /// ```
495    pub fn after_creating(
496        mut self,
497        hook: impl for<'a> Fn(&'a mut Record<F::Model>, &'a Target<'a>) -> BoxFuture<'a, Result<()>>
498        + Send
499        + Sync
500        + 'static,
501    ) -> Self {
502        self.after_creating.push(Arc::new(hook));
503        self
504    }
505
506    /// Drops the after-making hooks (also those `configure` added).
507    pub fn without_after_making(mut self) -> Self {
508        self.after_making.clear();
509        self
510    }
511
512    /// Drops the after-creating hooks (also those `configure` added).
513    pub fn without_after_creating(mut self) -> Self {
514        self.after_creating.clear();
515        self
516    }
517
518    // ---------------------------------------------------------------------
519    // Relationships
520    // ---------------------------------------------------------------------
521
522    /// Points every record at one parent from `parent` through `link`: a
523    /// factory (one parent is created for the whole batch, or a recycled
524    /// record is used), a [`LazyFactory`], or a stored record. `link` is the
525    /// foreign key column of this model, a [`BelongsTo`], or the name of a
526    /// relationship the factory declares.
527    ///
528    /// The parent's columns are set before the states, so a state can
529    /// still change them.
530    pub fn for_<S: ParentSource>(
531        self,
532        parent: S,
533        link: impl Into<BelongsTo<F::Model, S::Parent>>,
534    ) -> Self {
535        let link = link.into();
536        let link = match link.named {
537            Some(name) => {
538                match Relationships::<F::Model>::of::<F>().belongs_to_link::<S::Parent>(name) {
539                    Ok(link) => link,
540                    Err(error) => return self.with_error(problem(error)),
541                }
542            }
543            None => link,
544        };
545        let mut factory = self;
546        factory.parents.push(ParentLink {
547            source: parent.into_parent().0,
548            owner_key: link.owner_key.clone(),
549            foreign_key: link.foreign_key.clone(),
550            morph: link.morph.clone(),
551        });
552        factory
553    }
554
555    /// [`for_`](Factory::for_) with a stored record.
556    pub fn for_record<P: Model>(
557        self,
558        parent: &Record<P>,
559        link: impl Into<BelongsTo<F::Model, P>>,
560    ) -> Self {
561        self.for_(parent, link)
562    }
563
564    /// Creates `children` for each record once it is stored, pointing at it
565    /// through `link`: the child's foreign key column, a [`HasMany`], or
566    /// the name of a relationship the factory declares.
567    pub fn has<CF: ModelFactory>(
568        self,
569        children: Factory<CF>,
570        link: impl Into<HasMany<F::Model, CF::Model>>,
571    ) -> Self {
572        let link = link.into();
573        let link = match link.named {
574            Some(name) => {
575                match Relationships::<F::Model>::of::<F>().has_many_link::<CF::Model>(name) {
576                    Ok(link) => link,
577                    Err(error) => return self.with_error(problem(error)),
578                }
579            }
580            None => link,
581        };
582        let mut factory = self;
583        factory.children.push(Arc::new(HasChildren {
584            factory: children,
585            link,
586        }));
587        factory
588    }
589
590    /// Attaches records of `R` to each record once it is stored, through
591    /// the pivot table of `pivot` (a [`Pivot`] or the name of a
592    /// relationship the factory declares), with `values` in every pivot
593    /// row. `related` is a factory (its records are created for each
594    /// record) or stored records (attached to every record).
595    ///
596    /// ```no_run
597    /// # use navree_orm::__doc_factories::*;
598    /// # async fn demo(db: Db, vip: Record<Tag>) -> Result<()> {
599    /// let deals = Deal::factory()
600    ///     .has_attached(Tag::factory().count(2), [("source", Value::from("import"))], "tags")
601    ///     .has_attached(&vip, [], "tags")
602    ///     .create(&db)
603    ///     .await?;
604    /// # Ok(()) }
605    /// ```
606    pub fn has_attached<R: Model>(
607        self,
608        related: impl Into<Attach<R>>,
609        values: impl IntoIterator<Item = (&'static str, Value)>,
610        pivot: impl Into<Pivot<F::Model, R>>,
611    ) -> Self {
612        let pivot = pivot.into();
613        let pivot = match pivot.named {
614            Some(name) => match Relationships::<F::Model>::of::<F>().pivot_link::<R>(name) {
615                Ok(pivot) => pivot,
616                Err(error) => return self.with_error(problem(error)),
617            },
618            None => pivot,
619        };
620        let values = values
621            .into_iter()
622            .map(|(column, value)| (Cow::Borrowed(column), value))
623            .collect();
624        let mut factory = self;
625        factory.children.push(Arc::new(AttachRelated {
626            related: related.into().0,
627            pivot,
628            values,
629        }));
630        factory
631    }
632
633    /// Uses `records` wherever this builder (or a factory nested in it)
634    /// needs a parent of their model, instead of creating one: a random
635    /// one per record for the parents definitions declare, one per batch
636    /// for [`for_`](Factory::for_). Call it once per model.
637    pub fn recycle<P: Model>(mut self, records: impl IntoRecords<P>) -> Self {
638        self.recycle.add(records.into_records());
639        self
640    }
641
642    /// The parents definitions declare with
643    /// [`FactoryContext::belongs_to`] are not created: their columns keep
644    /// the empty value (recycled records are still used).
645    pub fn without_parents(mut self) -> Self {
646        self.expand_parents = Some(false);
647        self
648    }
649
650    /// Like [`without_parents`](Factory::without_parents), for the parent
651    /// declared on `column` only.
652    pub fn without_parent<T>(mut self, column: Column<F::Model, T>) -> Self {
653        use crate::column::ColumnName;
654        self.excluded_parents
655            .push(Cow::Owned(column.column_name().into_owned()));
656        self
657    }
658
659    /// A [`LazyFactory`]: one record, created the first time something
660    /// needs it, then shared.
661    pub fn lazy(self) -> LazyFactory<F> {
662        LazyFactory::new(self)
663    }
664
665    // ---------------------------------------------------------------------
666    // Building without the database
667    // ---------------------------------------------------------------------
668
669    /// Builds the records without storing them: definition, states, the
670    /// parents known without the database (stored or recycled records),
671    /// then the after-making hooks.
672    pub fn make(self) -> Result<Collection<F::Model>> {
673        let now = truncate_to_micros(Utc::now());
674        let mut faker = self.faker(FactoryOptions::default());
675        let parent_values = self.known_parent_values(&mut faker)?;
676        let count = self.count.unwrap_or(1);
677        let mut records = Vec::with_capacity(count);
678        for index in 0..count {
679            let (mut model, pending) = self.build(index, count, now, &mut faker, &parent_values)?;
680            for parent in &pending {
681                if parent.is_open(&model)? {
682                    let pick = faker.next_u64();
683                    if let Some(value) = parent.source.known(None, &self.recycle, pick)? {
684                        model.set_value(&parent.column, value)?;
685                    }
686                }
687            }
688            records.push(Record::new(model));
689        }
690        self.run_after_making(&mut records);
691        Ok(Collection::from(records))
692    }
693
694    /// One record, without storing it.
695    pub fn make_one(self) -> Result<Record<F::Model>> {
696        self.count(1)
697            .make()?
698            .into_vec()
699            .pop()
700            .ok_or_else(|| OrmError::factory(F::Model::meta().name(), "the factory made no record"))
701    }
702
703    /// `count` records, without storing them.
704    pub fn make_many(self, count: usize) -> Result<Collection<F::Model>> {
705        self.count(count).make()
706    }
707
708    /// The values the definition and the states generate for each record,
709    /// by column, without an empty key or empty timestamps (request bodies,
710    /// comparisons). Parents are filled as [`make`](Factory::make) fills
711    /// them.
712    pub fn raw(self) -> Result<Vec<Attributes>> {
713        let meta = F::Model::meta();
714        let timestamps: Vec<&str> = [meta.created_at(), meta.updated_at(), meta.deleted_at()]
715            .into_iter()
716            .flatten()
717            .collect();
718        self.without_after_making()
719            .make()?
720            .iter()
721            .map(|record| {
722                let model = record.model();
723                let values = model
724                    .values()?
725                    .into_iter()
726                    .filter(|(column, _)| {
727                        if *column == meta.key_column() {
728                            return !model.key().is_empty();
729                        }
730                        !(timestamps.contains(column) && model.timestamp_is_empty(column))
731                    })
732                    .collect::<Vec<_>>();
733                Ok(Attributes::from(values))
734            })
735            .collect()
736    }
737
738    /// The values of one record (see [`raw`](Factory::raw)).
739    pub fn raw_one(self) -> Result<Attributes> {
740        self.count(1)
741            .raw()?
742            .pop()
743            .ok_or_else(|| OrmError::factory(F::Model::meta().name(), "the factory made no record"))
744    }
745
746    // ---------------------------------------------------------------------
747    // Creating
748    // ---------------------------------------------------------------------
749
750    /// Creates the records through `exec`: parents first (shared ones for
751    /// `for_`, one per record for definitions), then each record is saved
752    /// (model events, change events, generated keys and timestamps) with
753    /// its children and attachments, then the after-creating hooks run.
754    pub async fn create<E: Executor + ?Sized>(self, exec: &E) -> Result<Collection<F::Model>> {
755        let target = exec.target(Access::Write).await?;
756        match self.connection.clone() {
757            Some(name) => {
758                let db = named_connection(&target, &name).await?;
759                let named = db.target(Access::Write).await?;
760                self.create_on(&named).await
761            }
762            None => self.create_on(&target).await,
763        }
764    }
765
766    /// One record, created.
767    pub async fn create_one<E: Executor + ?Sized>(self, exec: &E) -> Result<Record<F::Model>> {
768        self.count(1)
769            .create(exec)
770            .await?
771            .into_vec()
772            .pop()
773            .ok_or_else(|| {
774                OrmError::factory(F::Model::meta().name(), "the factory created no record")
775            })
776    }
777
778    /// `count` records, created.
779    pub async fn create_many<E: Executor + ?Sized>(
780        self,
781        exec: &E,
782        count: usize,
783    ) -> Result<Collection<F::Model>> {
784        self.count(count).create(exec).await
785    }
786
787    /// [`create`](Factory::create) without model events: the app's model
788    /// hooks (observers) do not run; the model's own behaviour (generated
789    /// keys, timestamps, workspace) and the change events of the audit log
790    /// still do.
791    pub async fn create_quietly<E: Executor + ?Sized>(
792        self,
793        exec: &E,
794    ) -> Result<Collection<F::Model>> {
795        self::quiet::scope(self.create(exec)).await
796    }
797
798    /// One record, created quietly.
799    pub async fn create_one_quietly<E: Executor + ?Sized>(
800        self,
801        exec: &E,
802    ) -> Result<Record<F::Model>> {
803        self::quiet::scope(self.create_one(exec)).await
804    }
805
806    /// `count` records, created quietly.
807    pub async fn create_many_quietly<E: Executor + ?Sized>(
808        self,
809        exec: &E,
810        count: usize,
811    ) -> Result<Collection<F::Model>> {
812        self::quiet::scope(self.create_many(exec, count)).await
813    }
814
815    /// Inserts the records in one `INSERT` statement: no model events, no
816    /// change events, no relationships (stored and recycled parents still
817    /// fill their columns; nothing else is created). Keys and timestamps
818    /// are generated as a save would. Returns how many rows were inserted.
819    pub async fn insert<E: Executor + ?Sized>(self, exec: &E) -> Result<u64> {
820        let target = exec.target(Access::Write).await?;
821        let ctx = target.context();
822        let now = ctx.now().await;
823        let options = factory_options(&ctx).await;
824        let mut faker = self.faker(options);
825        let parent_values = self.known_parent_values(&mut faker)?;
826        let count = self.count.unwrap_or(1);
827        let mut models = Vec::with_capacity(count);
828        for index in 0..count {
829            let (mut model, pending) = self.build(index, count, now, &mut faker, &parent_values)?;
830            for parent in &pending {
831                if parent.is_open(&model)? {
832                    let pick = faker.next_u64();
833                    if let Some(value) = parent.source.known(None, &self.recycle, pick)? {
834                        model.set_value(&parent.column, value)?;
835                    }
836                }
837            }
838            models.push(Record::new(model));
839        }
840        self.run_after_making(&mut models);
841        bulk::insert_models(
842            &target,
843            models.into_iter().map(Record::into_inner).collect(),
844            now,
845        )
846        .await
847    }
848
849    /// [`create`](Factory::create) on a resolved target.
850    pub(crate) async fn create_on(self, target: &Target<'_>) -> Result<Collection<F::Model>> {
851        self.check()?;
852        let ctx = target.context();
853        let now = ctx.now().await;
854        let options = factory_options(&ctx).await;
855        let expand = self.expand_parents.unwrap_or(options.expand_relationships);
856        let mut faker = self.faker(options);
857        let count = self.count.unwrap_or(1);
858
859        // The batch's parents, once.
860        let mut parent_values = Vec::new();
861        for link in &self.parents {
862            let pick = faker.next_u64();
863            let value = link
864                .source
865                .resolve(link.owner_key.as_deref(), target, &self.recycle, pick, true)
866                .await?
867                .ok_or_else(|| {
868                    OrmError::factory(
869                        F::Model::meta().name(),
870                        format!(
871                            "no {} record to point `{}` at",
872                            link.source.model_name(),
873                            link.foreign_key
874                        ),
875                    )
876                })?;
877            parent_values.extend(link.assignments(value));
878        }
879
880        // Make every record, with the parents its definition declares.
881        let mut records = Vec::with_capacity(count);
882        for index in 0..count {
883            let (mut model, pending) = self.build(index, count, now, &mut faker, &parent_values)?;
884            for parent in &pending {
885                if !parent.is_open(&model)? {
886                    continue;
887                }
888                let excluded = self.excluded_parents.contains(&parent.column);
889                let pick = faker.next_u64();
890                let value = parent
891                    .source
892                    .resolve(None, target, &self.recycle, pick, expand && !excluded)
893                    .await?;
894                if let Some(value) = value {
895                    model.set_value(&parent.column, value)?;
896                }
897            }
898            records.push(Record::new(model));
899        }
900        self.run_after_making(&mut records);
901
902        // Store them with their children, then the after-creating hooks.
903        for record in &mut records {
904            if !persist::save(target, record).await? {
905                return Err(OrmError::factory(
906                    F::Model::meta().name(),
907                    "a model hook cancelled saving a factory record",
908                ));
909            }
910            for child in &self.children {
911                child.create_for(record, target, &self.recycle).await?;
912            }
913        }
914        for record in &mut records {
915            for hook in &self.after_creating {
916                hook(record, target).await?;
917            }
918        }
919        Ok(Collection::from(records))
920    }
921
922    // ---------------------------------------------------------------------
923    // Internals
924    // ---------------------------------------------------------------------
925
926    fn push_state(
927        mut self,
928        state: impl Fn(&mut F::Model, &mut FactoryContext<'_, F::Model>) -> Result<()>
929        + Send
930        + Sync
931        + 'static,
932    ) -> Self {
933        self.states.push(Arc::new(state));
934        self
935    }
936
937    /// A state setting columns to fixed values (the foreign keys of `has`).
938    pub(crate) fn state_values(self, values: Vec<(Cow<'static, str>, Value)>) -> Self {
939        self.push_state(move |model, _| {
940            for (column, value) in &values {
941                model.set_value(column, value.clone())?;
942            }
943            Ok(())
944        })
945    }
946
947    /// Records a problem found while building; the factory fails with it
948    /// when it makes or creates records.
949    fn with_error(mut self, message: String) -> Self {
950        self.errors.push(message);
951        self
952    }
953
954    fn check(&self) -> Result<()> {
955        match self.errors.first() {
956            Some(message) => Err(OrmError::factory(F::Model::meta().name(), message.clone())),
957            None => Ok(()),
958        }
959    }
960
961    fn faker(&self, options: FactoryOptions) -> Faker {
962        match self.seed.or(options.seed) {
963            Some(seed) => Faker::seeded(seed),
964            None => Faker::new(),
965        }
966    }
967
968    /// The values of the batch's parents known without the database, for
969    /// `make` and `insert` (a parent from a factory that is not recycled
970    /// sets nothing).
971    fn known_parent_values(&self, faker: &mut Faker) -> Result<Vec<(Cow<'static, str>, Value)>> {
972        self.check()?;
973        let mut values = Vec::new();
974        for link in &self.parents {
975            let pick = faker.next_u64();
976            if let Some(value) =
977                link.source
978                    .known(link.owner_key.as_deref(), &self.recycle, pick)?
979            {
980                values.extend(link.assignments(value));
981            }
982        }
983        Ok(values)
984    }
985
986    /// One model: the definition, the batch's parents, then the states.
987    fn build(
988        &self,
989        index: usize,
990        count: usize,
991        now: DateTime<Utc>,
992        faker: &mut Faker,
993        parent_values: &[(Cow<'static, str>, Value)],
994    ) -> Result<(F::Model, Vec<PendingParent>)> {
995        let mut pending = Vec::new();
996        let mut ctx = FactoryContext::new(index, count, now, faker, &mut pending);
997        let mut model = self.factory.definition(&mut ctx);
998        for (column, value) in parent_values {
999            model.set_value(column, value.clone())?;
1000        }
1001        for state in &self.states {
1002            state(&mut model, &mut ctx)?;
1003        }
1004        Ok((model, pending))
1005    }
1006
1007    fn run_after_making(&self, records: &mut [Record<F::Model>]) {
1008        for record in records {
1009            for hook in &self.after_making {
1010                hook(record);
1011            }
1012        }
1013    }
1014}
1015
1016/// The message of a problem found while building (a factory error's own
1017/// message, so it is not wrapped twice).
1018fn problem(error: OrmError) -> String {
1019    match error {
1020        OrmError::Factory { message, .. } => message,
1021        other => other.to_string(),
1022    }
1023}
1024
1025/// Sets `assignment` on `model`.
1026fn apply_assignment<M: Model>(model: &mut M, assignment: &Assignment) -> Result<()> {
1027    match assignment.assigned_value() {
1028        Some(value) => model.set_value(assignment.column(), value.clone()),
1029        None => {
1030            let message = assignment
1031                .clone()
1032                .into_set()
1033                .err()
1034                .unwrap_or_else(|| format!("`{}` must be set to a value", assignment.column()));
1035            Err(OrmError::factory(M::meta().name(), message))
1036        }
1037    }
1038}
1039
1040/// The app's [`FactoryOptions`], or the defaults.
1041async fn factory_options(ctx: &crate::exec::ExecContext) -> FactoryOptions {
1042    match ctx.app() {
1043        Some(app) => app
1044            .try_get::<FactoryOptions>()
1045            .await
1046            .map(|options| *options)
1047            .unwrap_or_default(),
1048        None => FactoryOptions::default(),
1049    }
1050}
1051
1052/// The app's database connection `name` (a named `Db` provider).
1053async fn named_connection(target: &Target<'_>, name: &str) -> Result<Arc<Db>> {
1054    let ctx = target.context();
1055    let app = ctx.app().ok_or_else(|| {
1056        OrmError::invalid(format!(
1057            "the factory creates on connection `{name}`, but the executor belongs to no app to find it in"
1058        ))
1059    })?;
1060    app.get_named::<Db>(name).await.map_err(|error| {
1061        OrmError::invalid(format!(
1062            "no database connection named `{name}` in the app: {error}"
1063        ))
1064    })
1065}
1066
1067/// What a builder attaches with [`Factory::has_attached`]: records of `R`
1068/// a factory creates for each record, or stored records.
1069pub struct Attach<R: Model>(Attachable<R>);
1070
1071impl<RF: ModelFactory> From<Factory<RF>> for Attach<RF::Model> {
1072    fn from(factory: Factory<RF>) -> Self {
1073        Attach(Attachable::Factory(Arc::new(factory)))
1074    }
1075}
1076
1077impl<R: Model> From<&Record<R>> for Attach<R> {
1078    fn from(record: &Record<R>) -> Self {
1079        Attach(Attachable::Records(vec![record.clone()]))
1080    }
1081}
1082
1083impl<R: Model> From<Record<R>> for Attach<R> {
1084    fn from(record: Record<R>) -> Self {
1085        Attach(Attachable::Records(vec![record]))
1086    }
1087}
1088
1089impl<R: Model> From<&Collection<R>> for Attach<R> {
1090    fn from(records: &Collection<R>) -> Self {
1091        Attach(Attachable::Records(records.to_vec()))
1092    }
1093}
1094
1095impl<R: Model> From<Collection<R>> for Attach<R> {
1096    fn from(records: Collection<R>) -> Self {
1097        Attach(Attachable::Records(records.into_vec()))
1098    }
1099}
1100
1101impl<R: Model> From<Vec<Record<R>>> for Attach<R> {
1102    fn from(records: Vec<Record<R>>) -> Self {
1103        Attach(Attachable::Records(records))
1104    }
1105}
1106
1107impl<R: Model> fmt::Debug for Attach<R> {
1108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109        let what = match &self.0 {
1110            Attachable::Factory(_) => "factory",
1111            Attachable::Records(_) => "records",
1112        };
1113        f.debug_tuple("Attach").field(&what).finish()
1114    }
1115}
1116
1117impl<F: ModelFactory> Clone for Factory<F> {
1118    fn clone(&self) -> Self {
1119        Factory {
1120            factory: self.factory.clone(),
1121            count: self.count,
1122            states: self.states.clone(),
1123            parents: self.parents.clone(),
1124            children: self.children.clone(),
1125            recycle: self.recycle.clone(),
1126            after_making: self.after_making.clone(),
1127            after_creating: self.after_creating.clone(),
1128            expand_parents: self.expand_parents,
1129            excluded_parents: self.excluded_parents.clone(),
1130            connection: self.connection.clone(),
1131            seed: self.seed,
1132            errors: self.errors.clone(),
1133        }
1134    }
1135}
1136
1137impl<F: ModelFactory> fmt::Debug for Factory<F> {
1138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139        f.debug_struct("Factory")
1140            .field("model", &F::Model::meta().name())
1141            .field("count", &self.count)
1142            .field("states", &self.states.len())
1143            .field("parents", &self.parents.len())
1144            .field("children", &self.children.len())
1145            .field("recycle", &self.recycle)
1146            .field("seed", &self.seed)
1147            .field("connection", &self.connection)
1148            .finish_non_exhaustive()
1149    }
1150}