1use std::cmp::Reverse;
33use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
34
35use glob::Pattern;
36use rand::RngExt;
37
38use crate::diagnostic::{DiagnosticBag, Severity, SourceLocation};
39use crate::synthetic::model::{
40 ChildDistribution, InferenceMode, ModifierConfig, PlannerConfig, RelationshipModel, RowsModel,
41 SyntheticModel, TableModel, TableSeed,
42};
43use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
44
45use super::plan::{
46 ColumnOwner, CompiledOutput, CompiledRelationship, ExecutionPhase, FamilyPhase, GenerationPlan,
47 PlanEstimates, PlannedColumn, PlannedTable, RelationshipDistribution, ResolvedTableSeed,
48};
49use super::registry::{
50 ColumnScope, CompileContext, CompiledModifier, CompiledPlanner, ExtensionRegistry,
51};
52use super::seed::{SeedRoot, StreamId};
53
54#[derive(Debug, Clone, PartialEq)]
57pub struct TableCountOverride {
58 pub table: String,
60 pub kind: TableCountKind,
62}
63
64#[derive(Debug, Clone, PartialEq)]
66pub enum TableCountKind {
67 Rows(u64),
69 Scale(f64),
72}
73
74impl TableCountOverride {
75 pub fn rows(table: impl Into<String>, rows: u64) -> Self {
77 Self {
78 table: table.into(),
79 kind: TableCountKind::Rows(rows),
80 }
81 }
82
83 pub fn scale(table: impl Into<String>, scale: f64) -> Self {
85 Self {
86 table: table.into(),
87 kind: TableCountKind::Scale(scale),
88 }
89 }
90}
91
92#[derive(Debug, Clone, Default)]
95pub struct CompileOptions {
96 pub seed: Option<u64>,
98 pub scale: Option<f64>,
100 pub rows: Option<u64>,
102 pub max_rows: Option<u64>,
104 pub table_rows: Vec<TableCountOverride>,
106 pub tables: Vec<String>,
108 pub exclude: Vec<String>,
110 pub family_budget_bytes: Option<u64>,
115}
116
117const DEFAULT_FAMILY_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
119
120pub struct ModelCompiler {
125 registry: ExtensionRegistry,
126}
127
128impl ModelCompiler {
129 pub fn new(registry: ExtensionRegistry) -> Self {
131 Self { registry }
132 }
133
134 pub fn standard() -> Self {
136 Self::new(ExtensionRegistry::standard())
137 }
138
139 pub fn registry(&self) -> &ExtensionRegistry {
141 &self.registry
142 }
143
144 pub fn compile(
148 &self,
149 model: SyntheticModel,
150 options: CompileOptions,
151 ) -> Result<GenerationPlan, DiagnosticBag> {
152 let mut bag = DiagnosticBag::default();
153
154 if options.scale.is_some() && options.rows.is_some() {
155 bag.error(
156 crate::diagnostic::codes::COUNT_CONTROL_CONFLICT.code,
157 "options",
158 "`--scale` and `--rows` are mutually exclusive global row controls",
159 );
160 }
161 if let Some(scale) = options.scale {
162 if !scale.is_finite() || scale < 0.0 {
165 bag.error(
166 crate::diagnostic::codes::TABLE_SCALE_INVALID.code,
167 "options",
168 format!("`--scale` must be a finite, non-negative number (got {scale})"),
169 );
170 }
171 }
172
173 let overrides = self.collect_table_overrides(&options, &mut bag);
174 let selected = self.select_tables(&model, &options, &mut bag);
175 let all_parents = parent_edges(&model, EdgeKind::All);
181 let required = parent_edges(&model, EdgeKind::Required);
182 self.report_excluded_dependencies(&selected, &required, &mut bag);
183 let schema_changed = selected.len() < model.tables.len();
187
188 let root_seed = options.seed.or(model.seed).unwrap_or_else(rand::random);
192 let rounding_root = SeedRoot::new(root_seed);
193 let (mut order, mut cyclic) = topo_order(&selected, &all_parents);
194 if !cyclic.is_empty() {
195 let (required_order, required_cyclic) = topo_order(&selected, &required);
203 if required_cyclic.is_empty() {
204 order = required_order;
205 cyclic = Vec::new();
206 bag.warning(
207 crate::diagnostic::codes::FOREIGN_KEY_CYCLE.code,
208 "tables",
209 "nullable foreign keys form a dependency cycle; the cyclic tables cannot all be ordered parent-before-child in the output",
210 );
211 }
212 }
213 if !cyclic.is_empty() {
214 bag.error(
220 crate::diagnostic::codes::ROWS_CYCLE.code,
221 "tables",
222 format!(
223 "required dependencies (non-null foreign keys or relation.children row counts) form a cycle among tables: {}; each derives from a parent that ultimately derives from it",
224 cyclic.join(", ")
225 ),
226 );
227 }
228
229 let family_ctx = self.collect_family_facts(&model, &mut bag);
230 let family_budget_bytes = options
231 .family_budget_bytes
232 .unwrap_or(DEFAULT_FAMILY_BUDGET_BYTES);
233
234 let mut resolved: BTreeMap<String, u64> = BTreeMap::new();
235 let mut tables: Vec<PlannedTable> = Vec::with_capacity(order.len());
236
237 for name in &order {
238 let table = &model.tables[name];
239 let count = self.resolve_count(
240 &model,
241 name,
242 table,
243 &options,
244 overrides.get(name),
245 rounding_root,
246 &resolved,
247 &mut bag,
248 );
249 resolved.insert(name.clone(), count);
250 tables.push(self.plan_table(
251 &model,
252 name,
253 table,
254 count,
255 root_seed,
256 model.defaults.inference,
257 &family_ctx,
258 &resolved,
259 &selected,
260 !schema_changed,
261 &mut bag,
262 ));
263 }
264
265 let phases = build_phases(&order, &family_ctx, family_budget_bytes, &mut bag);
266
267 let estimates = PlanEstimates {
268 total_rows: resolved.values().copied().fold(0u64, u64::saturating_add),
269 ..PlanEstimates::default()
270 };
271
272 if bag.has_errors() {
273 return Err(bag);
274 }
275
276 let diagnostics = bag
280 .diagnostics
281 .into_iter()
282 .filter(|diagnostic| diagnostic.severity == Severity::Warning)
283 .collect();
284
285 Ok(GenerationPlan {
286 input_dialect: model
287 .source
288 .as_ref()
289 .and_then(|source| source.dialect.parse().ok()),
290 output: compile_output(&model),
291 tables,
292 phases,
293 diagnostics,
294 estimates,
295 family_budget_bytes,
296 })
297 }
298
299 fn collect_table_overrides(
303 &self,
304 options: &CompileOptions,
305 bag: &mut DiagnosticBag,
306 ) -> BTreeMap<String, TableOverride> {
307 let mut map: BTreeMap<String, TableOverride> = BTreeMap::new();
308 for over in &options.table_rows {
309 let entry = map.entry(over.table.clone()).or_default();
310 match over.kind {
311 TableCountKind::Rows(rows) => entry.rows = Some(rows),
312 TableCountKind::Scale(scale) => entry.scale = Some(scale),
313 }
314 }
315 for (table, over) in &map {
316 if over.rows.is_some() && over.scale.is_some() {
317 bag.error(
318 crate::diagnostic::codes::TABLE_COUNT_CONFLICT.code,
319 format!("tables.{table}"),
320 format!(
321 "table `{table}` has both `--table-rows` and `--table-scale`; they are mutually exclusive"
322 ),
323 );
324 }
325 }
326 map
327 }
328
329 fn select_tables(
331 &self,
332 model: &SyntheticModel,
333 options: &CompileOptions,
334 bag: &mut DiagnosticBag,
335 ) -> BTreeSet<String> {
336 let includes = compile_globs(&options.tables, bag);
337 let excludes = compile_globs(&options.exclude, bag);
338 model
339 .tables
340 .keys()
341 .filter(|name| {
342 let included =
343 includes.is_empty() || includes.iter().any(|pattern| pattern.matches(name));
344 let excluded = excludes.iter().any(|pattern| pattern.matches(name));
345 included && !excluded
346 })
347 .cloned()
348 .collect()
349 }
350
351 fn report_excluded_dependencies(
355 &self,
356 selected: &BTreeSet<String>,
357 parents: &BTreeMap<String, BTreeSet<String>>,
358 bag: &mut DiagnosticBag,
359 ) {
360 for start in selected {
361 let mut reported: BTreeSet<String> = BTreeSet::new();
362 let mut visited: BTreeSet<String> = BTreeSet::new();
363 let mut stack: Vec<Vec<String>> = vec![vec![start.clone()]];
364 while let Some(path) = stack.pop() {
365 let node = path.last().expect("path is never empty");
366 let Some(node_parents) = parents.get(node) else {
367 continue;
368 };
369 for parent in node_parents {
370 let mut extended = path.clone();
371 extended.push(parent.clone());
372 if selected.contains(parent) {
373 if visited.insert(parent.clone()) {
374 stack.push(extended);
375 }
376 } else if reported.insert(parent.clone()) {
377 bag.error(
378 crate::diagnostic::codes::EXCLUDED_DEPENDENCY.code,
379 format!("tables.{start}"),
380 format!(
381 "table `{start}` requires excluded table `{parent}` via dependency path {}",
382 extended.join(" -> ")
383 ),
384 );
385 }
386 }
387 }
388 }
389 }
390
391 #[allow(clippy::too_many_arguments)]
393 fn resolve_count(
394 &self,
395 model: &SyntheticModel,
396 name: &str,
397 table: &TableModel,
398 options: &CompileOptions,
399 over: Option<&TableOverride>,
400 rounding_root: SeedRoot,
401 resolved: &BTreeMap<String, u64>,
402 bag: &mut DiagnosticBag,
403 ) -> u64 {
404 match &table.rows {
405 RowsModel::RelationChildren {
406 parent,
407 distribution,
408 ..
409 } => self.resolve_child_count(
410 name,
411 parent,
412 distribution,
413 options,
414 over,
415 rounding_root,
416 resolved,
417 bag,
418 ),
419 rows => self.resolve_root_count(model, name, rows, options, over, rounding_root, bag),
420 }
421 }
422
423 #[allow(clippy::too_many_arguments)]
424 fn resolve_root_count(
425 &self,
426 model: &SyntheticModel,
427 name: &str,
428 rows: &RowsModel,
429 options: &CompileOptions,
430 over: Option<&TableOverride>,
431 rounding_root: SeedRoot,
432 bag: &mut DiagnosticBag,
433 ) -> u64 {
434 if matches!(rows, RowsModel::Observed { .. }) && !has_observed_provenance(model, name) {
435 bag.error(
436 crate::diagnostic::codes::ROWS_OBSERVED_MISSING.code,
437 format!("tables.{name}.rows"),
438 format!(
439 "table `{name}` uses `rows.kind: observed` but the model has no attached source or profile to resolve the observed count from"
440 ),
441 );
442 }
443
444 let base = declared_count(rows).unwrap_or(0) as f64;
445
446 let mut target = match (options.scale, options.rows) {
448 (Some(scale), _) => base * scale,
449 (None, Some(rows)) => rows as f64,
450 (None, None) => base,
451 };
452
453 match over.map(TableOverride::effective) {
456 Some(EffectiveOverride::Rows(rows)) => target = rows as f64,
457 Some(EffectiveOverride::Scale(scale)) => target = base * scale,
458 None | Some(EffectiveOverride::Conflict) => {}
459 }
460
461 let count = stochastic_round(target, rounding_root, name);
462 apply_max_rows(count, options.max_rows, name, bag)
463 }
464
465 #[allow(clippy::too_many_arguments)]
466 fn resolve_child_count(
467 &self,
468 name: &str,
469 parent: &str,
470 distribution: &ChildDistribution,
471 options: &CompileOptions,
472 over: Option<&TableOverride>,
473 rounding_root: SeedRoot,
474 resolved: &BTreeMap<String, u64>,
475 bag: &mut DiagnosticBag,
476 ) -> u64 {
477 let Some(&parent_count) = resolved.get(parent) else {
480 return 0;
481 };
482 let (mean, min, _max) = distribution_bounds(distribution);
483
484 let derived = parent_count as f64 * mean;
487 let target = match over.map(TableOverride::effective) {
488 Some(EffectiveOverride::Rows(rows)) => rows as f64,
489 Some(EffectiveOverride::Scale(scale)) => derived * scale,
490 None | Some(EffectiveOverride::Conflict) => derived,
491 };
492
493 let count = stochastic_round(target, rounding_root, name);
494 let count = apply_max_rows(count, options.max_rows, name, bag);
495
496 let minimum = (parent_count as f64 * min).ceil() as u64;
497 if count < minimum {
498 bag.error(
499 crate::diagnostic::codes::CHILD_COUNT_IMPOSSIBLE.code,
500 format!("tables.{name}.rows"),
501 format!(
502 "table `{name}` resolves to {count} rows, but its {parent_count} parents in `{parent}` each require at least {min} child(ren) ({minimum} total)"
503 ),
504 );
505 }
506 count
507 }
508
509 #[allow(clippy::too_many_arguments)]
514 fn plan_table(
515 &self,
516 model: &SyntheticModel,
517 name: &str,
518 table: &TableModel,
519 rows: u64,
520 root_seed: u64,
521 inference: InferenceMode,
522 family_ctx: &FamilyContext,
523 resolved: &BTreeMap<String, u64>,
524 selected: &BTreeSet<String>,
525 preserve_raw: bool,
526 bag: &mut DiagnosticBag,
527 ) -> PlannedTable {
528 let seed = resolve_seed(&table.seed, root_seed);
529 let compile_seed = seed_root_of(&seed);
530 let mut seen_columns: BTreeSet<&str> = BTreeSet::new();
534 for column in &table.schema.columns {
535 if !seen_columns.insert(column.name.as_str()) {
536 bag.error(
537 crate::diagnostic::codes::DUPLICATE_COLUMN.code,
538 format!("tables.{name}.schema.columns"),
539 format!(
540 "table `{name}` declares column `{}` more than once",
541 column.name
542 ),
543 );
544 }
545 }
546 self.validate_column_operator_arguments(name, table, bag);
547 let mut relationships: Vec<CompiledRelationship> = table
548 .relationships
549 .iter()
550 .map(compile_relationship)
551 .collect();
552 for schema_rel in &table.schema.relationships {
557 if relationships
558 .iter()
559 .any(|existing| existing.columns == schema_rel.columns)
560 {
561 continue;
562 }
563 relationships.push(CompiledRelationship {
564 name: schema_rel.name.clone(),
565 columns: schema_rel.columns.clone(),
566 parent_table: schema_rel.referenced_table.clone(),
567 parent_columns: schema_rel.referenced_columns.clone(),
568 distribution: RelationshipDistribution::default(),
569 null_permille: 0,
570 });
571 }
572 fold_foreign_key_generators(name, table, &mut relationships, bag);
573
574 relationships.retain(|relationship| {
580 if selected.contains(&relationship.parent_table) {
581 return true;
582 }
583 if !fk_columns_all_non_null(table, &relationship.columns) {
584 bag.warning(
585 crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
586 format!("tables.{name}"),
587 format!(
588 "optional relationship `{}` on table `{name}` references excluded table `{}`; its foreign key is detached and omitted from the rendered DDL",
589 relationship.name.as_deref().unwrap_or("(unnamed)"),
590 relationship.parent_table
591 ),
592 );
593 }
594 false
595 });
596
597 for relationship in &relationships {
598 let parent_is_empty = resolved
599 .get(&relationship.parent_table)
600 .is_some_and(|count| *count == 0);
601 if rows > 0 && parent_is_empty && !fk_columns_all_nullable(table, &relationship.columns)
602 {
603 bag.error(
604 crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
605 format!("tables.{name}.relationships"),
606 format!(
607 "table `{name}` resolves to {rows} row(s), but required relationship `{}` targets empty parent table `{}`",
608 relationship.name.as_deref().unwrap_or("(unnamed)"),
609 relationship.parent_table
610 ),
611 );
612 }
613 }
614
615 let planners =
616 self.compile_planners(model, name, table, compile_seed, family_ctx, resolved, bag);
617 let claims = collect_claims(table, &planners);
618
619 let columns: Vec<PlannedColumn> = table
620 .schema
621 .columns
622 .iter()
623 .map(|column| {
624 let owner = self.resolve_owner(
625 name,
626 table,
627 column,
628 claims.get(&column.name).map(Vec::as_slice).unwrap_or(&[]),
629 &planners,
630 family_ctx,
631 compile_seed,
632 inference,
633 bag,
634 );
635 let modifiers =
636 self.compile_modifiers(name, table, column, &owner, compile_seed, bag);
637 PlannedColumn {
638 schema: column.clone(),
639 owner,
640 modifiers,
641 }
642 })
643 .collect();
644
645 report_dependency_cycles(name, table, &columns, &planners, bag);
646 let eval_order = column_eval_order(table, &columns);
647
648 let compiled_planners = planners.into_iter().filter_map(|p| p.compiled).collect();
653
654 let present_columns: BTreeSet<&str> = table
661 .schema
662 .columns
663 .iter()
664 .map(|c| c.name.as_str())
665 .collect();
666 let mut schema = table.schema.clone();
667 schema
668 .relationships
669 .retain(|relationship| selected.contains(&relationship.referenced_table));
670 schema.indexes.retain(|index| {
671 index
672 .columns
673 .iter()
674 .all(|c| present_columns.contains(c.as_str()))
675 });
676 if !preserve_raw {
677 schema.create_statement = None;
678 }
679
680 PlannedTable {
681 name: name.to_string(),
682 rows,
683 schema,
684 seed,
685 columns,
686 relationships,
687 planners: compiled_planners,
688 eval_order,
689 }
690 }
691
692 #[allow(clippy::too_many_arguments)]
695 fn compile_planners(
696 &self,
697 model: &SyntheticModel,
698 table_name: &str,
699 table: &TableModel,
700 seed: SeedRoot,
701 family_ctx: &FamilyContext,
702 resolved: &BTreeMap<String, u64>,
703 bag: &mut DiagnosticBag,
704 ) -> Vec<PlannerInfo> {
705 let relationship_names = relationship_names(table);
706 let relation_facts = build_relation_facts(model, table, resolved);
714 table
715 .planners
716 .iter()
717 .enumerate()
718 .map(|(index, config)| {
719 let path = format!("tables.{table_name}.planners[{index}]");
720 let Some(factory) = self.registry.planner(&config.kind) else {
721 bag.error(
722 crate::diagnostic::codes::PLANNER_UNKNOWN.code,
723 path,
724 format!("no planner registered for kind `{}`", config.kind),
725 );
726 return PlannerInfo::unresolved(&config.kind);
727 };
728 let descriptor = factory.descriptor();
729 validate_operator_arguments(
730 &config.args,
731 descriptor.arguments,
732 &path,
733 "planner",
734 &config.kind,
735 bag,
736 );
737 let is_family = config.args.contains_key("children");
742 let is_cross_table = descriptor.cross_table;
743 let injected;
744 let config = if let Some(facts) = family_ctx.facts.get(&(table_name.to_string(), index)) {
745 let mut cloned = config.clone();
746 cloned.args.insert(
747 super::planners::order_family::FAMILY_FACTS_KEY.to_string(),
748 facts.clone(),
749 );
750 injected = cloned;
751 &injected
752 } else if !is_family
753 && (is_cross_table || config.args.contains_key("relationship"))
754 {
755 let mut cloned = config.clone();
763 cloned.args.insert(
764 super::planners::structural::RELATION_FACTS_KEY.to_string(),
765 relation_facts.clone(),
766 );
767 injected = cloned;
768 &injected
769 } else {
770 config
771 };
772 let writes = match descriptor.writes {
773 ColumnScope::Configured => configured_columns(config, &["columns", "writes"]),
774 _ => Vec::new(),
775 };
776 let reads = match descriptor.reads {
777 ColumnScope::Configured => configured_columns(config, &["reads"]),
778 _ => Vec::new(),
779 };
780
781 if !is_family {
782 if let Some(referenced) = string_arg(config, "relationship") {
783 if !relationship_names.iter().any(|n| n == referenced) {
784 bag.error(
785 crate::diagnostic::codes::RELATIONSHIP_UNKNOWN.code,
786 format!("{path}.relationship"),
787 format!(
788 "planner `{}` references relationship `{referenced}`, which is not declared on table `{table_name}`",
789 config.kind
790 ),
791 );
792 }
793 }
794 }
795
796 let context = CompileContext::for_table(&table.schema, seed, &path);
797 let compiled = match factory.compile(config, &context) {
798 Ok(compiled) => Some(compiled),
799 Err(errors) => {
800 bag.diagnostics.extend(errors.diagnostics);
801 None
802 }
803 };
804
805 PlannerInfo {
806 kind: descriptor.kind.to_string(),
807 writes,
808 reads,
809 compiled,
810 }
811 })
812 .collect()
813 }
814
815 fn validate_column_operator_arguments(
819 &self,
820 table_name: &str,
821 table: &TableModel,
822 bag: &mut DiagnosticBag,
823 ) {
824 for (column_name, rule) in &table.columns {
825 if let Some(config) = &rule.generator {
826 if let Some(factory) = self.registry.generator(&config.kind) {
827 validate_operator_arguments(
828 &config.args,
829 factory.descriptor().arguments,
830 &format!("tables.{table_name}.columns.{column_name}.generator"),
831 "generator",
832 &config.kind,
833 bag,
834 );
835 }
836 }
837 for (index, config) in rule.modifiers.iter().enumerate() {
838 if let Some(factory) = self.registry.modifier(&config.kind) {
839 validate_operator_arguments(
840 &config.args,
841 factory.descriptor().arguments,
842 &format!("tables.{table_name}.columns.{column_name}.modifiers[{index}]"),
843 "modifier",
844 &config.kind,
845 bag,
846 );
847 }
848 }
849 }
850 }
851
852 #[allow(clippy::too_many_arguments)]
854 fn resolve_owner(
855 &self,
856 table_name: &str,
857 table: &TableModel,
858 column: &PortableColumn,
859 claimants: &[Claim],
860 planners: &[PlannerInfo],
861 family_ctx: &FamilyContext,
862 seed: SeedRoot,
863 inference: InferenceMode,
864 bag: &mut DiagnosticBag,
865 ) -> ColumnOwner {
866 if claimants.len() > 1 {
867 let diagnostic = bag.error(
868 crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
869 format!("tables.{table_name}.columns.{}", column.name),
870 format!(
871 "tables.{table_name}.columns.{} is produced by more than one owner",
872 column.name
873 ),
874 );
875 diagnostic.related = claimants
876 .iter()
877 .map(|claim| SourceLocation {
878 path: claim.path.clone(),
879 description: claim.description.clone(),
880 })
881 .collect();
882 diagnostic.help = Some(format!(
883 "keep a single owner for `{}`: remove the column generator or drop it from the planner mapping",
884 column.name
885 ));
886 return ColumnOwner::GeneratedByDatabase;
887 }
888
889 if let Some(claim) = claimants.first() {
890 return match &claim.source {
891 ClaimSource::Generator => {
892 self.compile_generator(table_name, table, column, seed, bag)
893 }
894 ClaimSource::Planner { index } => ColumnOwner::Planner {
895 kind: planners[*index].kind.clone(),
896 planner_index: *index,
897 },
898 };
899 }
900
901 if let Some(external) = family_ctx
904 .external_owners
905 .get(&(table_name.to_string(), column.name.clone()))
906 {
907 return ColumnOwner::FamilyChild {
908 planner_kind: external.planner_kind.clone(),
909 };
910 }
911
912 self.infer_structural_owner(table_name, table, column, inference, seed, bag)
913 }
914
915 fn compile_generator(
917 &self,
918 table_name: &str,
919 table: &TableModel,
920 column: &PortableColumn,
921 seed: SeedRoot,
922 bag: &mut DiagnosticBag,
923 ) -> ColumnOwner {
924 let path = format!("tables.{table_name}.columns.{}.generator", column.name);
925 let config = table.columns[&column.name]
926 .generator
927 .as_ref()
928 .expect("generator claim implies a generator rule");
929 self.compile_generator_config(table, column, config, path, seed, bag)
930 }
931
932 fn compile_generator_config(
936 &self,
937 table: &TableModel,
938 column: &PortableColumn,
939 config: &crate::synthetic::model::GeneratorConfig,
940 path: String,
941 seed: SeedRoot,
942 bag: &mut DiagnosticBag,
943 ) -> ColumnOwner {
944 let Some(factory) = self.registry.generator(&config.kind) else {
945 bag.error(
946 crate::diagnostic::codes::GENERATOR_UNKNOWN.code,
947 path,
948 format!("no generator registered for kind `{}`", config.kind),
949 );
950 return ColumnOwner::GeneratedByDatabase;
951 };
952 let descriptor = factory.descriptor();
953
954 if !descriptor.accepts.contains(&column.family) {
955 bag.error(
956 crate::diagnostic::codes::GENERATOR_TYPE.code,
957 path,
958 format!(
959 "generator `{}` cannot produce column `{}` of type family {:?}",
960 config.kind, column.name, column.family
961 ),
962 );
963 return ColumnOwner::GeneratedByDatabase;
964 }
965
966 let context = CompileContext::for_column(&table.schema, column, seed, &path);
967 match factory.compile(config, &context) {
968 Ok(compiled) => ColumnOwner::Generator {
969 kind: descriptor.kind.to_string(),
970 compiled,
971 },
972 Err(errors) => {
973 bag.diagnostics.extend(errors.diagnostics);
974 ColumnOwner::GeneratedByDatabase
975 }
976 }
977 }
978
979 fn infer_structural_owner(
983 &self,
984 table_name: &str,
985 table: &TableModel,
986 column: &PortableColumn,
987 inference: InferenceMode,
988 seed: SeedRoot,
989 bag: &mut DiagnosticBag,
990 ) -> ColumnOwner {
991 if column.generated || column.identity {
995 return ColumnOwner::GeneratedByDatabase;
996 }
997 if foreign_key_columns(table).contains(&column.name) {
998 return ColumnOwner::Relationship {
999 relationship: relationship_of(table, &column.name),
1000 };
1001 }
1002 if column.default_sql.is_some() {
1003 return ColumnOwner::DatabaseDefault;
1004 }
1005
1006 if matches!(inference, InferenceMode::Schema)
1017 && column.primary_key
1018 && matches!(
1019 column.family,
1020 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
1021 )
1022 {
1023 return ColumnOwner::GeneratedByDatabase;
1024 }
1025
1026 match inference {
1035 InferenceMode::Schema => {
1036 let config =
1037 crate::profile::heuristics::schema_inferred_generator(&table.schema, column);
1038 let path = format!(
1039 "tables.{table_name}.columns.{}.generator[inferred]",
1040 column.name
1041 );
1042 self.compile_generator_config(table, column, &config, path, seed, bag)
1043 }
1044 InferenceMode::Disabled => {
1045 bag.error(
1046 crate::diagnostic::codes::COLUMN_OWNER_MISSING.code,
1047 format!("tables.{table_name}.columns.{}", column.name),
1048 format!(
1049 "column `{}` on table `{table_name}` has no generator, planner, relationship, or database default to produce its value",
1050 column.name
1051 ),
1052 );
1053 ColumnOwner::GeneratedByDatabase
1054 }
1055 }
1056 }
1057
1058 fn compile_modifiers(
1069 &self,
1070 table_name: &str,
1071 table: &TableModel,
1072 column: &PortableColumn,
1073 owner: &ColumnOwner,
1074 seed: SeedRoot,
1075 bag: &mut DiagnosticBag,
1076 ) -> Vec<Box<dyn CompiledModifier>> {
1077 let empty_rule;
1082 let rule = match table.columns.get(&column.name) {
1083 Some(rule) => rule,
1084 None => {
1085 empty_rule = crate::synthetic::model::ColumnRule {
1086 semantic: None,
1087 generator: None,
1088 modifiers: Vec::new(),
1089 };
1090 &empty_rule
1091 }
1092 };
1093 let is_generator = matches!(owner, ColumnOwner::Generator { .. });
1094 let mut compiled: Vec<Box<dyn CompiledModifier>> = Vec::new();
1095 for (index, modifier) in rule.modifiers.iter().enumerate() {
1096 let path = format!(
1097 "tables.{table_name}.columns.{}.modifiers[{index}]",
1098 column.name
1099 );
1100 let Some(factory) = self.registry.modifier(&modifier.kind) else {
1101 bag.error(
1102 crate::diagnostic::codes::MODIFIER_UNKNOWN.code,
1103 path,
1104 format!("no modifier registered for kind `{}`", modifier.kind),
1105 );
1106 continue;
1107 };
1108 if !factory.descriptor().accepts.contains(&column.family) {
1109 bag.error(
1110 crate::diagnostic::codes::MODIFIER_TYPE.code,
1111 path,
1112 format!(
1113 "modifier `{}` cannot transform column `{}` of type family {:?}",
1114 modifier.kind, column.name, column.family
1115 ),
1116 );
1117 continue;
1118 }
1119 if !is_generator {
1120 continue;
1121 }
1122 let context = CompileContext::for_column(&table.schema, column, seed, &path);
1123 match factory.compile(modifier, &context) {
1124 Ok(operator) => compiled.push(operator),
1125 Err(errors) => bag.diagnostics.extend(errors.diagnostics),
1126 }
1127 }
1128
1129 self.enforce_key_uniqueness(
1130 table_name,
1131 table,
1132 column,
1133 owner,
1134 rule,
1135 seed,
1136 &mut compiled,
1137 bag,
1138 );
1139
1140 compiled
1141 }
1142
1143 #[allow(clippy::too_many_arguments)]
1156 fn enforce_key_uniqueness(
1157 &self,
1158 table_name: &str,
1159 table: &TableModel,
1160 column: &PortableColumn,
1161 owner: &ColumnOwner,
1162 rule: &crate::synthetic::model::ColumnRule,
1163 seed: SeedRoot,
1164 compiled: &mut Vec<Box<dyn CompiledModifier>>,
1165 bag: &mut DiagnosticBag,
1166 ) {
1167 let ColumnOwner::Generator {
1168 compiled: generator,
1169 ..
1170 } = owner
1171 else {
1172 return;
1173 };
1174 if !is_single_column_key(&table.schema, column) {
1175 return;
1176 }
1177 if generator.is_inherently_unique() {
1178 return;
1179 }
1180 if rule
1183 .modifiers
1184 .iter()
1185 .any(|modifier| modifier.kind == "unique")
1186 {
1187 return;
1188 }
1189 let Some(factory) = self.registry.modifier("unique") else {
1190 return;
1191 };
1192 let path = format!(
1193 "tables.{table_name}.columns.{}.modifiers[auto-unique]",
1194 column.name
1195 );
1196 let config = ModifierConfig {
1197 kind: "unique".to_string(),
1198 args: [(
1199 "on_exhaustion".to_string(),
1200 serde_yaml_ng::Value::from("error"),
1201 )]
1202 .into_iter()
1203 .collect(),
1204 };
1205 let context = CompileContext::for_column(&table.schema, column, seed, &path);
1206 match factory.compile(&config, &context) {
1207 Ok(operator) => compiled.push(operator),
1208 Err(errors) => bag.diagnostics.extend(errors.diagnostics),
1209 }
1210 }
1211}
1212
1213fn validate_operator_arguments(
1217 args: &BTreeMap<String, serde_yaml_ng::Value>,
1218 expected: &[super::registry::ArgumentSpec],
1219 path: &str,
1220 operator_type: &str,
1221 kind: &str,
1222 bag: &mut DiagnosticBag,
1223) {
1224 for argument in args.keys() {
1225 if expected.iter().any(|spec| spec.name == argument) {
1226 continue;
1227 }
1228 let diagnostic = bag.error(
1229 crate::diagnostic::codes::OPERATOR_UNKNOWN_ARGUMENT.code,
1230 format!("{path}.{argument}"),
1231 format!("{operator_type} `{kind}` does not accept argument `{argument}`"),
1232 );
1233 if !expected.is_empty() {
1234 diagnostic.help = Some(format!(
1235 "supported arguments: {}",
1236 expected
1237 .iter()
1238 .map(|spec| spec.name)
1239 .collect::<Vec<_>>()
1240 .join(", ")
1241 ));
1242 }
1243 }
1244}
1245
1246fn primary_key_columns(table: &PortableTable) -> BTreeSet<&str> {
1249 let mut columns: BTreeSet<&str> = table.primary_key.iter().map(String::as_str).collect();
1250 columns.extend(
1251 table
1252 .columns
1253 .iter()
1254 .filter(|column| column.primary_key)
1255 .map(|column| column.name.as_str()),
1256 );
1257 columns
1258}
1259
1260fn is_single_column_key(table: &PortableTable, column: &PortableColumn) -> bool {
1266 let primary = primary_key_columns(table);
1267 if primary.len() == 1 && primary.contains(column.name.as_str()) {
1268 return true;
1269 }
1270 if column.unique {
1271 return true;
1272 }
1273 let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
1274 table
1275 .unique_constraints
1276 .iter()
1277 .any(|constraint| single(&constraint.columns))
1278 || table
1279 .indexes
1280 .iter()
1281 .any(|index| index.unique && single(&index.columns))
1282}
1283
1284#[derive(Debug, Default, Clone, Copy)]
1286struct TableOverride {
1287 rows: Option<u64>,
1288 scale: Option<f64>,
1289}
1290
1291enum EffectiveOverride {
1293 Rows(u64),
1294 Scale(f64),
1295 Conflict,
1296}
1297
1298impl TableOverride {
1299 fn effective(&self) -> EffectiveOverride {
1300 match (self.rows, self.scale) {
1301 (Some(_), Some(_)) => EffectiveOverride::Conflict,
1302 (Some(rows), None) => EffectiveOverride::Rows(rows),
1303 (None, Some(scale)) => EffectiveOverride::Scale(scale),
1304 (None, None) => EffectiveOverride::Conflict,
1305 }
1306 }
1307}
1308
1309fn apply_max_rows(count: u64, max_rows: Option<u64>, name: &str, bag: &mut DiagnosticBag) -> u64 {
1312 match max_rows {
1313 Some(max) if count > max => {
1314 bag.warning(
1315 crate::diagnostic::codes::MAX_ROWS_CAPPED.code,
1316 format!("tables.{name}.rows"),
1317 format!("table `{name}` row count capped from {count} to {max} by `--max-rows`"),
1318 );
1319 max
1320 }
1321 _ => count,
1322 }
1323}
1324
1325fn stochastic_round(value: f64, root: SeedRoot, table: &str) -> u64 {
1328 if value <= 0.0 {
1329 return 0;
1330 }
1331 let floor = value.floor();
1332 let fraction = value - floor;
1333 let mut count = floor as u64;
1334 if fraction > 0.0 {
1335 let mut rng = root.stream(StreamId::rounding(table));
1336 if rng.random::<f64>() < fraction {
1337 count += 1;
1338 }
1339 }
1340 count
1341}
1342
1343fn declared_count(rows: &RowsModel) -> Option<u64> {
1346 match rows {
1347 RowsModel::Fixed { count }
1348 | RowsModel::Observed { count }
1349 | RowsModel::Scale { count, .. } => Some(*count),
1350 RowsModel::RelationChildren { .. } => None,
1351 }
1352}
1353
1354fn distribution_kind(distribution: &ChildDistribution) -> &'static str {
1357 match distribution {
1358 ChildDistribution::Observed { .. } => "observed",
1359 ChildDistribution::Fixed { .. } => "fixed",
1360 ChildDistribution::Uniform { .. } => "uniform",
1361 ChildDistribution::Poisson { .. } => "poisson",
1362 ChildDistribution::Histogram { .. } => "histogram",
1363 }
1364}
1365
1366fn distribution_bounds(distribution: &ChildDistribution) -> (f64, f64, f64) {
1368 match distribution {
1369 ChildDistribution::Observed { mean, min, max }
1370 | ChildDistribution::Fixed { mean, min, max }
1371 | ChildDistribution::Uniform { mean, min, max }
1372 | ChildDistribution::Poisson { mean, min, max }
1373 | ChildDistribution::Histogram { mean, min, max } => (*mean, *min, *max),
1374 }
1375}
1376
1377fn has_observed_provenance(model: &SyntheticModel, table: &str) -> bool {
1379 model.source.is_some()
1380 || model
1381 .profiles
1382 .keys()
1383 .filter_map(|key| key.split_once('.'))
1384 .any(|(profiled_table, _)| profiled_table == table)
1385}
1386
1387#[derive(Clone, Copy, PartialEq, Eq)]
1389enum EdgeKind {
1390 All,
1393 Required,
1397}
1398
1399fn fk_columns_all_non_null(table: &TableModel, columns: &[String]) -> bool {
1403 columns.iter().all(|column| {
1404 table
1405 .schema
1406 .columns
1407 .iter()
1408 .find(|candidate| &candidate.name == column)
1409 .map(|candidate| !candidate.nullable)
1410 .unwrap_or(true)
1411 })
1412}
1413
1414fn fk_columns_all_nullable(table: &TableModel, columns: &[String]) -> bool {
1417 columns.iter().all(|column| {
1418 table
1419 .schema
1420 .columns
1421 .iter()
1422 .find(|candidate| &candidate.name == column)
1423 .is_some_and(|candidate| candidate.nullable)
1424 })
1425}
1426
1427fn parent_edges(model: &SyntheticModel, kind: EdgeKind) -> BTreeMap<String, BTreeSet<String>> {
1433 model
1434 .tables
1435 .iter()
1436 .map(|(name, table)| {
1437 let generation = table
1438 .relationships
1439 .iter()
1440 .map(|relationship| (relationship.references.table.clone(), &relationship.columns));
1441 let schema =
1442 table.schema.relationships.iter().map(|relationship| {
1443 (relationship.referenced_table.clone(), &relationship.columns)
1444 });
1445 let mut parents: BTreeSet<String> = BTreeSet::new();
1446 for (parent, columns) in generation.chain(schema) {
1447 if kind == EdgeKind::All || fk_columns_all_non_null(table, columns) {
1448 parents.insert(parent);
1449 }
1450 }
1451 if let RowsModel::RelationChildren { parent, .. } = &table.rows {
1452 parents.insert(parent.clone());
1453 }
1454 for planner in &table.planners {
1458 if let Some(serde_yaml_ng::Value::Sequence(items)) = planner.args.get("targets") {
1459 for item in items {
1460 if let Some(target) =
1461 item.get("table").and_then(serde_yaml_ng::Value::as_str)
1462 {
1463 parents.insert(target.to_string());
1464 }
1465 }
1466 }
1467 }
1468 parents.remove(name);
1470 (name.clone(), parents)
1471 })
1472 .collect()
1473}
1474
1475fn topo_order(
1483 selected: &BTreeSet<String>,
1484 parents: &BTreeMap<String, BTreeSet<String>>,
1485) -> (Vec<String>, Vec<String>) {
1486 let mut in_degree: BTreeMap<String, usize> = BTreeMap::new();
1487 let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
1488 for name in selected {
1489 let selected_parents: Vec<&String> = parents
1490 .get(name)
1491 .into_iter()
1492 .flatten()
1493 .filter(|parent| selected.contains(*parent))
1494 .collect();
1495 in_degree.insert(name.clone(), selected_parents.len());
1496 for parent in selected_parents {
1497 children
1498 .entry(parent.clone())
1499 .or_default()
1500 .push(name.clone());
1501 }
1502 }
1503
1504 let mut queue: Vec<String> = in_degree
1508 .iter()
1509 .filter(|(_, °ree)| degree == 0)
1510 .map(|(name, _)| name.clone())
1511 .collect();
1512 queue.sort();
1513 queue.reverse();
1514 let mut order: Vec<String> = Vec::with_capacity(selected.len());
1515 while let Some(name) = queue.pop() {
1516 order.push(name.clone());
1517 if let Some(kids) = children.get(&name) {
1518 for kid in kids {
1519 let degree = in_degree.get_mut(kid).expect("child has an in-degree");
1520 *degree -= 1;
1521 if *degree == 0 {
1522 queue.push(kid.clone());
1523 }
1524 }
1525 }
1526 queue.sort();
1527 queue.reverse();
1528 }
1529
1530 let cyclic: Vec<String> = selected
1532 .iter()
1533 .filter(|name| !order.contains(name))
1534 .cloned()
1535 .collect();
1536 (order, cyclic)
1537}
1538
1539struct PlannerInfo {
1543 kind: String,
1544 writes: Vec<String>,
1545 reads: Vec<String>,
1546 compiled: Option<Box<dyn CompiledPlanner>>,
1547}
1548
1549impl PlannerInfo {
1550 fn unresolved(kind: &str) -> Self {
1552 Self {
1553 kind: kind.to_string(),
1554 writes: Vec::new(),
1555 reads: Vec::new(),
1556 compiled: None,
1557 }
1558 }
1559}
1560
1561struct Claim {
1563 source: ClaimSource,
1564 path: String,
1565 description: Option<String>,
1566}
1567
1568enum ClaimSource {
1570 Generator,
1572 Planner { index: usize },
1574}
1575
1576fn collect_claims(table: &TableModel, planners: &[PlannerInfo]) -> BTreeMap<String, Vec<Claim>> {
1580 let mut claims: BTreeMap<String, Vec<Claim>> = BTreeMap::new();
1581 for (name, rule) in &table.columns {
1582 if rule.generator.is_some() {
1583 claims.entry(name.clone()).or_default().push(Claim {
1584 source: ClaimSource::Generator,
1585 path: format!("columns.{name}.generator"),
1586 description: None,
1587 });
1588 }
1589 }
1590 for (index, planner) in planners.iter().enumerate() {
1591 let mut claimed: BTreeSet<&str> = BTreeSet::new();
1595 for column in &planner.writes {
1596 if !claimed.insert(column.as_str()) {
1597 continue;
1598 }
1599 claims.entry(column.clone()).or_default().push(Claim {
1600 source: ClaimSource::Planner { index },
1601 path: format!("planners[{index}]"),
1602 description: Some(planner.kind.clone()),
1603 });
1604 }
1605 }
1606 claims
1607}
1608
1609fn configured_columns(config: &PlannerConfig, keys: &[&str]) -> Vec<String> {
1613 let mut columns = Vec::new();
1614 for key in keys {
1615 match config.args.get(*key) {
1616 Some(serde_yaml_ng::Value::Sequence(items)) => columns.extend(
1617 items
1618 .iter()
1619 .filter_map(serde_yaml_ng::Value::as_str)
1620 .map(str::to_string),
1621 ),
1622 Some(serde_yaml_ng::Value::Mapping(map)) => columns.extend(
1623 map.values()
1624 .filter_map(serde_yaml_ng::Value::as_str)
1625 .map(str::to_string),
1626 ),
1627 _ => {}
1628 }
1629 }
1630 columns
1631}
1632
1633fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
1635 config.args.get(key).and_then(serde_yaml_ng::Value::as_str)
1636}
1637
1638fn relationship_names(table: &TableModel) -> Vec<String> {
1641 table
1642 .relationships
1643 .iter()
1644 .filter_map(|relationship| relationship.name.clone())
1645 .chain(
1646 table
1647 .schema
1648 .relationships
1649 .iter()
1650 .filter_map(|relationship| relationship.name.clone()),
1651 )
1652 .collect()
1653}
1654
1655fn foreign_key_columns(table: &TableModel) -> BTreeSet<String> {
1658 table
1659 .relationships
1660 .iter()
1661 .flat_map(|relationship| relationship.columns.iter().cloned())
1662 .chain(
1663 table
1664 .schema
1665 .relationships
1666 .iter()
1667 .flat_map(|relationship| relationship.columns.iter().cloned()),
1668 )
1669 .collect()
1670}
1671
1672fn relationship_of(table: &TableModel, column: &str) -> Option<String> {
1674 table
1675 .relationships
1676 .iter()
1677 .find(|relationship| relationship.columns.iter().any(|c| c == column))
1678 .and_then(|relationship| relationship.name.clone())
1679 .or_else(|| {
1680 table
1681 .schema
1682 .relationships
1683 .iter()
1684 .find(|relationship| relationship.columns.iter().any(|c| c == column))
1685 .and_then(|relationship| relationship.name.clone())
1686 })
1687}
1688
1689fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
1691 match seed {
1692 ResolvedTableSeed::Inherited(root)
1693 | ResolvedTableSeed::Fixed(root)
1694 | ResolvedTableSeed::Random(root) => *root,
1695 }
1696}
1697
1698#[derive(Clone, PartialEq, Eq)]
1700enum DepNode {
1701 Column(String),
1702 Planner(usize),
1703}
1704
1705fn report_dependency_cycles(
1710 table_name: &str,
1711 table: &TableModel,
1712 columns: &[PlannedColumn],
1713 planners: &[PlannerInfo],
1714 bag: &mut DiagnosticBag,
1715) {
1716 let mut nodes: Vec<DepNode> = columns
1717 .iter()
1718 .map(|column| DepNode::Column(column.schema.name.clone()))
1719 .collect();
1720 nodes.extend((0..planners.len()).map(DepNode::Planner));
1721
1722 let index_of = |node: &DepNode| nodes.iter().position(|candidate| candidate == node);
1723 let mut edges: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
1724 let add_edge = |from: &DepNode, to: &DepNode, edges: &mut Vec<Vec<usize>>| {
1725 if let (Some(from), Some(to)) = (index_of(from), index_of(to)) {
1726 edges[from].push(to);
1727 }
1728 };
1729
1730 for planned in columns {
1732 if matches!(planned.owner, ColumnOwner::Generator { .. }) {
1733 for read in generator_reads(table, &planned.schema.name) {
1734 add_edge(
1735 &DepNode::Column(read),
1736 &DepNode::Column(planned.schema.name.clone()),
1737 &mut edges,
1738 );
1739 }
1740 }
1741 }
1742 for (index, planner) in planners.iter().enumerate() {
1745 for read in &planner.reads {
1746 add_edge(
1747 &DepNode::Column(read.clone()),
1748 &DepNode::Planner(index),
1749 &mut edges,
1750 );
1751 }
1752 for write in &planner.writes {
1753 add_edge(
1754 &DepNode::Planner(index),
1755 &DepNode::Column(write.clone()),
1756 &mut edges,
1757 );
1758 }
1759 }
1760
1761 for component in strongly_connected_components(&edges) {
1762 let self_loop = component.len() == 1 && edges[component[0]].contains(&component[0]);
1763 if component.len() <= 1 && !self_loop {
1764 continue;
1765 }
1766 let cycle_columns: Vec<String> = component
1767 .iter()
1768 .filter_map(|&node| match &nodes[node] {
1769 DepNode::Column(name) => Some(name.clone()),
1770 DepNode::Planner(_) => None,
1771 })
1772 .collect();
1773 if owned_by_single_planner(&cycle_columns, columns) {
1774 continue;
1775 }
1776 bag.error(
1777 crate::diagnostic::codes::COLUMN_CYCLE.code,
1778 format!("tables.{table_name}.columns"),
1779 format!(
1780 "columns on table `{table_name}` form a read/write dependency cycle: {}",
1781 cycle_columns.join(", ")
1782 ),
1783 );
1784 }
1785}
1786
1787fn column_eval_order(table: &TableModel, columns: &[PlannedColumn]) -> Vec<usize> {
1798 let n = columns.len();
1799 let index_of: BTreeMap<&str, usize> = columns
1800 .iter()
1801 .enumerate()
1802 .map(|(index, column)| (column.schema.name.as_str(), index))
1803 .collect();
1804
1805 let mut successors: Vec<Vec<usize>> = vec![Vec::new(); n];
1806 let mut in_degree = vec![0usize; n];
1807 for (reader, column) in columns.iter().enumerate() {
1808 if !matches!(column.owner, ColumnOwner::Generator { .. }) {
1809 continue;
1810 }
1811 for read in generator_reads(table, &column.schema.name) {
1812 if let Some(&source) = index_of.get(read.as_str()) {
1813 if source != reader {
1814 successors[source].push(reader);
1815 in_degree[reader] += 1;
1816 }
1817 }
1818 }
1819 }
1820
1821 let mut ready: BinaryHeap<Reverse<usize>> = (0..n)
1824 .filter(|&index| in_degree[index] == 0)
1825 .map(Reverse)
1826 .collect();
1827 let mut order = Vec::with_capacity(n);
1828 while let Some(Reverse(node)) = ready.pop() {
1829 order.push(node);
1830 for &next in &successors[node] {
1831 in_degree[next] -= 1;
1832 if in_degree[next] == 0 {
1833 ready.push(Reverse(next));
1834 }
1835 }
1836 }
1837
1838 if order.len() < n {
1841 let mut placed = vec![false; n];
1842 for &node in &order {
1843 placed[node] = true;
1844 }
1845 for (node, &is_placed) in placed.iter().enumerate() {
1846 if !is_placed {
1847 order.push(node);
1848 }
1849 }
1850 }
1851 order
1852}
1853
1854fn generator_reads(table: &TableModel, column: &str) -> Vec<String> {
1868 let Some(config) = table
1869 .columns
1870 .get(column)
1871 .and_then(|rule| rule.generator.as_ref())
1872 else {
1873 return Vec::new();
1874 };
1875
1876 let mut reads = Vec::new();
1877 let mut push = |name: &str| {
1878 let name = name.to_string();
1879 if !reads.contains(&name) {
1880 reads.push(name);
1881 }
1882 };
1883
1884 if let Some(serde_yaml_ng::Value::Sequence(items)) = config.args.get("reads") {
1885 for name in items.iter().filter_map(serde_yaml_ng::Value::as_str) {
1886 push(name);
1887 }
1888 }
1889
1890 match config.kind.as_str() {
1891 "copy" | "slug" | "before" | "after" => {
1892 if let Some(source) = config
1893 .args
1894 .get("source")
1895 .and_then(serde_yaml_ng::Value::as_str)
1896 {
1897 push(source);
1898 }
1899 }
1900 "template" => {
1901 if let Some(serde_yaml_ng::Value::Sequence(parts)) = config.args.get("parts") {
1902 for part in parts {
1903 if let Some(field) = part.get("field").and_then(serde_yaml_ng::Value::as_str) {
1904 push(field);
1905 }
1906 }
1907 }
1908 }
1909 _ => {}
1910 }
1911
1912 reads
1913}
1914
1915fn owned_by_single_planner(cycle_columns: &[String], columns: &[PlannedColumn]) -> bool {
1917 let mut planner: Option<usize> = None;
1918 for name in cycle_columns {
1919 let owner = columns
1920 .iter()
1921 .find(|planned| &planned.schema.name == name)
1922 .map(|planned| &planned.owner);
1923 match owner {
1924 Some(ColumnOwner::Planner { planner_index, .. }) => {
1925 if planner.is_some_and(|existing| existing != *planner_index) {
1926 return false;
1927 }
1928 planner = Some(*planner_index);
1929 }
1930 _ => return false,
1931 }
1932 }
1933 planner.is_some()
1934}
1935
1936fn strongly_connected_components(edges: &[Vec<usize>]) -> Vec<Vec<usize>> {
1939 struct State<'a> {
1940 edges: &'a [Vec<usize>],
1941 index: usize,
1942 indices: Vec<Option<usize>>,
1943 low: Vec<usize>,
1944 on_stack: Vec<bool>,
1945 stack: Vec<usize>,
1946 components: Vec<Vec<usize>>,
1947 }
1948
1949 fn connect(state: &mut State, v: usize) {
1950 state.indices[v] = Some(state.index);
1951 state.low[v] = state.index;
1952 state.index += 1;
1953 state.stack.push(v);
1954 state.on_stack[v] = true;
1955
1956 for &w in &state.edges[v] {
1957 match state.indices[w] {
1958 None => {
1959 connect(state, w);
1960 state.low[v] = state.low[v].min(state.low[w]);
1961 }
1962 Some(w_index) if state.on_stack[w] => {
1963 state.low[v] = state.low[v].min(w_index);
1964 }
1965 Some(_) => {}
1966 }
1967 }
1968
1969 if state.low[v] == state.indices[v].expect("v was assigned an index") {
1970 let mut component = Vec::new();
1971 while let Some(w) = state.stack.pop() {
1972 state.on_stack[w] = false;
1973 component.push(w);
1974 if w == v {
1975 break;
1976 }
1977 }
1978 state.components.push(component);
1979 }
1980 }
1981
1982 let n = edges.len();
1983 let mut state = State {
1984 edges,
1985 index: 0,
1986 indices: vec![None; n],
1987 low: vec![0; n],
1988 on_stack: vec![false; n],
1989 stack: Vec::new(),
1990 components: Vec::new(),
1991 };
1992 for v in 0..n {
1993 if state.indices[v].is_none() {
1994 connect(&mut state, v);
1995 }
1996 }
1997 state.components
1998}
1999
2000#[derive(Default)]
2007struct FamilyContext {
2008 facts: BTreeMap<(String, usize), serde_yaml_ng::Value>,
2010 external_owners: BTreeMap<(String, String), ExternalChildOwner>,
2012 families: Vec<FamilyMembership>,
2014}
2015
2016struct ExternalChildOwner {
2018 planner_kind: String,
2019}
2020
2021struct FamilyMembership {
2023 parent: String,
2024 child: String,
2025}
2026
2027fn is_family_producer(registry: &ExtensionRegistry, config: &PlannerConfig) -> bool {
2037 registry
2038 .planner(&config.kind)
2039 .is_some_and(|factory| factory.descriptor().cross_table)
2040 && config.args.contains_key("children")
2041}
2042
2043impl ModelCompiler {
2044 fn collect_family_facts(
2053 &self,
2054 model: &SyntheticModel,
2055 bag: &mut DiagnosticBag,
2056 ) -> FamilyContext {
2057 collect_family_facts(&self.registry, model, bag)
2058 }
2059}
2060
2061fn collect_family_facts(
2062 registry: &ExtensionRegistry,
2063 model: &SyntheticModel,
2064 bag: &mut DiagnosticBag,
2065) -> FamilyContext {
2066 let mut ctx = FamilyContext::default();
2067 for (parent_name, table) in &model.tables {
2068 for (index, config) in table.planners.iter().enumerate() {
2069 if !is_family_producer(registry, config) {
2070 continue;
2071 }
2072 let child_name = config.args.get("children").and_then(|v| v.as_str());
2073 let child = child_name.and_then(|name| model.tables.get(name).map(|t| (name, t)));
2074
2075 let mut facts = serde_yaml_ng::Mapping::new();
2076 facts.insert("child_found".into(), (child.is_some()).into());
2077
2078 if let Some((child_name, child_model)) = child {
2079 let mut columns = serde_yaml_ng::Mapping::new();
2080 for column in &child_model.schema.columns {
2081 columns.insert(
2082 column.name.clone().into(),
2083 column.source_type.clone().into(),
2084 );
2085 }
2086 facts.insert(
2087 "child_columns".into(),
2088 serde_yaml_ng::Value::Mapping(columns),
2089 );
2090
2091 if let RowsModel::RelationChildren { distribution, .. } = &child_model.rows {
2092 let (mean, min, max) = distribution_bounds(distribution);
2093 facts.insert("dist_kind".into(), distribution_kind(distribution).into());
2094 facts.insert("dist_mean".into(), mean.into());
2095 facts.insert("dist_min".into(), min.into());
2096 facts.insert("dist_max".into(), max.into());
2097 }
2098
2099 let rel_name = config.args.get("relationship").and_then(|v| v.as_str());
2100 let rel_on_child = rel_name.is_some_and(|name| {
2101 child_relationship_references(child_model, name, parent_name)
2102 });
2103 facts.insert("rel_on_child".into(), rel_on_child.into());
2104
2105 if let Some(serde_yaml_ng::Value::Mapping(mapping)) =
2108 config.args.get("child_columns")
2109 {
2110 for column_name in mapping.values().filter_map(|v| v.as_str()) {
2111 let exists = child_model
2112 .schema
2113 .columns
2114 .iter()
2115 .any(|column| column.name == column_name);
2116 if !exists {
2117 continue;
2118 }
2119 let has_generator = child_model
2120 .columns
2121 .get(column_name)
2122 .is_some_and(|rule| rule.generator.is_some());
2123 if has_generator {
2124 bag.error(
2125 crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
2126 format!("tables.{child_name}.columns.{column_name}"),
2127 format!(
2128 "column `{column_name}` on table `{child_name}` is produced by both its own generator and the `commerce.order_family` planner on table `{parent_name}`"
2129 ),
2130 );
2131 }
2132 ctx.external_owners.insert(
2133 (child_name.to_string(), column_name.to_string()),
2134 ExternalChildOwner {
2135 planner_kind: config.kind.clone(),
2136 },
2137 );
2138 }
2139 }
2140
2141 if ctx.families.iter().any(|f| f.child == child_name) {
2142 bag.error(
2145 crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
2146 format!("tables.{child_name}"),
2147 format!(
2148 "child table `{child_name}` is claimed as a family child by more than one parent; a family child must have a single producing parent"
2149 ),
2150 );
2151 } else {
2152 ctx.families.push(FamilyMembership {
2153 parent: parent_name.clone(),
2154 child: child_name.to_string(),
2155 });
2156 }
2157 }
2158
2159 ctx.facts.insert(
2160 (parent_name.clone(), index),
2161 serde_yaml_ng::Value::Mapping(facts),
2162 );
2163 }
2164 }
2165 ctx
2166}
2167
2168fn dense_key_recipe(table: &TableModel, column: &str) -> Option<(i128, i128)> {
2177 if let Some(rule) = table.columns.get(column) {
2178 if let Some(generator) = &rule.generator {
2179 if generator.kind == "sequence" {
2180 let start = generator
2181 .args
2182 .get("start")
2183 .and_then(serde_yaml_ng::Value::as_i64)
2184 .unwrap_or(0);
2185 let step = generator
2186 .args
2187 .get("step")
2188 .and_then(serde_yaml_ng::Value::as_i64)
2189 .unwrap_or(1);
2190 return Some((i128::from(start), i128::from(step)));
2191 }
2192 return None;
2194 }
2195 }
2196 let column = table.schema.columns.iter().find(|c| c.name == column)?;
2197 if column.primary_key
2203 && !column.generated
2204 && matches!(
2205 column.family,
2206 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
2207 )
2208 {
2209 return Some((1, 1));
2210 }
2211 None
2212}
2213
2214fn build_relation_facts(
2221 model: &SyntheticModel,
2222 table: &TableModel,
2223 resolved: &BTreeMap<String, u64>,
2224) -> serde_yaml_ng::Value {
2225 use serde_yaml_ng::{Mapping, Value};
2226
2227 let recipe_map = |recipe: Option<(i128, i128)>| -> Mapping {
2228 let mut m = Mapping::new();
2229 match recipe {
2230 Some((start, step)) => {
2231 m.insert("dense".into(), true.into());
2232 m.insert("start".into(), (start as i64).into());
2233 m.insert("step".into(), (step as i64).into());
2234 }
2235 None => {
2236 m.insert("dense".into(), false.into());
2237 }
2238 }
2239 m
2240 };
2241
2242 let mut relationships = Mapping::new();
2243 let generation = table.relationships.iter().map(|rel| {
2244 (
2245 rel.name.clone(),
2246 rel.references.table.clone(),
2247 rel.references.columns.clone(),
2248 )
2249 });
2250 let schema = table.schema.relationships.iter().map(|rel| {
2251 (
2252 rel.name.clone(),
2253 rel.referenced_table.clone(),
2254 rel.referenced_columns.clone(),
2255 )
2256 });
2257 for (name, parent_table, parent_columns) in generation.chain(schema) {
2258 let Some(name) = name else { continue };
2259 let parent_column = parent_columns.first().cloned().unwrap_or_default();
2260 let recipe = model
2261 .tables
2262 .get(&parent_table)
2263 .and_then(|parent| dense_key_recipe(parent, &parent_column));
2264 let mut entry = recipe_map(recipe);
2265 entry.insert("parent_table".into(), parent_table.clone().into());
2266 entry.insert("parent_column".into(), parent_column.into());
2267 entry.insert(
2268 "count".into(),
2269 resolved.get(&parent_table).copied().unwrap_or(0).into(),
2270 );
2271 relationships.insert(name.into(), Value::Mapping(entry));
2272 }
2273
2274 let mut tables = Mapping::new();
2275 for (name, target) in &model.tables {
2276 let count = resolved.get(name).copied().unwrap_or(0);
2277 let mut keys = Mapping::new();
2278 for column in &target.schema.columns {
2279 if let Some(recipe) = dense_key_recipe(target, &column.name) {
2280 let mut key_entry = recipe_map(Some(recipe));
2281 key_entry.insert("count".into(), count.into());
2285 keys.insert(column.name.clone().into(), Value::Mapping(key_entry));
2286 }
2287 }
2288 let mut entry = Mapping::new();
2289 entry.insert("count".into(), count.into());
2290 entry.insert("keys".into(), Value::Mapping(keys));
2291 let primary_key = target.schema.primary_key.first().cloned().or_else(|| {
2294 target
2295 .schema
2296 .columns
2297 .iter()
2298 .find(|column| column.primary_key)
2299 .map(|column| column.name.clone())
2300 });
2301 if let Some(primary_key) = primary_key {
2302 entry.insert("primary_key".into(), primary_key.into());
2303 }
2304 tables.insert(name.clone().into(), Value::Mapping(entry));
2305 }
2306
2307 let mut root = Mapping::new();
2308 root.insert("relationships".into(), Value::Mapping(relationships));
2309 root.insert("tables".into(), Value::Mapping(tables));
2310 root.insert(
2314 "self_count".into(),
2315 resolved
2316 .get(&table.schema.name)
2317 .copied()
2318 .unwrap_or(0)
2319 .into(),
2320 );
2321 Value::Mapping(root)
2322}
2323
2324fn child_relationship_references(child: &TableModel, name: &str, parent: &str) -> bool {
2330 let generation = child.relationships.iter().any(|relationship| {
2331 relationship.name.as_deref() == Some(name) && relationship.references.table == parent
2332 });
2333 let schema = child.schema.relationships.iter().any(|relationship| {
2334 relationship.name.as_deref() == Some(name) && relationship.referenced_table == parent
2335 });
2336 generation || schema
2337}
2338
2339fn build_phases(
2343 order: &[String],
2344 family_ctx: &FamilyContext,
2345 budget_bytes: u64,
2346 bag: &mut DiagnosticBag,
2347) -> Vec<ExecutionPhase> {
2348 let ordered: BTreeSet<&str> = order.iter().map(String::as_str).collect();
2349 let child_tables: BTreeSet<&str> = family_ctx
2350 .families
2351 .iter()
2352 .map(|family| family.child.as_str())
2353 .collect();
2354 let mut phases = Vec::with_capacity(order.len());
2355 for name in order {
2356 if child_tables.contains(name.as_str()) {
2357 continue;
2358 }
2359 match family_ctx
2360 .families
2361 .iter()
2362 .find(|family| &family.parent == name)
2363 {
2364 Some(family) if ordered.contains(family.child.as_str()) => {
2368 phases.push(ExecutionPhase::Family(FamilyPhase {
2369 name: name.clone(),
2370 tables: vec![name.clone(), family.child.clone()],
2371 budget_bytes,
2372 }));
2373 }
2374 Some(family) => {
2375 bag.warning(
2376 crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
2377 format!("tables.{name}.planners"),
2378 format!(
2379 "family child `{}` of `{name}` was excluded; generating `{name}` without its correlated child rows",
2380 family.child
2381 ),
2382 );
2383 phases.push(ExecutionPhase::Table(name.clone()));
2384 }
2385 None => phases.push(ExecutionPhase::Table(name.clone())),
2386 }
2387 }
2388 phases
2389}
2390
2391fn compile_relationship(relationship: &RelationshipModel) -> CompiledRelationship {
2394 CompiledRelationship {
2395 name: relationship.name.clone(),
2396 columns: relationship.columns.clone(),
2397 parent_table: relationship.references.table.clone(),
2398 parent_columns: relationship.references.columns.clone(),
2399 distribution: parse_distribution(relationship.distribution.as_deref()),
2400 null_permille: 0,
2401 }
2402}
2403
2404fn parse_distribution(name: Option<&str>) -> RelationshipDistribution {
2407 match name {
2408 Some("sequential") => RelationshipDistribution::Sequential,
2409 Some("weighted") => RelationshipDistribution::Weighted,
2410 Some("observed") => RelationshipDistribution::Observed,
2411 _ => RelationshipDistribution::Uniform,
2412 }
2413}
2414
2415fn fold_foreign_key_generators(
2424 table_name: &str,
2425 table: &TableModel,
2426 relationships: &mut [CompiledRelationship],
2427 bag: &mut DiagnosticBag,
2428) {
2429 for (column, rule) in &table.columns {
2430 let Some(generator) = &rule.generator else {
2431 continue;
2432 };
2433 if generator.kind != "relation.foreign_key" && generator.kind != "relation.composite_key" {
2434 continue;
2435 }
2436 let Some(relationship) = relationships
2437 .iter_mut()
2438 .find(|relationship| relationship.columns.iter().any(|c| c == column))
2439 else {
2440 bag.error(
2441 crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
2442 format!("tables.{table_name}.columns.{column}.generator"),
2443 format!(
2444 "column `{column}` on table `{table_name}` uses generator `{}` but no relationship declares it as a foreign key; declare a `relationships:` entry covering it",
2445 generator.kind
2446 ),
2447 );
2448 continue;
2449 };
2450 if let Some(name) = generator.args.get("distribution").and_then(|v| v.as_str()) {
2451 relationship.distribution = parse_distribution(Some(name));
2452 }
2453 if let Some(rate) = generator.args.get("null_rate").and_then(|v| v.as_f64()) {
2454 relationship.null_permille = (rate.clamp(0.0, 1.0) * 1000.0).round() as u16;
2455 }
2456 }
2457}
2458
2459fn resolve_seed(seed: &TableSeed, root_seed: u64) -> ResolvedTableSeed {
2461 match seed {
2462 TableSeed::Inherit => ResolvedTableSeed::Inherited(SeedRoot::new(root_seed)),
2463 TableSeed::Random => ResolvedTableSeed::Random(SeedRoot::new(rand::random())),
2464 TableSeed::Fixed(seed) => ResolvedTableSeed::Fixed(SeedRoot::new(*seed)),
2465 }
2466}
2467
2468fn compile_output(model: &SyntheticModel) -> CompiledOutput {
2470 CompiledOutput {
2471 dialect: model.output.dialect.as_ref().and_then(|d| d.parse().ok()),
2472 mode: model.output.mode,
2473 inserts: model.output.inserts,
2474 batch_size: model.output.batch_size,
2475 }
2476}
2477
2478fn compile_globs(patterns: &[String], bag: &mut DiagnosticBag) -> Vec<Pattern> {
2481 patterns
2482 .iter()
2483 .filter_map(|pattern| match Pattern::new(pattern) {
2484 Ok(compiled) => Some(compiled),
2485 Err(error) => {
2486 bag.error(
2487 crate::diagnostic::codes::INVALID_GLOB.code,
2488 "options",
2489 format!("invalid table glob `{pattern}`: {error}"),
2490 );
2491 None
2492 }
2493 })
2494 .collect()
2495}