Skip to main content

FactoryCreate

Trait FactoryCreate 

Source
pub trait FactoryCreate<Pool>: Sized
where Pool: Sync,
{ type Entity; // Required method fn create<'life0, 'async_trait>( self, pool: &'life0 Pool, ) -> Pin<Box<dyn Future<Output = FactoryResult<Self::Entity>> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait; }
Expand description

Trait for factories that can create entities in the database.

The Pool type parameter allows factories to work with any database backend:

  • sqlx::PgPool (PostgreSQL)
  • sqlx::SqlitePool (SQLite)
  • sqlx::MySqlPool (MySQL)
  • mongodb::Database (MongoDB)
  • Any custom connection type

§Example

ⓘ
use factory_core::{FactoryCreate, FactoryResult};
use sqlx::PgPool;

#[async_trait]
impl FactoryCreate<PgPool> for PatientFactory {
    type Entity = Patient;

    async fn create(self, pool: &PgPool) -> FactoryResult<Patient> {
        // build_with_fks resolves all FK dependencies automatically
        let entity = self.build_with_fks(pool).await?;

        // User writes the INSERT query
        let patient = sqlx::query_as!(Patient,
            "INSERT INTO patient (practice_id, name) VALUES ($1, $2) RETURNING *",
            entity.practice_id.0,
            entity.name,
        )
        .fetch_one(pool)
        .await?;

        Ok(patient)
    }
}

Required Associated Types§

Source

type Entity

The entity type this factory creates.

Required Methods§

Source

fn create<'life0, 'async_trait>( self, pool: &'life0 Pool, ) -> Pin<Box<dyn Future<Output = FactoryResult<Self::Entity>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Create the entity in the database.

Implementations should:

  1. Call self.build_with_fks(pool).await? to resolve FK dependencies
  2. Execute an INSERT query with the resolved entity fields
  3. Return the created entity (usually with RETURNING *)

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§