1mod 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
84pub trait ModelFactory: Send + Sync + Sized + 'static {
126 type Model: Model;
128
129 fn definition(&self, ctx: &mut FactoryContext<'_, Self::Model>) -> Self::Model;
133
134 fn configure(factory: Factory<Self>) -> Factory<Self> {
138 factory
139 }
140
141 fn relationships(relationships: &mut Relationships<Self::Model>) {
146 let _ = relationships;
147 }
148}
149
150pub trait HasFactory: Model {
153 type Factory: ModelFactory<Model = Self> + Default;
155
156 fn factory() -> Factory<Self::Factory> {
158 Factory::new()
159 }
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166#[non_exhaustive]
167pub struct FactoryOptions {
168 pub expand_relationships: bool,
172 pub seed: Option<u64>,
175}
176
177impl FactoryOptions {
178 pub const fn new() -> Self {
180 FactoryOptions {
181 expand_relationships: true,
182 seed: None,
183 }
184 }
185
186 pub const fn expand_relationships(mut self, expand: bool) -> Self {
188 self.expand_relationships = expand;
189 self
190 }
191
192 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
205type StateFn<M> =
207 Arc<dyn Fn(&mut M, &mut FactoryContext<'_, M>) -> Result<()> + Send + Sync + 'static>;
208
209type AfterMaking<M> = Arc<dyn Fn(&mut Record<M>) + Send + Sync + 'static>;
211
212type 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
220struct 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 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
252pub 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 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 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 pub fn definition(&self) -> &F {
313 &self.factory
314 }
315
316 pub fn count(mut self, count: usize) -> Self {
322 self.count = Some(count);
323 self
324 }
325
326 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 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 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 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 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 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 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 pub fn trashed(self) -> Self {
424 self.trashed_with(None)
425 }
426
427 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 pub fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self {
448 if condition { then(self) } else { self }
449 }
450
451 pub fn seed(mut self, seed: u64) -> Self {
454 self.seed = Some(seed);
455 self
456 }
457
458 pub fn connection(mut self, name: impl Into<Cow<'static, str>>) -> Self {
462 self.connection = Some(name.into());
463 self
464 }
465
466 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 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 pub fn without_after_making(mut self) -> Self {
508 self.after_making.clear();
509 self
510 }
511
512 pub fn without_after_creating(mut self) -> Self {
514 self.after_creating.clear();
515 self
516 }
517
518 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 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 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 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 pub fn recycle<P: Model>(mut self, records: impl IntoRecords<P>) -> Self {
638 self.recycle.add(records.into_records());
639 self
640 }
641
642 pub fn without_parents(mut self) -> Self {
646 self.expand_parents = Some(false);
647 self
648 }
649
650 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 pub fn lazy(self) -> LazyFactory<F> {
662 LazyFactory::new(self)
663 }
664
665 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 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 pub fn make_many(self, count: usize) -> Result<Collection<F::Model>> {
705 self.count(count).make()
706 }
707
708 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
1016fn problem(error: OrmError) -> String {
1019 match error {
1020 OrmError::Factory { message, .. } => message,
1021 other => other.to_string(),
1022 }
1023}
1024
1025fn 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
1040async 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
1052async 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
1067pub 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}