Skip to main content

larust_orm/
factory.rs

1//! Model factories - Eloquent's `Model::factory()`. Implemented by hand,
2//! once per model, in an app's own `database/factories/` (no generated
3//! code or derive involved, unlike `#[derive(Model)]` itself - a factory
4//! is test/seed-only, so there's nothing for `#[derive(Model)]` to need
5//! to know about it).
6//!
7//! ```ignore
8//! use larust_support::orm::Factory;
9//!
10//! pub struct PostFactory;
11//!
12//! impl Factory for PostFactory {
13//!     type Model = Post;
14//!
15//!     fn definition(seq: u64) -> NewPost {
16//!         NewPost { title: format!("Post {seq}"), user_id: 0 }
17//!     }
18//! }
19//!
20//! // in a test:
21//! let post = PostFactory::new()
22//!     .state(move |p| NewPost { user_id: user.id, ..p })
23//!     .create()
24//!     .await?;
25//! ```
26//!
27//! `definition` is synchronous and takes no database-derived input - a
28//! parent row (`user_id` above) is wired explicitly via `.state(...)`,
29//! not auto-created the way Laravel's own `'user_id' => User::factory()`
30//! implicitly does. Auto-creating would force `definition` to be async
31//! *and* to persist a row just to build one field's value, which is
32//! Laravel's own quirk (a `make()` that doesn't actually just "make"),
33//! not something worth porting.
34//!
35//! `create`/`create_many` never spawn a task - both run `F::Model::create`
36//! directly, in the caller's own task, so `larust_orm::with_pool_override`
37//! (what `larust_testing::test_transaction` uses to scope a factory-backed
38//! test to its own isolated database) is respected automatically.
39
40use crate::model::Model;
41use larust_core::AppError;
42use std::marker::PhantomData;
43use std::sync::atomic::{AtomicU64, Ordering};
44
45/// A process-wide counter, not per-factory - matches Laravel's own
46/// `sequence()`/factory counter being a single incrementing source apps
47/// never reset mid-run. Exists so a plain `definition` can produce unique
48/// values (an email, a slug) with no faker dependency: `format!("user{seq}
49/// @example.com")` is enough for most tests.
50static SEQUENCE: AtomicU64 = AtomicU64::new(1);
51
52fn next_seq() -> u64 {
53    SEQUENCE.fetch_add(1, Ordering::Relaxed)
54}
55
56/// Implemented by hand for each model that needs factory-built test/seed
57/// data. `Self::Model::New` (the model's own generated `New{Model}` type)
58/// is what `definition` builds and what `.state(...)` transforms.
59pub trait Factory: Sized + 'static {
60    type Model: Model;
61
62    /// Builds one unsaved value from a unique sequence number.
63    fn definition(seq: u64) -> <Self::Model as Model>::New;
64
65    /// `PostFactory::new()` - a real, always-correct default (not an
66    /// optional hook silently no-op-ing), so it's safe to provide here the
67    /// same way `larust_auth::Policy`'s own `authorize_*` helpers are.
68    fn new() -> FactoryBuilder<Self> {
69        FactoryBuilder::new()
70    }
71}
72
73type StateFn<F> = Box<
74    dyn Fn(<<F as Factory>::Model as Model>::New) -> <<F as Factory>::Model as Model>::New
75        + Send
76        + Sync,
77>;
78
79/// Accumulates `.state(...)` overrides before `.make()`/`.create()`
80/// actually builds a value - Laravel's own factory builder, minus the
81/// PHP-side magic (no `$this->state(fn (array $attributes) => [...])`
82/// merge-by-array-key; a state here is a plain `FnOnce`-shaped closure
83/// over the whole typed value, applied via Rust's own struct-update
84/// syntax: `|p| NewPost { title: "x".into(), ..p }`).
85pub struct FactoryBuilder<F: Factory> {
86    states: Vec<StateFn<F>>,
87    _marker: PhantomData<fn() -> F>,
88}
89
90impl<F: Factory> FactoryBuilder<F> {
91    pub fn new() -> Self {
92        Self {
93            states: Vec::new(),
94            _marker: PhantomData,
95        }
96    }
97
98    /// Queues an override applied, in call order, after `F::definition`.
99    #[must_use]
100    pub fn state(
101        mut self,
102        f: impl Fn(<F::Model as Model>::New) -> <F::Model as Model>::New + Send + Sync + 'static,
103    ) -> Self {
104        self.states.push(Box::new(f));
105        self
106    }
107
108    /// Eloquent's `make()` - builds one value without persisting it.
109    pub fn make(&self) -> <F::Model as Model>::New {
110        let mut data = F::definition(next_seq());
111        for state in &self.states {
112            data = state(data);
113        }
114        data
115    }
116
117    /// Eloquent's `make()->count($n)`.
118    pub fn make_many(&self, n: usize) -> Vec<<F::Model as Model>::New> {
119        (0..n).map(|_| self.make()).collect()
120    }
121
122    /// Eloquent's `create()` - builds and persists one row.
123    pub async fn create(&self) -> Result<F::Model, AppError> {
124        F::Model::create(self.make()).await
125    }
126
127    /// Eloquent's `create()->count($n)` - sequential, never spawned (see
128    /// the module doc comment for why that matters for test isolation).
129    pub async fn create_many(&self, n: usize) -> Result<Vec<F::Model>, AppError> {
130        let mut out = Vec::with_capacity(n);
131        for _ in 0..n {
132            out.push(self.create().await?);
133        }
134        Ok(out)
135    }
136}
137
138impl<F: Factory> Default for FactoryBuilder<F> {
139    fn default() -> Self {
140        Self::new()
141    }
142}