mod bulk;
mod context;
mod faker;
pub(crate) mod quiet;
mod relationships;
mod sequence;
mod sources;
use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use chrono::{DateTime, Duration, Utc};
use navree_db::Db;
use navree_kernel::BoxFuture;
pub use context::{Attributes, FactoryContext};
pub use faker::{FakeNumber, Faker};
pub use relationships::{BelongsTo, HasMany, Pivot, RelationshipInfo, Relationships};
pub use sequence::{Sequence, SequenceIndex};
pub use sources::{IntoRecords, LazyFactory, ParentHandle, ParentSource};
use crate::collection::Collection;
use crate::column::{Assignment, Column};
use crate::error::{OrmError, Result};
use crate::exec::{Access, Executor, Target, truncate_to_micros};
use crate::model::{Model, PrimaryKey};
use crate::persist;
use crate::record::Record;
use crate::value::{Value, ValueFor};
use self::context::PendingParent;
use self::relationships::{AttachRelated, Attachable, ChildLink, HasChildren};
use self::sources::{Recycle, ResolveParent};
pub trait ModelFactory: Send + Sync + Sized + 'static {
type Model: Model;
fn definition(&self, ctx: &mut FactoryContext<'_, Self::Model>) -> Self::Model;
fn configure(factory: Factory<Self>) -> Factory<Self> {
factory
}
fn relationships(relationships: &mut Relationships<Self::Model>) {
let _ = relationships;
}
}
pub trait HasFactory: Model {
type Factory: ModelFactory<Model = Self> + Default;
fn factory() -> Factory<Self::Factory> {
Factory::new()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FactoryOptions {
pub expand_relationships: bool,
pub seed: Option<u64>,
}
impl FactoryOptions {
pub const fn new() -> Self {
FactoryOptions {
expand_relationships: true,
seed: None,
}
}
pub const fn expand_relationships(mut self, expand: bool) -> Self {
self.expand_relationships = expand;
self
}
pub const fn seed(mut self, seed: u64) -> Self {
self.seed = Some(seed);
self
}
}
impl Default for FactoryOptions {
fn default() -> Self {
FactoryOptions::new()
}
}
type StateFn<M> =
Arc<dyn Fn(&mut M, &mut FactoryContext<'_, M>) -> Result<()> + Send + Sync + 'static>;
type AfterMaking<M> = Arc<dyn Fn(&mut Record<M>) + Send + Sync + 'static>;
type AfterCreating<M> = Arc<
dyn for<'a> Fn(&'a mut Record<M>, &'a Target<'a>) -> BoxFuture<'a, Result<()>>
+ Send
+ Sync
+ 'static,
>;
struct ParentLink {
source: Arc<dyn ResolveParent>,
owner_key: Option<Cow<'static, str>>,
foreign_key: Cow<'static, str>,
morph: Option<(Cow<'static, str>, Cow<'static, str>)>,
}
impl Clone for ParentLink {
fn clone(&self) -> Self {
ParentLink {
source: self.source.clone(),
owner_key: self.owner_key.clone(),
foreign_key: self.foreign_key.clone(),
morph: self.morph.clone(),
}
}
}
impl ParentLink {
fn assignments(&self, value: Value) -> Vec<(Cow<'static, str>, Value)> {
let mut values = vec![(self.foreign_key.clone(), value)];
if let Some((column, morph_type)) = &self.morph {
values.push((column.clone(), Value::from(morph_type.to_string())));
}
values
}
}
pub struct Factory<F: ModelFactory> {
factory: Arc<F>,
count: Option<usize>,
states: Vec<StateFn<F::Model>>,
parents: Vec<ParentLink>,
children: Vec<Arc<dyn ChildLink<F::Model>>>,
pub(crate) recycle: Recycle,
after_making: Vec<AfterMaking<F::Model>>,
after_creating: Vec<AfterCreating<F::Model>>,
expand_parents: Option<bool>,
excluded_parents: Vec<Cow<'static, str>>,
connection: Option<Cow<'static, str>>,
seed: Option<u64>,
errors: Vec<String>,
}
impl<F: ModelFactory + Default> Factory<F> {
pub fn new() -> Self {
Factory::of(F::default())
}
}
impl<F: ModelFactory + Default> Default for Factory<F> {
fn default() -> Self {
Factory::new()
}
}
impl<F: ModelFactory> Factory<F> {
pub fn of(factory: F) -> Self {
F::configure(Factory {
factory: Arc::new(factory),
count: None,
states: Vec::new(),
parents: Vec::new(),
children: Vec::new(),
recycle: Recycle::default(),
after_making: Vec::new(),
after_creating: Vec::new(),
expand_parents: None,
excluded_parents: Vec::new(),
connection: None,
seed: None,
errors: Vec::new(),
})
}
pub fn definition(&self) -> &F {
&self.factory
}
pub fn count(mut self, count: usize) -> Self {
self.count = Some(count);
self
}
pub fn state(self, state: impl Fn(&mut F::Model) + Send + Sync + 'static) -> Self {
self.push_state(move |model, _| {
state(model);
Ok(())
})
}
pub fn state_with(
self,
state: impl Fn(&mut F::Model, &mut FactoryContext<'_, F::Model>) + Send + Sync + 'static,
) -> Self {
self.push_state(move |model, ctx| {
state(model, ctx);
Ok(())
})
}
pub fn prepend_state(mut self, state: impl Fn(&mut F::Model) + Send + Sync + 'static) -> Self {
self.states.insert(
0,
Arc::new(move |model, _| {
state(model);
Ok(())
}),
);
self
}
pub fn set<T>(self, column: Column<F::Model, T>, value: impl ValueFor<T>) -> Self {
let assignment = column.set(value);
self.push_state(move |model, _| apply_assignment::<F::Model>(model, &assignment))
}
pub fn sequence(self, sequence: impl Into<Sequence<F::Model>>) -> Self {
let sequence = sequence.into();
self.push_state(move |model, ctx| sequence.apply(model, ctx.index()))
}
pub fn for_each_sequence(self, sequence: impl Into<Sequence<F::Model>>) -> Self {
let sequence = sequence.into();
let count = sequence.len();
self.sequence(sequence).count(count)
}
pub fn cross_join_sequence(
self,
sequences: impl IntoIterator<Item = Sequence<F::Model>>,
) -> Self {
let joined = Sequence::cross_join(sequences);
let count = joined.len();
let factory = self.sequence(joined);
match factory.count {
Some(_) => factory,
None => factory.count(count),
}
}
pub fn trashed(self) -> Self {
self.trashed_with(None)
}
pub fn trashed_at(self, at: DateTime<Utc>) -> Self {
self.trashed_with(Some(at))
}
fn trashed_with(self, at: Option<DateTime<Utc>>) -> Self {
let meta = F::Model::meta();
let Some(column) = meta.deleted_at() else {
let name = meta.name();
return self.with_error(format!(
"{name} does not soft-delete: trashed() needs #[model(soft_deletes)] on {name}"
));
};
self.push_state(move |model, ctx| {
let at = at.unwrap_or_else(|| ctx.now() - Duration::days(1));
model.touch_timestamp(column, at)
})
}
pub fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
if condition { then(self) } else { self }
}
pub fn seed(mut self, seed: u64) -> Self {
self.seed = Some(seed);
self
}
pub fn connection(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.connection = Some(name.into());
self
}
pub fn after_making(
mut self,
hook: impl Fn(&mut Record<F::Model>) + Send + Sync + 'static,
) -> Self {
self.after_making.push(Arc::new(hook));
self
}
pub fn after_creating(
mut self,
hook: impl for<'a> Fn(&'a mut Record<F::Model>, &'a Target<'a>) -> BoxFuture<'a, Result<()>>
+ Send
+ Sync
+ 'static,
) -> Self {
self.after_creating.push(Arc::new(hook));
self
}
pub fn without_after_making(mut self) -> Self {
self.after_making.clear();
self
}
pub fn without_after_creating(mut self) -> Self {
self.after_creating.clear();
self
}
pub fn for_<S: ParentSource>(
self,
parent: S,
link: impl Into<BelongsTo<F::Model, S::Parent>>,
) -> Self {
let link = link.into();
let link = match link.named {
Some(name) => {
match Relationships::<F::Model>::of::<F>().belongs_to_link::<S::Parent>(name) {
Ok(link) => link,
Err(error) => return self.with_error(problem(error)),
}
}
None => link,
};
let mut factory = self;
factory.parents.push(ParentLink {
source: parent.into_parent().0,
owner_key: link.owner_key.clone(),
foreign_key: link.foreign_key.clone(),
morph: link.morph.clone(),
});
factory
}
pub fn for_record<P: Model>(
self,
parent: &Record<P>,
link: impl Into<BelongsTo<F::Model, P>>,
) -> Self {
self.for_(parent, link)
}
pub fn has<CF: ModelFactory>(
self,
children: Factory<CF>,
link: impl Into<HasMany<F::Model, CF::Model>>,
) -> Self {
let link = link.into();
let link = match link.named {
Some(name) => {
match Relationships::<F::Model>::of::<F>().has_many_link::<CF::Model>(name) {
Ok(link) => link,
Err(error) => return self.with_error(problem(error)),
}
}
None => link,
};
let mut factory = self;
factory.children.push(Arc::new(HasChildren {
factory: children,
link,
}));
factory
}
pub fn has_attached<R: Model>(
self,
related: impl Into<Attach<R>>,
values: impl IntoIterator<Item = (&'static str, Value)>,
pivot: impl Into<Pivot<F::Model, R>>,
) -> Self {
let pivot = pivot.into();
let pivot = match pivot.named {
Some(name) => match Relationships::<F::Model>::of::<F>().pivot_link::<R>(name) {
Ok(pivot) => pivot,
Err(error) => return self.with_error(problem(error)),
},
None => pivot,
};
let values = values
.into_iter()
.map(|(column, value)| (Cow::Borrowed(column), value))
.collect();
let mut factory = self;
factory.children.push(Arc::new(AttachRelated {
related: related.into().0,
pivot,
values,
}));
factory
}
pub fn recycle<P: Model>(mut self, records: impl IntoRecords<P>) -> Self {
self.recycle.add(records.into_records());
self
}
pub fn without_parents(mut self) -> Self {
self.expand_parents = Some(false);
self
}
pub fn without_parent<T>(mut self, column: Column<F::Model, T>) -> Self {
use crate::column::ColumnName;
self.excluded_parents
.push(Cow::Owned(column.column_name().into_owned()));
self
}
pub fn lazy(self) -> LazyFactory<F> {
LazyFactory::new(self)
}
pub fn make(self) -> Result<Collection<F::Model>> {
let now = truncate_to_micros(Utc::now());
let mut faker = self.faker(FactoryOptions::default());
let parent_values = self.known_parent_values(&mut faker)?;
let count = self.count.unwrap_or(1);
let mut records = Vec::with_capacity(count);
for index in 0..count {
let (mut model, pending) = self.build(index, count, now, &mut faker, &parent_values)?;
for parent in &pending {
if parent.is_open(&model)? {
let pick = faker.next_u64();
if let Some(value) = parent.source.known(None, &self.recycle, pick)? {
model.set_value(&parent.column, value)?;
}
}
}
records.push(Record::new(model));
}
self.run_after_making(&mut records);
Ok(Collection::from(records))
}
pub fn make_one(self) -> Result<Record<F::Model>> {
self.count(1)
.make()?
.into_vec()
.pop()
.ok_or_else(|| OrmError::factory(F::Model::meta().name(), "the factory made no record"))
}
pub fn make_many(self, count: usize) -> Result<Collection<F::Model>> {
self.count(count).make()
}
pub fn raw(self) -> Result<Vec<Attributes>> {
let meta = F::Model::meta();
let timestamps: Vec<&str> = [meta.created_at(), meta.updated_at(), meta.deleted_at()]
.into_iter()
.flatten()
.collect();
self.without_after_making()
.make()?
.iter()
.map(|record| {
let model = record.model();
let values = model
.values()?
.into_iter()
.filter(|(column, _)| {
if *column == meta.key_column() {
return !model.key().is_empty();
}
!(timestamps.contains(column) && model.timestamp_is_empty(column))
})
.collect::<Vec<_>>();
Ok(Attributes::from(values))
})
.collect()
}
pub fn raw_one(self) -> Result<Attributes> {
self.count(1)
.raw()?
.pop()
.ok_or_else(|| OrmError::factory(F::Model::meta().name(), "the factory made no record"))
}
pub async fn create<E: Executor + ?Sized>(self, exec: &E) -> Result<Collection<F::Model>> {
let target = exec.target(Access::Write).await?;
match self.connection.clone() {
Some(name) => {
let db = named_connection(&target, &name).await?;
let named = db.target(Access::Write).await?;
self.create_on(&named).await
}
None => self.create_on(&target).await,
}
}
pub async fn create_one<E: Executor + ?Sized>(self, exec: &E) -> Result<Record<F::Model>> {
self.count(1)
.create(exec)
.await?
.into_vec()
.pop()
.ok_or_else(|| {
OrmError::factory(F::Model::meta().name(), "the factory created no record")
})
}
pub async fn create_many<E: Executor + ?Sized>(
self,
exec: &E,
count: usize,
) -> Result<Collection<F::Model>> {
self.count(count).create(exec).await
}
pub async fn create_quietly<E: Executor + ?Sized>(
self,
exec: &E,
) -> Result<Collection<F::Model>> {
self::quiet::scope(self.create(exec)).await
}
pub async fn create_one_quietly<E: Executor + ?Sized>(
self,
exec: &E,
) -> Result<Record<F::Model>> {
self::quiet::scope(self.create_one(exec)).await
}
pub async fn create_many_quietly<E: Executor + ?Sized>(
self,
exec: &E,
count: usize,
) -> Result<Collection<F::Model>> {
self::quiet::scope(self.create_many(exec, count)).await
}
pub async fn insert<E: Executor + ?Sized>(self, exec: &E) -> Result<u64> {
let target = exec.target(Access::Write).await?;
let ctx = target.context();
let now = ctx.now().await;
let options = factory_options(&ctx).await;
let mut faker = self.faker(options);
let parent_values = self.known_parent_values(&mut faker)?;
let count = self.count.unwrap_or(1);
let mut models = Vec::with_capacity(count);
for index in 0..count {
let (mut model, pending) = self.build(index, count, now, &mut faker, &parent_values)?;
for parent in &pending {
if parent.is_open(&model)? {
let pick = faker.next_u64();
if let Some(value) = parent.source.known(None, &self.recycle, pick)? {
model.set_value(&parent.column, value)?;
}
}
}
models.push(Record::new(model));
}
self.run_after_making(&mut models);
bulk::insert_models(
&target,
models.into_iter().map(Record::into_inner).collect(),
now,
)
.await
}
pub(crate) async fn create_on(self, target: &Target<'_>) -> Result<Collection<F::Model>> {
self.check()?;
let ctx = target.context();
let now = ctx.now().await;
let options = factory_options(&ctx).await;
let expand = self.expand_parents.unwrap_or(options.expand_relationships);
let mut faker = self.faker(options);
let count = self.count.unwrap_or(1);
let mut parent_values = Vec::new();
for link in &self.parents {
let pick = faker.next_u64();
let value = link
.source
.resolve(link.owner_key.as_deref(), target, &self.recycle, pick, true)
.await?
.ok_or_else(|| {
OrmError::factory(
F::Model::meta().name(),
format!(
"no {} record to point `{}` at",
link.source.model_name(),
link.foreign_key
),
)
})?;
parent_values.extend(link.assignments(value));
}
let mut records = Vec::with_capacity(count);
for index in 0..count {
let (mut model, pending) = self.build(index, count, now, &mut faker, &parent_values)?;
for parent in &pending {
if !parent.is_open(&model)? {
continue;
}
let excluded = self.excluded_parents.contains(&parent.column);
let pick = faker.next_u64();
let value = parent
.source
.resolve(None, target, &self.recycle, pick, expand && !excluded)
.await?;
if let Some(value) = value {
model.set_value(&parent.column, value)?;
}
}
records.push(Record::new(model));
}
self.run_after_making(&mut records);
for record in &mut records {
if !persist::save(target, record).await? {
return Err(OrmError::factory(
F::Model::meta().name(),
"a model hook cancelled saving a factory record",
));
}
for child in &self.children {
child.create_for(record, target, &self.recycle).await?;
}
}
for record in &mut records {
for hook in &self.after_creating {
hook(record, target).await?;
}
}
Ok(Collection::from(records))
}
fn push_state(
mut self,
state: impl Fn(&mut F::Model, &mut FactoryContext<'_, F::Model>) -> Result<()>
+ Send
+ Sync
+ 'static,
) -> Self {
self.states.push(Arc::new(state));
self
}
pub(crate) fn state_values(self, values: Vec<(Cow<'static, str>, Value)>) -> Self {
self.push_state(move |model, _| {
for (column, value) in &values {
model.set_value(column, value.clone())?;
}
Ok(())
})
}
fn with_error(mut self, message: String) -> Self {
self.errors.push(message);
self
}
fn check(&self) -> Result<()> {
match self.errors.first() {
Some(message) => Err(OrmError::factory(F::Model::meta().name(), message.clone())),
None => Ok(()),
}
}
fn faker(&self, options: FactoryOptions) -> Faker {
match self.seed.or(options.seed) {
Some(seed) => Faker::seeded(seed),
None => Faker::new(),
}
}
fn known_parent_values(&self, faker: &mut Faker) -> Result<Vec<(Cow<'static, str>, Value)>> {
self.check()?;
let mut values = Vec::new();
for link in &self.parents {
let pick = faker.next_u64();
if let Some(value) =
link.source
.known(link.owner_key.as_deref(), &self.recycle, pick)?
{
values.extend(link.assignments(value));
}
}
Ok(values)
}
fn build(
&self,
index: usize,
count: usize,
now: DateTime<Utc>,
faker: &mut Faker,
parent_values: &[(Cow<'static, str>, Value)],
) -> Result<(F::Model, Vec<PendingParent>)> {
let mut pending = Vec::new();
let mut ctx = FactoryContext::new(index, count, now, faker, &mut pending);
let mut model = self.factory.definition(&mut ctx);
for (column, value) in parent_values {
model.set_value(column, value.clone())?;
}
for state in &self.states {
state(&mut model, &mut ctx)?;
}
Ok((model, pending))
}
fn run_after_making(&self, records: &mut [Record<F::Model>]) {
for record in records {
for hook in &self.after_making {
hook(record);
}
}
}
}
fn problem(error: OrmError) -> String {
match error {
OrmError::Factory { message, .. } => message,
other => other.to_string(),
}
}
fn apply_assignment<M: Model>(model: &mut M, assignment: &Assignment) -> Result<()> {
match assignment.assigned_value() {
Some(value) => model.set_value(assignment.column(), value.clone()),
None => {
let message = assignment
.clone()
.into_set()
.err()
.unwrap_or_else(|| format!("`{}` must be set to a value", assignment.column()));
Err(OrmError::factory(M::meta().name(), message))
}
}
}
async fn factory_options(ctx: &crate::exec::ExecContext) -> FactoryOptions {
match ctx.app() {
Some(app) => app
.try_get::<FactoryOptions>()
.await
.map(|options| *options)
.unwrap_or_default(),
None => FactoryOptions::default(),
}
}
async fn named_connection(target: &Target<'_>, name: &str) -> Result<Arc<Db>> {
let ctx = target.context();
let app = ctx.app().ok_or_else(|| {
OrmError::invalid(format!(
"the factory creates on connection `{name}`, but the executor belongs to no app to find it in"
))
})?;
app.get_named::<Db>(name).await.map_err(|error| {
OrmError::invalid(format!(
"no database connection named `{name}` in the app: {error}"
))
})
}
pub struct Attach<R: Model>(Attachable<R>);
impl<RF: ModelFactory> From<Factory<RF>> for Attach<RF::Model> {
fn from(factory: Factory<RF>) -> Self {
Attach(Attachable::Factory(Arc::new(factory)))
}
}
impl<R: Model> From<&Record<R>> for Attach<R> {
fn from(record: &Record<R>) -> Self {
Attach(Attachable::Records(vec![record.clone()]))
}
}
impl<R: Model> From<Record<R>> for Attach<R> {
fn from(record: Record<R>) -> Self {
Attach(Attachable::Records(vec![record]))
}
}
impl<R: Model> From<&Collection<R>> for Attach<R> {
fn from(records: &Collection<R>) -> Self {
Attach(Attachable::Records(records.to_vec()))
}
}
impl<R: Model> From<Collection<R>> for Attach<R> {
fn from(records: Collection<R>) -> Self {
Attach(Attachable::Records(records.into_vec()))
}
}
impl<R: Model> From<Vec<Record<R>>> for Attach<R> {
fn from(records: Vec<Record<R>>) -> Self {
Attach(Attachable::Records(records))
}
}
impl<R: Model> fmt::Debug for Attach<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let what = match &self.0 {
Attachable::Factory(_) => "factory",
Attachable::Records(_) => "records",
};
f.debug_tuple("Attach").field(&what).finish()
}
}
impl<F: ModelFactory> Clone for Factory<F> {
fn clone(&self) -> Self {
Factory {
factory: self.factory.clone(),
count: self.count,
states: self.states.clone(),
parents: self.parents.clone(),
children: self.children.clone(),
recycle: self.recycle.clone(),
after_making: self.after_making.clone(),
after_creating: self.after_creating.clone(),
expand_parents: self.expand_parents,
excluded_parents: self.excluded_parents.clone(),
connection: self.connection.clone(),
seed: self.seed,
errors: self.errors.clone(),
}
}
}
impl<F: ModelFactory> fmt::Debug for Factory<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Factory")
.field("model", &F::Model::meta().name())
.field("count", &self.count)
.field("states", &self.states.len())
.field("parents", &self.parents.len())
.field("children", &self.children.len())
.field("recycle", &self.recycle)
.field("seed", &self.seed)
.field("connection", &self.connection)
.finish_non_exhaustive()
}
}