Skip to main content

factory_m8/
lib.rs

1//! Factory Core - Shared traits for test data factories
2//!
3//! This crate provides traits that factories implement to enable
4//! database insertion with automatic FK resolution.
5//!
6//! ## Traits
7//!
8//! - [`FactoryCreate`] - Async trait for creating entities in the database
9//! - [`Sentinel`] - Trait for detecting "unset" values that trigger auto-creation
10//!
11//! ## Database Agnostic
12//!
13//! `FactoryCreate` is generic over the connection/pool type, so it works with any database:
14//!
15//! - `sqlx::PgPool` (PostgreSQL)
16//! - `sqlx::SqlitePool` (SQLite)
17//! - `sqlx::MySqlPool` (MySQL)
18//! - `mongodb::Database` (MongoDB)
19//! - Any custom connection type
20//!
21//! ## Example
22//!
23//! ```ignore
24//! use factory_core::{FactoryCreate, FactoryResult, Sentinel};
25//! use sqlx::PgPool;
26//!
27//! // Implement Sentinel for your ID types
28//! #[derive(Clone, Default, PartialEq)]
29//! pub struct UserId(pub i64);
30//!
31//! impl Sentinel for UserId {
32//!     fn sentinel() -> Self { UserId(0) }
33//!     fn is_sentinel(&self) -> bool { self.0 == 0 }
34//! }
35//!
36//! // Use in factory
37//! #[derive(Factory)]
38//! #[factory(entity = User)]
39//! pub struct UserFactory {
40//!     #[pk]
41//!     pub id: UserId,
42//!
43//!     #[fk(Tenant, "id", TenantFactory)]
44//!     pub tenant_id: TenantId,  // Auto-creates if sentinel
45//! }
46//!
47//! // Implement for your chosen database
48//! #[async_trait]
49//! impl FactoryCreate<PgPool> for UserFactory {
50//!     type Entity = User;
51//!
52//!     async fn create(self, pool: &PgPool) -> FactoryResult<User> {
53//!         // ... INSERT query
54//!     }
55//! }
56//! ```
57//!
58//! ## Mixed Database Backends
59//!
60//! If your project uses multiple databases (e.g., Postgres + MongoDB), you can:
61//!
62//! 1. Implement `FactoryCreate<PgPool>` for Postgres entities
63//! 2. Implement `FactoryCreate<mongodb::Database>` for MongoDB entities
64//! 3. Use `no_default` on cross-backend FKs to disable auto-creation:
65//!
66//! ```ignore
67//! #[derive(Factory)]
68//! #[factory(entity = Patient)]
69//! pub struct PatientFactory {
70//!     // Same backend - auto-creates work
71//!     #[fk(Practice, "id", PracticeFactory)]
72//!     pub practice_id: PracticeId,
73//!
74//!     // Different backend - set manually, no auto-create
75//!     #[fk(AuditLog, "id", AuditLogFactory, no_default)]
76//!     pub audit_log_id: Option<AuditLogId>,
77//! }
78//! ```
79
80use async_trait::async_trait;
81#[cfg(feature = "derive")]
82pub use factory_m8_derive::Factory;
83use std::error::Error;
84
85// =============================================================================
86// RESULT TYPE
87// =============================================================================
88
89/// Result type for factory create operations.
90pub type FactoryResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
91
92// =============================================================================
93// SENTINEL TRAIT
94// =============================================================================
95
96/// Trait for detecting "sentinel" values that trigger auto-creation of FK dependencies.
97///
98/// When a factory field has a sentinel value, `build_with_fks()` will automatically
99/// create the dependency using its factory instead of using the sentinel value.
100///
101/// ## Common Sentinel Values
102///
103/// - For numeric IDs: `0` (database IDs typically start at 1)
104/// - For UUIDs: `Uuid::nil()`
105/// - For `Option<T>`: `None`
106///
107/// ## Example
108///
109/// ```
110/// use factory_core::Sentinel;
111///
112/// #[derive(Clone, Copy, Default, PartialEq)]
113/// pub struct UserId(pub i64);
114///
115/// impl Sentinel for UserId {
116///     fn sentinel() -> Self {
117///         UserId(0)
118///     }
119///
120///     fn is_sentinel(&self) -> bool {
121///         self.0 == 0
122///     }
123/// }
124/// ```
125pub trait Sentinel: Clone {
126    /// Returns the sentinel value for this type.
127    ///
128    /// This is the value that indicates "not set, please auto-generate".
129    fn sentinel() -> Self;
130
131    /// Returns true if this value is the sentinel (i.e., should trigger auto-creation).
132    fn is_sentinel(&self) -> bool;
133}
134
135// =============================================================================
136// SENTINEL IMPLEMENTATIONS FOR COMMON TYPES
137// =============================================================================
138
139impl Sentinel for i64 {
140    fn sentinel() -> Self {
141        0
142    }
143    fn is_sentinel(&self) -> bool {
144        *self == 0
145    }
146}
147
148impl Sentinel for i32 {
149    fn sentinel() -> Self {
150        0
151    }
152    fn is_sentinel(&self) -> bool {
153        *self == 0
154    }
155}
156
157impl Sentinel for i16 {
158    fn sentinel() -> Self {
159        0
160    }
161    fn is_sentinel(&self) -> bool {
162        *self == 0
163    }
164}
165
166impl Sentinel for u64 {
167    fn sentinel() -> Self {
168        0
169    }
170    fn is_sentinel(&self) -> bool {
171        *self == 0
172    }
173}
174
175impl Sentinel for u32 {
176    fn sentinel() -> Self {
177        0
178    }
179    fn is_sentinel(&self) -> bool {
180        *self == 0
181    }
182}
183
184impl Sentinel for String {
185    fn sentinel() -> Self {
186        String::new()
187    }
188    fn is_sentinel(&self) -> bool {
189        self.is_empty()
190    }
191}
192
193/// Blanket implementation for `Option<T>`.
194///
195/// - `None` is always a sentinel
196/// - `Some(value)` is a sentinel if `value.is_sentinel()` returns true
197impl<T: Sentinel> Sentinel for Option<T> {
198    fn sentinel() -> Self {
199        None
200    }
201
202    fn is_sentinel(&self) -> bool {
203        match self {
204            None => true,
205            Some(v) => v.is_sentinel(),
206        }
207    }
208}
209
210// =============================================================================
211// FACTORY CREATE TRAIT
212// =============================================================================
213
214/// Trait for factories that can create entities in the database.
215///
216/// The `Pool` type parameter allows factories to work with any database backend:
217///
218/// - `sqlx::PgPool` (PostgreSQL)
219/// - `sqlx::SqlitePool` (SQLite)
220/// - `sqlx::MySqlPool` (MySQL)
221/// - `mongodb::Database` (MongoDB)
222/// - Any custom connection type
223///
224/// ## Example
225///
226/// ```ignore
227/// use factory_core::{FactoryCreate, FactoryResult};
228/// use sqlx::PgPool;
229///
230/// #[async_trait]
231/// impl FactoryCreate<PgPool> for PatientFactory {
232///     type Entity = Patient;
233///
234///     async fn create(self, pool: &PgPool) -> FactoryResult<Patient> {
235///         // build_with_fks resolves all FK dependencies automatically
236///         let entity = self.build_with_fks(pool).await?;
237///
238///         // User writes the INSERT query
239///         let patient = sqlx::query_as!(Patient,
240///             "INSERT INTO patient (practice_id, name) VALUES ($1, $2) RETURNING *",
241///             entity.practice_id.0,
242///             entity.name,
243///         )
244///         .fetch_one(pool)
245///         .await?;
246///
247///         Ok(patient)
248///     }
249/// }
250/// ```
251#[async_trait]
252pub trait FactoryCreate<Pool>: Sized
253where
254    Pool: Sync,
255{
256    /// The entity type this factory creates.
257    type Entity;
258
259    /// Create the entity in the database.
260    ///
261    /// Implementations should:
262    /// 1. Call `self.build_with_fks(pool).await?` to resolve FK dependencies
263    /// 2. Execute an INSERT query with the resolved entity fields
264    /// 3. Return the created entity (usually with RETURNING *)
265    async fn create(self, pool: &Pool) -> FactoryResult<Self::Entity>;
266}
267
268// =============================================================================
269// TESTS
270// =============================================================================
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[derive(Clone, Copy, Default, PartialEq, Debug)]
277    struct TestId(i64);
278
279    impl Sentinel for TestId {
280        fn sentinel() -> Self {
281            TestId(0)
282        }
283        fn is_sentinel(&self) -> bool {
284            self.0 == 0
285        }
286    }
287
288    #[test]
289    fn test_sentinel_i64() {
290        assert!(0_i64.is_sentinel());
291        assert!(!1_i64.is_sentinel());
292        assert!(!(-1_i64).is_sentinel());
293    }
294
295    #[test]
296    fn test_sentinel_option_none() {
297        let none: Option<i64> = None;
298        assert!(none.is_sentinel());
299    }
300
301    #[test]
302    fn test_sentinel_option_some_sentinel() {
303        let some_zero: Option<i64> = Some(0);
304        assert!(some_zero.is_sentinel());
305    }
306
307    #[test]
308    fn test_sentinel_option_some_non_sentinel() {
309        let some_one: Option<i64> = Some(1);
310        assert!(!some_one.is_sentinel());
311    }
312
313    #[test]
314    fn test_sentinel_custom_type() {
315        assert!(TestId(0).is_sentinel());
316        assert!(!TestId(1).is_sentinel());
317        assert!(!TestId(999).is_sentinel());
318    }
319
320    #[test]
321    fn test_sentinel_option_custom_type() {
322        let none: Option<TestId> = None;
323        let some_zero: Option<TestId> = Some(TestId(0));
324        let some_one: Option<TestId> = Some(TestId(1));
325
326        assert!(none.is_sentinel());
327        assert!(some_zero.is_sentinel());
328        assert!(!some_one.is_sentinel());
329    }
330}