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::parser::SqlDialect;
40use crate::synthetic::model::{
41 ChildDistribution, InferenceMode, ModifierConfig, PlannerConfig, RelationshipModel, RowsModel,
42 SyntheticModel, TableModel, TableSeed, MAX_OUTPUT_BATCH_SIZE,
43};
44use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
45
46use super::plan::{
47 ColumnOwner, CompiledOutput, CompiledRelationship, ExecutionPhase, FamilyPhase, GenerationPlan,
48 PlanEstimates, PlannedColumn, PlannedTable, RelationshipDistribution, ResolvedTableSeed,
49};
50use super::registry::{
51 ColumnScope, CompileContext, CompiledModifier, CompiledPlanner, ExtensionRegistry,
52};
53use super::seed::{SeedRoot, StreamId};
54
55#[derive(Debug, Clone, PartialEq)]
58pub struct TableCountOverride {
59 pub table: String,
61 pub kind: TableCountKind,
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub enum TableCountKind {
68 Rows(u64),
70 Scale(f64),
73}
74
75impl TableCountOverride {
76 pub fn rows(table: impl Into<String>, rows: u64) -> Self {
78 Self {
79 table: table.into(),
80 kind: TableCountKind::Rows(rows),
81 }
82 }
83
84 pub fn scale(table: impl Into<String>, scale: f64) -> Self {
86 Self {
87 table: table.into(),
88 kind: TableCountKind::Scale(scale),
89 }
90 }
91}
92
93#[derive(Debug, Clone, Default)]
96pub struct CompileOptions {
97 pub seed: Option<u64>,
99 pub scale: Option<f64>,
101 pub rows: Option<u64>,
103 pub max_rows: Option<u64>,
105 pub table_rows: Vec<TableCountOverride>,
107 pub tables: Vec<String>,
109 pub exclude: Vec<String>,
111 pub family_budget_bytes: Option<u64>,
116}
117
118const DEFAULT_FAMILY_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
120
121pub struct ModelCompiler {
126 registry: ExtensionRegistry,
127}
128
129impl ModelCompiler {
130 pub fn new(registry: ExtensionRegistry) -> Self {
132 Self { registry }
133 }
134
135 pub fn standard() -> Self {
137 Self::new(ExtensionRegistry::standard())
138 }
139
140 pub fn registry(&self) -> &ExtensionRegistry {
142 &self.registry
143 }
144
145 pub fn compile(
149 &self,
150 model: SyntheticModel,
151 options: CompileOptions,
152 ) -> Result<GenerationPlan, DiagnosticBag> {
153 let mut bag = DiagnosticBag::default();
154
155 if let Some(source) = &model.source {
156 if source.dialect.parse::<SqlDialect>().is_err() {
157 bag.error(
158 crate::diagnostic::codes::DIALECT_INVALID.code,
159 "source.dialect",
160 format!(
161 "unsupported source dialect `{}`; expected mysql, postgres, sqlite, or mssql",
162 source.dialect
163 ),
164 );
165 }
166 }
167 if let Some(dialect) = &model.output.dialect {
168 if dialect.parse::<SqlDialect>().is_err() {
169 bag.error(
170 crate::diagnostic::codes::DIALECT_INVALID.code,
171 "output.dialect",
172 format!(
173 "unsupported output dialect `{dialect}`; expected mysql, postgres, sqlite, or mssql"
174 ),
175 );
176 }
177 }
178 if let Some(batch_size) = model.output.batch_size {
179 if batch_size == 0 || batch_size > MAX_OUTPUT_BATCH_SIZE {
180 bag.error(
181 crate::diagnostic::codes::OUTPUT_BATCH_SIZE.code,
182 "output.batch_size",
183 format!(
184 "output batch size must be between 1 and {MAX_OUTPUT_BATCH_SIZE} (got {batch_size})"
185 ),
186 );
187 }
188 }
189
190 if options.scale.is_some() && options.rows.is_some() {
191 bag.error(
192 crate::diagnostic::codes::COUNT_CONTROL_CONFLICT.code,
193 "options",
194 "`--scale` and `--rows` are mutually exclusive global row controls",
195 );
196 }
197 if let Some(scale) = options.scale {
198 if !scale.is_finite() || scale < 0.0 {
201 bag.error(
202 crate::diagnostic::codes::TABLE_SCALE_INVALID.code,
203 "options",
204 format!("`--scale` must be a finite, non-negative number (got {scale})"),
205 );
206 }
207 }
208
209 let overrides = self.collect_table_overrides(&options, &mut bag);
210 let selected = self.select_tables(&model, &options, &mut bag);
211 let all_parents = parent_edges(&model, EdgeKind::All);
217 let required = parent_edges(&model, EdgeKind::Required);
218 self.report_excluded_dependencies(&selected, &required, &mut bag);
219 let schema_changed = selected.len() < model.tables.len();
223
224 let root_seed = options.seed.or(model.seed).unwrap_or_else(rand::random);
228 let rounding_root = SeedRoot::new(root_seed);
229 let (mut order, mut cyclic) = topo_order(&selected, &all_parents);
230 if !cyclic.is_empty() {
231 let (required_order, required_cyclic) = topo_order(&selected, &required);
239 if required_cyclic.is_empty() {
240 order = required_order;
241 cyclic = Vec::new();
242 bag.warning(
243 crate::diagnostic::codes::FOREIGN_KEY_CYCLE.code,
244 "tables",
245 "nullable foreign keys form a dependency cycle; the cyclic tables cannot all be ordered parent-before-child in the output",
246 );
247 }
248 }
249 if !cyclic.is_empty() {
250 bag.error(
256 crate::diagnostic::codes::ROWS_CYCLE.code,
257 "tables",
258 format!(
259 "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",
260 cyclic.join(", ")
261 ),
262 );
263 }
264
265 let family_ctx = self.collect_family_facts(&model, &mut bag);
266 let family_budget_bytes = options
267 .family_budget_bytes
268 .unwrap_or(DEFAULT_FAMILY_BUDGET_BYTES);
269
270 let mut resolved: BTreeMap<String, u64> = BTreeMap::new();
271 let mut tables: Vec<PlannedTable> = Vec::with_capacity(order.len());
272
273 for name in &order {
274 let table = &model.tables[name];
275 let count = self.resolve_count(
276 &model,
277 name,
278 table,
279 &options,
280 overrides.get(name),
281 rounding_root,
282 &resolved,
283 &mut bag,
284 );
285 resolved.insert(name.clone(), count);
286 tables.push(self.plan_table(
287 &model,
288 name,
289 table,
290 count,
291 root_seed,
292 model.defaults.inference,
293 &family_ctx,
294 &resolved,
295 &selected,
296 !schema_changed,
297 options.max_rows,
298 &mut bag,
299 ));
300 }
301
302 let phases = build_phases(&order, &family_ctx, family_budget_bytes, &mut bag);
303
304 let estimates = PlanEstimates {
305 total_rows: resolved.values().copied().fold(0u64, u64::saturating_add),
306 ..PlanEstimates::default()
307 };
308
309 if bag.has_errors() {
310 return Err(bag);
311 }
312
313 let diagnostics = bag
317 .diagnostics
318 .into_iter()
319 .filter(|diagnostic| diagnostic.severity == Severity::Warning)
320 .collect();
321
322 Ok(GenerationPlan {
323 input_dialect: model
324 .source
325 .as_ref()
326 .and_then(|source| source.dialect.parse().ok()),
327 output: compile_output(&model),
328 tables,
329 phases,
330 diagnostics,
331 estimates,
332 family_budget_bytes,
333 })
334 }
335
336 fn collect_table_overrides(
340 &self,
341 options: &CompileOptions,
342 bag: &mut DiagnosticBag,
343 ) -> BTreeMap<String, TableOverride> {
344 let mut map: BTreeMap<String, TableOverride> = BTreeMap::new();
345 for over in &options.table_rows {
346 let entry = map.entry(over.table.clone()).or_default();
347 match over.kind {
348 TableCountKind::Rows(rows) => entry.rows = Some(rows),
349 TableCountKind::Scale(scale) => entry.scale = Some(scale),
350 }
351 }
352 for (table, over) in &map {
353 if over.rows.is_some() && over.scale.is_some() {
354 bag.error(
355 crate::diagnostic::codes::TABLE_COUNT_CONFLICT.code,
356 format!("tables.{table}"),
357 format!(
358 "table `{table}` has both `--table-rows` and `--table-scale`; they are mutually exclusive"
359 ),
360 );
361 }
362 }
363 map
364 }
365
366 fn select_tables(
368 &self,
369 model: &SyntheticModel,
370 options: &CompileOptions,
371 bag: &mut DiagnosticBag,
372 ) -> BTreeSet<String> {
373 let includes = compile_globs(&options.tables, bag);
374 let excludes = compile_globs(&options.exclude, bag);
375 model
376 .tables
377 .keys()
378 .filter(|name| {
379 let included =
380 includes.is_empty() || includes.iter().any(|pattern| pattern.matches(name));
381 let excluded = excludes.iter().any(|pattern| pattern.matches(name));
382 included && !excluded
383 })
384 .cloned()
385 .collect()
386 }
387
388 fn report_excluded_dependencies(
392 &self,
393 selected: &BTreeSet<String>,
394 parents: &BTreeMap<String, BTreeSet<String>>,
395 bag: &mut DiagnosticBag,
396 ) {
397 for start in selected {
398 let mut reported: BTreeSet<String> = BTreeSet::new();
399 let mut visited: BTreeSet<String> = BTreeSet::new();
400 let mut stack: Vec<Vec<String>> = vec![vec![start.clone()]];
401 while let Some(path) = stack.pop() {
402 let node = path.last().expect("path is never empty");
403 let Some(node_parents) = parents.get(node) else {
404 continue;
405 };
406 for parent in node_parents {
407 let mut extended = path.clone();
408 extended.push(parent.clone());
409 if selected.contains(parent) {
410 if visited.insert(parent.clone()) {
411 stack.push(extended);
412 }
413 } else if reported.insert(parent.clone()) {
414 bag.error(
415 crate::diagnostic::codes::EXCLUDED_DEPENDENCY.code,
416 format!("tables.{start}"),
417 format!(
418 "table `{start}` requires excluded table `{parent}` via dependency path {}",
419 extended.join(" -> ")
420 ),
421 );
422 }
423 }
424 }
425 }
426 }
427
428 #[allow(clippy::too_many_arguments)]
430 fn resolve_count(
431 &self,
432 model: &SyntheticModel,
433 name: &str,
434 table: &TableModel,
435 options: &CompileOptions,
436 over: Option<&TableOverride>,
437 rounding_root: SeedRoot,
438 resolved: &BTreeMap<String, u64>,
439 bag: &mut DiagnosticBag,
440 ) -> u64 {
441 match &table.rows {
442 RowsModel::RelationChildren {
443 parent,
444 distribution,
445 ..
446 } => self.resolve_child_count(
447 name,
448 parent,
449 distribution,
450 options,
451 over,
452 rounding_root,
453 resolved,
454 bag,
455 ),
456 rows => self.resolve_root_count(model, name, rows, options, over, rounding_root, bag),
457 }
458 }
459
460 #[allow(clippy::too_many_arguments)]
461 fn resolve_root_count(
462 &self,
463 model: &SyntheticModel,
464 name: &str,
465 rows: &RowsModel,
466 options: &CompileOptions,
467 over: Option<&TableOverride>,
468 rounding_root: SeedRoot,
469 bag: &mut DiagnosticBag,
470 ) -> u64 {
471 if matches!(rows, RowsModel::Observed { .. }) && !has_observed_provenance(model, name) {
472 bag.error(
473 crate::diagnostic::codes::ROWS_OBSERVED_MISSING.code,
474 format!("tables.{name}.rows"),
475 format!(
476 "table `{name}` uses `rows.kind: observed` but the model has no attached source or profile to resolve the observed count from"
477 ),
478 );
479 }
480
481 let base = declared_count(rows).unwrap_or(0) as f64;
482
483 let mut target = match (options.scale, options.rows) {
485 (Some(scale), _) => base * scale,
486 (None, Some(rows)) => rows as f64,
487 (None, None) => base,
488 };
489
490 match over.map(TableOverride::effective) {
493 Some(EffectiveOverride::Rows(rows)) => target = rows as f64,
494 Some(EffectiveOverride::Scale(scale)) => target = base * scale,
495 None | Some(EffectiveOverride::Conflict) => {}
496 }
497
498 let count = stochastic_round(target, rounding_root, name);
499 apply_max_rows(count, options.max_rows, name, bag)
500 }
501
502 #[allow(clippy::too_many_arguments)]
503 fn resolve_child_count(
504 &self,
505 name: &str,
506 parent: &str,
507 distribution: &ChildDistribution,
508 options: &CompileOptions,
509 over: Option<&TableOverride>,
510 rounding_root: SeedRoot,
511 resolved: &BTreeMap<String, u64>,
512 bag: &mut DiagnosticBag,
513 ) -> u64 {
514 let Some(&parent_count) = resolved.get(parent) else {
517 return 0;
518 };
519 let (mean, min, _max) = distribution_bounds(distribution);
520
521 let derived = parent_count as f64 * mean;
524 let target = match over.map(TableOverride::effective) {
525 Some(EffectiveOverride::Rows(rows)) => rows as f64,
526 Some(EffectiveOverride::Scale(scale)) => derived * scale,
527 None | Some(EffectiveOverride::Conflict) => derived,
528 };
529
530 let count = stochastic_round(target, rounding_root, name);
531 let count = apply_max_rows(count, options.max_rows, name, bag);
532
533 let minimum = (parent_count as f64 * min).ceil() as u64;
534 if count < minimum {
535 bag.error(
536 crate::diagnostic::codes::CHILD_COUNT_IMPOSSIBLE.code,
537 format!("tables.{name}.rows"),
538 format!(
539 "table `{name}` resolves to {count} rows, but its {parent_count} parents in `{parent}` each require at least {min} child(ren) ({minimum} total)"
540 ),
541 );
542 }
543 count
544 }
545
546 #[allow(clippy::too_many_arguments)]
551 fn plan_table(
552 &self,
553 model: &SyntheticModel,
554 name: &str,
555 table: &TableModel,
556 rows: u64,
557 root_seed: u64,
558 inference: InferenceMode,
559 family_ctx: &FamilyContext,
560 resolved: &BTreeMap<String, u64>,
561 selected: &BTreeSet<String>,
562 preserve_raw: bool,
563 max_rows: Option<u64>,
564 bag: &mut DiagnosticBag,
565 ) -> PlannedTable {
566 let seed = resolve_seed(&table.seed, root_seed);
567 let compile_seed = seed_root_of(&seed);
568 let mut seen_columns: BTreeSet<&str> = BTreeSet::new();
572 for column in &table.schema.columns {
573 if !seen_columns.insert(column.name.as_str()) {
574 bag.error(
575 crate::diagnostic::codes::DUPLICATE_COLUMN.code,
576 format!("tables.{name}.schema.columns"),
577 format!(
578 "table `{name}` declares column `{}` more than once",
579 column.name
580 ),
581 );
582 }
583 }
584 self.validate_column_operator_arguments(name, table, bag);
585 let mut relationships: Vec<CompiledRelationship> = table
586 .relationships
587 .iter()
588 .map(compile_relationship)
589 .collect();
590 for schema_rel in &table.schema.relationships {
595 if relationships
596 .iter()
597 .any(|existing| existing.columns == schema_rel.columns)
598 {
599 continue;
600 }
601 relationships.push(CompiledRelationship {
602 name: schema_rel.name.clone(),
603 columns: schema_rel.columns.clone(),
604 parent_table: schema_rel.referenced_table.clone(),
605 parent_columns: schema_rel.referenced_columns.clone(),
606 distribution: RelationshipDistribution::default(),
607 null_permille: 0,
608 });
609 }
610 fold_foreign_key_generators(name, table, &mut relationships, bag);
611
612 relationships.retain(|relationship| {
618 if selected.contains(&relationship.parent_table) {
619 return true;
620 }
621 if !fk_columns_all_non_null(table, &relationship.columns) {
622 bag.warning(
623 crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
624 format!("tables.{name}"),
625 format!(
626 "optional relationship `{}` on table `{name}` references excluded table `{}`; its foreign key is detached and omitted from the rendered DDL",
627 relationship.name.as_deref().unwrap_or("(unnamed)"),
628 relationship.parent_table
629 ),
630 );
631 }
632 false
633 });
634
635 for relationship in &relationships {
636 let parent_is_empty = resolved
637 .get(&relationship.parent_table)
638 .is_some_and(|count| *count == 0);
639 if rows > 0 && parent_is_empty && !fk_columns_all_nullable(table, &relationship.columns)
640 {
641 bag.error(
642 crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
643 format!("tables.{name}.relationships"),
644 format!(
645 "table `{name}` resolves to {rows} row(s), but required relationship `{}` targets empty parent table `{}`",
646 relationship.name.as_deref().unwrap_or("(unnamed)"),
647 relationship.parent_table
648 ),
649 );
650 }
651 }
652
653 let planners = self.compile_planners(
654 model,
655 name,
656 table,
657 compile_seed,
658 family_ctx,
659 resolved,
660 rows,
661 max_rows,
662 bag,
663 );
664 let claims = collect_claims(table, &planners);
665
666 let columns: Vec<PlannedColumn> = table
667 .schema
668 .columns
669 .iter()
670 .map(|column| {
671 let owner = self.resolve_owner(
672 name,
673 table,
674 column,
675 claims.get(&column.name).map(Vec::as_slice).unwrap_or(&[]),
676 &planners,
677 family_ctx,
678 compile_seed,
679 inference,
680 bag,
681 );
682 let modifiers =
683 self.compile_modifiers(name, table, column, &owner, compile_seed, bag);
684 PlannedColumn {
685 schema: column.clone(),
686 owner,
687 modifiers,
688 }
689 })
690 .collect();
691
692 report_dependency_cycles(name, table, &columns, &planners, bag);
693 let eval_order = column_eval_order(table, &columns);
694
695 let compiled_planners = planners.into_iter().filter_map(|p| p.compiled).collect();
700
701 let present_columns: BTreeSet<&str> = table
708 .schema
709 .columns
710 .iter()
711 .map(|c| c.name.as_str())
712 .collect();
713 let mut schema = table.schema.clone();
714 schema
715 .relationships
716 .retain(|relationship| selected.contains(&relationship.referenced_table));
717 schema.indexes.retain(|index| {
718 index
719 .columns
720 .iter()
721 .all(|c| present_columns.contains(c.as_str()))
722 });
723 if !preserve_raw {
724 schema.create_statement = None;
725 }
726
727 PlannedTable {
728 name: name.to_string(),
729 rows,
730 schema,
731 seed,
732 columns,
733 relationships,
734 planners: compiled_planners,
735 eval_order,
736 }
737 }
738
739 #[allow(clippy::too_many_arguments)]
742 fn compile_planners(
743 &self,
744 model: &SyntheticModel,
745 table_name: &str,
746 table: &TableModel,
747 seed: SeedRoot,
748 family_ctx: &FamilyContext,
749 resolved: &BTreeMap<String, u64>,
750 parent_rows: u64,
751 max_rows: Option<u64>,
752 bag: &mut DiagnosticBag,
753 ) -> Vec<PlannerInfo> {
754 let relationship_names = relationship_names(table);
755 let relation_facts = build_relation_facts(model, table, resolved);
763 table
764 .planners
765 .iter()
766 .enumerate()
767 .map(|(index, config)| {
768 let path = format!("tables.{table_name}.planners[{index}]");
769 let Some(factory) = self.registry.planner(&config.kind) else {
770 bag.error(
771 crate::diagnostic::codes::PLANNER_UNKNOWN.code,
772 path,
773 format!("no planner registered for kind `{}`", config.kind),
774 );
775 return PlannerInfo::unresolved(&config.kind);
776 };
777 let descriptor = factory.descriptor();
778 validate_operator_arguments(
779 &config.args,
780 descriptor.arguments,
781 &path,
782 "planner",
783 &config.kind,
784 bag,
785 );
786 let is_family = config.args.contains_key("children");
791 let is_cross_table = descriptor.cross_table;
792 let injected;
793 let config = if let Some(facts) =
794 family_ctx.facts.get(&(table_name.to_string(), index))
795 {
796 let mut cloned = config.clone();
797 let mut facts = facts.clone();
798 if let (Some(max_rows), serde_yaml_ng::Value::Mapping(mapping)) =
799 (max_rows, &mut facts)
800 {
801 mapping.insert("child_row_limit".into(), max_rows.into());
802 }
803 if let serde_yaml_ng::Value::Mapping(mapping) = &mut facts {
804 mapping.insert("parent_rows".into(), parent_rows.into());
805 }
806 cloned.args.insert(
807 super::planners::order_family::FAMILY_FACTS_KEY.to_string(),
808 facts,
809 );
810 injected = cloned;
811 &injected
812 } else if !is_family
813 && (is_cross_table || config.args.contains_key("relationship"))
814 {
815 let mut cloned = config.clone();
823 cloned.args.insert(
824 super::planners::structural::RELATION_FACTS_KEY.to_string(),
825 relation_facts.clone(),
826 );
827 injected = cloned;
828 &injected
829 } else {
830 config
831 };
832 let writes = match descriptor.writes {
833 ColumnScope::Configured => configured_columns(config, &["columns", "writes"]),
834 _ => Vec::new(),
835 };
836 let reads = match descriptor.reads {
837 ColumnScope::Configured => configured_columns(config, &["reads"]),
838 _ => Vec::new(),
839 };
840
841 if !is_family {
842 if let Some(referenced) = string_arg(config, "relationship") {
843 if !relationship_names.iter().any(|n| n == referenced) {
844 bag.error(
845 crate::diagnostic::codes::RELATIONSHIP_UNKNOWN.code,
846 format!("{path}.relationship"),
847 format!(
848 "planner `{}` references relationship `{referenced}`, which is not declared on table `{table_name}`",
849 config.kind
850 ),
851 );
852 }
853 }
854 }
855
856 let context = CompileContext::for_table(&table.schema, seed, &path);
857 let compiled = match factory.compile(config, &context) {
858 Ok(compiled) => Some(compiled),
859 Err(errors) => {
860 bag.diagnostics.extend(errors.diagnostics);
861 None
862 }
863 };
864
865 PlannerInfo {
866 kind: descriptor.kind.to_string(),
867 writes,
868 reads,
869 compiled,
870 }
871 })
872 .collect()
873 }
874
875 fn validate_column_operator_arguments(
879 &self,
880 table_name: &str,
881 table: &TableModel,
882 bag: &mut DiagnosticBag,
883 ) {
884 for (column_name, rule) in &table.columns {
885 if let Some(config) = &rule.generator {
886 if let Some(factory) = self.registry.generator(&config.kind) {
887 validate_operator_arguments(
888 &config.args,
889 factory.descriptor().arguments,
890 &format!("tables.{table_name}.columns.{column_name}.generator"),
891 "generator",
892 &config.kind,
893 bag,
894 );
895 }
896 }
897 for (index, config) in rule.modifiers.iter().enumerate() {
898 if let Some(factory) = self.registry.modifier(&config.kind) {
899 validate_operator_arguments(
900 &config.args,
901 factory.descriptor().arguments,
902 &format!("tables.{table_name}.columns.{column_name}.modifiers[{index}]"),
903 "modifier",
904 &config.kind,
905 bag,
906 );
907 }
908 }
909 }
910 }
911
912 #[allow(clippy::too_many_arguments)]
914 fn resolve_owner(
915 &self,
916 table_name: &str,
917 table: &TableModel,
918 column: &PortableColumn,
919 claimants: &[Claim],
920 planners: &[PlannerInfo],
921 family_ctx: &FamilyContext,
922 seed: SeedRoot,
923 inference: InferenceMode,
924 bag: &mut DiagnosticBag,
925 ) -> ColumnOwner {
926 if claimants.len() > 1 {
927 let diagnostic = bag.error(
928 crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
929 format!("tables.{table_name}.columns.{}", column.name),
930 format!(
931 "tables.{table_name}.columns.{} is produced by more than one owner",
932 column.name
933 ),
934 );
935 diagnostic.related = claimants
936 .iter()
937 .map(|claim| SourceLocation {
938 path: claim.path.clone(),
939 description: claim.description.clone(),
940 })
941 .collect();
942 diagnostic.help = Some(format!(
943 "keep a single owner for `{}`: remove the column generator or drop it from the planner mapping",
944 column.name
945 ));
946 return ColumnOwner::GeneratedByDatabase;
947 }
948
949 if let Some(claim) = claimants.first() {
950 return match &claim.source {
951 ClaimSource::Generator => {
952 self.compile_generator(table_name, table, column, seed, bag)
953 }
954 ClaimSource::Planner { index } => ColumnOwner::Planner {
955 kind: planners[*index].kind.clone(),
956 planner_index: *index,
957 },
958 };
959 }
960
961 if let Some(external) = family_ctx
964 .external_owners
965 .get(&(table_name.to_string(), column.name.clone()))
966 {
967 return ColumnOwner::FamilyChild {
968 planner_kind: external.planner_kind.clone(),
969 };
970 }
971
972 self.infer_structural_owner(table_name, table, column, inference, seed, bag)
973 }
974
975 fn compile_generator(
977 &self,
978 table_name: &str,
979 table: &TableModel,
980 column: &PortableColumn,
981 seed: SeedRoot,
982 bag: &mut DiagnosticBag,
983 ) -> ColumnOwner {
984 let path = format!("tables.{table_name}.columns.{}.generator", column.name);
985 let config = table.columns[&column.name]
986 .generator
987 .as_ref()
988 .expect("generator claim implies a generator rule");
989 self.compile_generator_config(table, column, config, path, seed, bag)
990 }
991
992 fn compile_generator_config(
996 &self,
997 table: &TableModel,
998 column: &PortableColumn,
999 config: &crate::synthetic::model::GeneratorConfig,
1000 path: String,
1001 seed: SeedRoot,
1002 bag: &mut DiagnosticBag,
1003 ) -> ColumnOwner {
1004 let Some(factory) = self.registry.generator(&config.kind) else {
1005 bag.error(
1006 crate::diagnostic::codes::GENERATOR_UNKNOWN.code,
1007 path,
1008 format!("no generator registered for kind `{}`", config.kind),
1009 );
1010 return ColumnOwner::GeneratedByDatabase;
1011 };
1012 let descriptor = factory.descriptor();
1013
1014 if !descriptor.accepts.contains(&column.family) {
1015 bag.error(
1016 crate::diagnostic::codes::GENERATOR_TYPE.code,
1017 path,
1018 format!(
1019 "generator `{}` cannot produce column `{}` of type family {:?}",
1020 config.kind, column.name, column.family
1021 ),
1022 );
1023 return ColumnOwner::GeneratedByDatabase;
1024 }
1025
1026 let context = CompileContext::for_column(&table.schema, column, seed, &path);
1027 match factory.compile(config, &context) {
1028 Ok(compiled) => ColumnOwner::Generator {
1029 kind: descriptor.kind.to_string(),
1030 compiled,
1031 },
1032 Err(errors) => {
1033 bag.diagnostics.extend(errors.diagnostics);
1034 ColumnOwner::GeneratedByDatabase
1035 }
1036 }
1037 }
1038
1039 fn infer_structural_owner(
1043 &self,
1044 table_name: &str,
1045 table: &TableModel,
1046 column: &PortableColumn,
1047 inference: InferenceMode,
1048 seed: SeedRoot,
1049 bag: &mut DiagnosticBag,
1050 ) -> ColumnOwner {
1051 if column.generated || column.identity {
1055 return ColumnOwner::GeneratedByDatabase;
1056 }
1057 if foreign_key_columns(table).contains(&column.name) {
1058 return ColumnOwner::Relationship {
1059 relationship: relationship_of(table, &column.name),
1060 };
1061 }
1062 if column.default_sql.is_some() {
1063 return ColumnOwner::DatabaseDefault;
1064 }
1065
1066 if matches!(inference, InferenceMode::Schema)
1077 && column.primary_key
1078 && matches!(
1079 column.family,
1080 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
1081 )
1082 {
1083 return ColumnOwner::GeneratedByDatabase;
1084 }
1085
1086 match inference {
1095 InferenceMode::Schema => {
1096 let config =
1097 crate::profile::heuristics::schema_inferred_generator(&table.schema, column);
1098 let path = format!(
1099 "tables.{table_name}.columns.{}.generator[inferred]",
1100 column.name
1101 );
1102 self.compile_generator_config(table, column, &config, path, seed, bag)
1103 }
1104 InferenceMode::Disabled => {
1105 bag.error(
1106 crate::diagnostic::codes::COLUMN_OWNER_MISSING.code,
1107 format!("tables.{table_name}.columns.{}", column.name),
1108 format!(
1109 "column `{}` on table `{table_name}` has no generator, planner, relationship, or database default to produce its value",
1110 column.name
1111 ),
1112 );
1113 ColumnOwner::GeneratedByDatabase
1114 }
1115 }
1116 }
1117
1118 fn compile_modifiers(
1129 &self,
1130 table_name: &str,
1131 table: &TableModel,
1132 column: &PortableColumn,
1133 owner: &ColumnOwner,
1134 seed: SeedRoot,
1135 bag: &mut DiagnosticBag,
1136 ) -> Vec<Box<dyn CompiledModifier>> {
1137 let empty_rule;
1142 let rule = match table.columns.get(&column.name) {
1143 Some(rule) => rule,
1144 None => {
1145 empty_rule = crate::synthetic::model::ColumnRule {
1146 semantic: None,
1147 generator: None,
1148 modifiers: Vec::new(),
1149 };
1150 &empty_rule
1151 }
1152 };
1153 let is_generator = matches!(owner, ColumnOwner::Generator { .. });
1154 let mut compiled: Vec<Box<dyn CompiledModifier>> = Vec::new();
1155 for (index, modifier) in rule.modifiers.iter().enumerate() {
1156 let path = format!(
1157 "tables.{table_name}.columns.{}.modifiers[{index}]",
1158 column.name
1159 );
1160 let Some(factory) = self.registry.modifier(&modifier.kind) else {
1161 bag.error(
1162 crate::diagnostic::codes::MODIFIER_UNKNOWN.code,
1163 path,
1164 format!("no modifier registered for kind `{}`", modifier.kind),
1165 );
1166 continue;
1167 };
1168 if !factory.descriptor().accepts.contains(&column.family) {
1169 bag.error(
1170 crate::diagnostic::codes::MODIFIER_TYPE.code,
1171 path,
1172 format!(
1173 "modifier `{}` cannot transform column `{}` of type family {:?}",
1174 modifier.kind, column.name, column.family
1175 ),
1176 );
1177 continue;
1178 }
1179 if !is_generator {
1180 continue;
1181 }
1182 let context = CompileContext::for_column(&table.schema, column, seed, &path);
1183 match factory.compile(modifier, &context) {
1184 Ok(operator) => compiled.push(operator),
1185 Err(errors) => bag.diagnostics.extend(errors.diagnostics),
1186 }
1187 }
1188
1189 self.enforce_key_uniqueness(
1190 table_name,
1191 table,
1192 column,
1193 owner,
1194 rule,
1195 seed,
1196 &mut compiled,
1197 bag,
1198 );
1199
1200 compiled
1201 }
1202
1203 #[allow(clippy::too_many_arguments)]
1216 fn enforce_key_uniqueness(
1217 &self,
1218 table_name: &str,
1219 table: &TableModel,
1220 column: &PortableColumn,
1221 owner: &ColumnOwner,
1222 rule: &crate::synthetic::model::ColumnRule,
1223 seed: SeedRoot,
1224 compiled: &mut Vec<Box<dyn CompiledModifier>>,
1225 bag: &mut DiagnosticBag,
1226 ) {
1227 let ColumnOwner::Generator {
1228 compiled: generator,
1229 ..
1230 } = owner
1231 else {
1232 return;
1233 };
1234 if !is_single_column_key(&table.schema, column) {
1235 return;
1236 }
1237 if generator.is_inherently_unique() {
1238 return;
1239 }
1240 if rule
1243 .modifiers
1244 .iter()
1245 .any(|modifier| modifier.kind == "unique")
1246 {
1247 return;
1248 }
1249 let Some(factory) = self.registry.modifier("unique") else {
1250 return;
1251 };
1252 let path = format!(
1253 "tables.{table_name}.columns.{}.modifiers[auto-unique]",
1254 column.name
1255 );
1256 let config = ModifierConfig {
1257 kind: "unique".to_string(),
1258 args: [(
1259 "on_exhaustion".to_string(),
1260 serde_yaml_ng::Value::from("error"),
1261 )]
1262 .into_iter()
1263 .collect(),
1264 };
1265 let context = CompileContext::for_column(&table.schema, column, seed, &path);
1266 match factory.compile(&config, &context) {
1267 Ok(operator) => compiled.push(operator),
1268 Err(errors) => bag.diagnostics.extend(errors.diagnostics),
1269 }
1270 }
1271}
1272
1273fn validate_operator_arguments(
1277 args: &BTreeMap<String, serde_yaml_ng::Value>,
1278 expected: &[super::registry::ArgumentSpec],
1279 path: &str,
1280 operator_type: &str,
1281 kind: &str,
1282 bag: &mut DiagnosticBag,
1283) {
1284 for argument in args.keys() {
1285 if expected.iter().any(|spec| spec.name == argument) {
1286 continue;
1287 }
1288 let diagnostic = bag.error(
1289 crate::diagnostic::codes::OPERATOR_UNKNOWN_ARGUMENT.code,
1290 format!("{path}.{argument}"),
1291 format!("{operator_type} `{kind}` does not accept argument `{argument}`"),
1292 );
1293 if !expected.is_empty() {
1294 diagnostic.help = Some(format!(
1295 "supported arguments: {}",
1296 expected
1297 .iter()
1298 .map(|spec| spec.name)
1299 .collect::<Vec<_>>()
1300 .join(", ")
1301 ));
1302 }
1303 }
1304}
1305
1306fn primary_key_columns(table: &PortableTable) -> BTreeSet<&str> {
1309 let mut columns: BTreeSet<&str> = table.primary_key.iter().map(String::as_str).collect();
1310 columns.extend(
1311 table
1312 .columns
1313 .iter()
1314 .filter(|column| column.primary_key)
1315 .map(|column| column.name.as_str()),
1316 );
1317 columns
1318}
1319
1320fn is_single_column_key(table: &PortableTable, column: &PortableColumn) -> bool {
1326 let primary = primary_key_columns(table);
1327 if primary.len() == 1 && primary.contains(column.name.as_str()) {
1328 return true;
1329 }
1330 if column.unique {
1331 return true;
1332 }
1333 let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
1334 table
1335 .unique_constraints
1336 .iter()
1337 .any(|constraint| single(&constraint.columns))
1338 || table
1339 .indexes
1340 .iter()
1341 .any(|index| index.unique && single(&index.columns))
1342}
1343
1344#[derive(Debug, Default, Clone, Copy)]
1346struct TableOverride {
1347 rows: Option<u64>,
1348 scale: Option<f64>,
1349}
1350
1351enum EffectiveOverride {
1353 Rows(u64),
1354 Scale(f64),
1355 Conflict,
1356}
1357
1358impl TableOverride {
1359 fn effective(&self) -> EffectiveOverride {
1360 match (self.rows, self.scale) {
1361 (Some(_), Some(_)) => EffectiveOverride::Conflict,
1362 (Some(rows), None) => EffectiveOverride::Rows(rows),
1363 (None, Some(scale)) => EffectiveOverride::Scale(scale),
1364 (None, None) => EffectiveOverride::Conflict,
1365 }
1366 }
1367}
1368
1369fn apply_max_rows(count: u64, max_rows: Option<u64>, name: &str, bag: &mut DiagnosticBag) -> u64 {
1372 match max_rows {
1373 Some(max) if count > max => {
1374 bag.warning(
1375 crate::diagnostic::codes::MAX_ROWS_CAPPED.code,
1376 format!("tables.{name}.rows"),
1377 format!("table `{name}` row count capped from {count} to {max} by `--max-rows`"),
1378 );
1379 max
1380 }
1381 _ => count,
1382 }
1383}
1384
1385fn stochastic_round(value: f64, root: SeedRoot, table: &str) -> u64 {
1388 if value <= 0.0 {
1389 return 0;
1390 }
1391 let floor = value.floor();
1392 let fraction = value - floor;
1393 let mut count = floor as u64;
1394 if fraction > 0.0 {
1395 let mut rng = root.stream(StreamId::rounding(table));
1396 if rng.random::<f64>() < fraction {
1397 count += 1;
1398 }
1399 }
1400 count
1401}
1402
1403fn declared_count(rows: &RowsModel) -> Option<u64> {
1406 match rows {
1407 RowsModel::Fixed { count }
1408 | RowsModel::Observed { count }
1409 | RowsModel::Scale { count, .. } => Some(*count),
1410 RowsModel::RelationChildren { .. } => None,
1411 }
1412}
1413
1414fn distribution_kind(distribution: &ChildDistribution) -> &'static str {
1417 match distribution {
1418 ChildDistribution::Observed { .. } => "observed",
1419 ChildDistribution::Fixed { .. } => "fixed",
1420 ChildDistribution::Uniform { .. } => "uniform",
1421 ChildDistribution::Poisson { .. } => "poisson",
1422 ChildDistribution::Histogram { .. } => "histogram",
1423 }
1424}
1425
1426fn distribution_bounds(distribution: &ChildDistribution) -> (f64, f64, f64) {
1428 match distribution {
1429 ChildDistribution::Observed { mean, min, max }
1430 | ChildDistribution::Fixed { mean, min, max }
1431 | ChildDistribution::Uniform { mean, min, max }
1432 | ChildDistribution::Poisson { mean, min, max }
1433 | ChildDistribution::Histogram { mean, min, max } => (*mean, *min, *max),
1434 }
1435}
1436
1437fn has_observed_provenance(model: &SyntheticModel, table: &str) -> bool {
1439 model.source.is_some()
1440 || model
1441 .profiles
1442 .keys()
1443 .filter_map(|key| key.split_once('.'))
1444 .any(|(profiled_table, _)| profiled_table == table)
1445}
1446
1447#[derive(Clone, Copy, PartialEq, Eq)]
1449enum EdgeKind {
1450 All,
1453 Required,
1457}
1458
1459fn fk_columns_all_non_null(table: &TableModel, columns: &[String]) -> bool {
1463 columns.iter().all(|column| {
1464 table
1465 .schema
1466 .columns
1467 .iter()
1468 .find(|candidate| &candidate.name == column)
1469 .map(|candidate| !candidate.nullable)
1470 .unwrap_or(true)
1471 })
1472}
1473
1474fn fk_columns_all_nullable(table: &TableModel, columns: &[String]) -> bool {
1477 columns.iter().all(|column| {
1478 table
1479 .schema
1480 .columns
1481 .iter()
1482 .find(|candidate| &candidate.name == column)
1483 .is_some_and(|candidate| candidate.nullable)
1484 })
1485}
1486
1487fn parent_edges(model: &SyntheticModel, kind: EdgeKind) -> BTreeMap<String, BTreeSet<String>> {
1493 model
1494 .tables
1495 .iter()
1496 .map(|(name, table)| {
1497 let generation = table
1498 .relationships
1499 .iter()
1500 .map(|relationship| (relationship.references.table.clone(), &relationship.columns));
1501 let schema =
1502 table.schema.relationships.iter().map(|relationship| {
1503 (relationship.referenced_table.clone(), &relationship.columns)
1504 });
1505 let mut parents: BTreeSet<String> = BTreeSet::new();
1506 for (parent, columns) in generation.chain(schema) {
1507 if kind == EdgeKind::All || fk_columns_all_non_null(table, columns) {
1508 parents.insert(parent);
1509 }
1510 }
1511 if let RowsModel::RelationChildren { parent, .. } = &table.rows {
1512 parents.insert(parent.clone());
1513 }
1514 for planner in &table.planners {
1518 if let Some(serde_yaml_ng::Value::Sequence(items)) = planner.args.get("targets") {
1519 for item in items {
1520 if let Some(target) =
1521 item.get("table").and_then(serde_yaml_ng::Value::as_str)
1522 {
1523 parents.insert(target.to_string());
1524 }
1525 }
1526 }
1527 }
1528 parents.remove(name);
1530 (name.clone(), parents)
1531 })
1532 .collect()
1533}
1534
1535fn topo_order(
1543 selected: &BTreeSet<String>,
1544 parents: &BTreeMap<String, BTreeSet<String>>,
1545) -> (Vec<String>, Vec<String>) {
1546 let mut in_degree: BTreeMap<String, usize> = BTreeMap::new();
1547 let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
1548 for name in selected {
1549 let selected_parents: Vec<&String> = parents
1550 .get(name)
1551 .into_iter()
1552 .flatten()
1553 .filter(|parent| selected.contains(*parent))
1554 .collect();
1555 in_degree.insert(name.clone(), selected_parents.len());
1556 for parent in selected_parents {
1557 children
1558 .entry(parent.clone())
1559 .or_default()
1560 .push(name.clone());
1561 }
1562 }
1563
1564 let mut queue: Vec<String> = in_degree
1568 .iter()
1569 .filter(|(_, °ree)| degree == 0)
1570 .map(|(name, _)| name.clone())
1571 .collect();
1572 queue.sort();
1573 queue.reverse();
1574 let mut order: Vec<String> = Vec::with_capacity(selected.len());
1575 while let Some(name) = queue.pop() {
1576 order.push(name.clone());
1577 if let Some(kids) = children.get(&name) {
1578 for kid in kids {
1579 let degree = in_degree.get_mut(kid).expect("child has an in-degree");
1580 *degree -= 1;
1581 if *degree == 0 {
1582 queue.push(kid.clone());
1583 }
1584 }
1585 }
1586 queue.sort();
1587 queue.reverse();
1588 }
1589
1590 let cyclic: Vec<String> = selected
1592 .iter()
1593 .filter(|name| !order.contains(name))
1594 .cloned()
1595 .collect();
1596 (order, cyclic)
1597}
1598
1599struct PlannerInfo {
1603 kind: String,
1604 writes: Vec<String>,
1605 reads: Vec<String>,
1606 compiled: Option<Box<dyn CompiledPlanner>>,
1607}
1608
1609impl PlannerInfo {
1610 fn unresolved(kind: &str) -> Self {
1612 Self {
1613 kind: kind.to_string(),
1614 writes: Vec::new(),
1615 reads: Vec::new(),
1616 compiled: None,
1617 }
1618 }
1619}
1620
1621struct Claim {
1623 source: ClaimSource,
1624 path: String,
1625 description: Option<String>,
1626}
1627
1628enum ClaimSource {
1630 Generator,
1632 Planner { index: usize },
1634}
1635
1636fn collect_claims(table: &TableModel, planners: &[PlannerInfo]) -> BTreeMap<String, Vec<Claim>> {
1640 let mut claims: BTreeMap<String, Vec<Claim>> = BTreeMap::new();
1641 for (name, rule) in &table.columns {
1642 if rule.generator.is_some() {
1643 claims.entry(name.clone()).or_default().push(Claim {
1644 source: ClaimSource::Generator,
1645 path: format!("columns.{name}.generator"),
1646 description: None,
1647 });
1648 }
1649 }
1650 for (index, planner) in planners.iter().enumerate() {
1651 let mut claimed: BTreeSet<&str> = BTreeSet::new();
1655 for column in &planner.writes {
1656 if !claimed.insert(column.as_str()) {
1657 continue;
1658 }
1659 claims.entry(column.clone()).or_default().push(Claim {
1660 source: ClaimSource::Planner { index },
1661 path: format!("planners[{index}]"),
1662 description: Some(planner.kind.clone()),
1663 });
1664 }
1665 }
1666 claims
1667}
1668
1669fn configured_columns(config: &PlannerConfig, keys: &[&str]) -> Vec<String> {
1673 let mut columns = Vec::new();
1674 for key in keys {
1675 match config.args.get(*key) {
1676 Some(serde_yaml_ng::Value::Sequence(items)) => columns.extend(
1677 items
1678 .iter()
1679 .filter_map(serde_yaml_ng::Value::as_str)
1680 .map(str::to_string),
1681 ),
1682 Some(serde_yaml_ng::Value::Mapping(map)) => columns.extend(
1683 map.values()
1684 .filter_map(serde_yaml_ng::Value::as_str)
1685 .map(str::to_string),
1686 ),
1687 _ => {}
1688 }
1689 }
1690 columns
1691}
1692
1693fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
1695 config.args.get(key).and_then(serde_yaml_ng::Value::as_str)
1696}
1697
1698fn relationship_names(table: &TableModel) -> Vec<String> {
1701 table
1702 .relationships
1703 .iter()
1704 .filter_map(|relationship| relationship.name.clone())
1705 .chain(
1706 table
1707 .schema
1708 .relationships
1709 .iter()
1710 .filter_map(|relationship| relationship.name.clone()),
1711 )
1712 .collect()
1713}
1714
1715fn foreign_key_columns(table: &TableModel) -> BTreeSet<String> {
1718 table
1719 .relationships
1720 .iter()
1721 .flat_map(|relationship| relationship.columns.iter().cloned())
1722 .chain(
1723 table
1724 .schema
1725 .relationships
1726 .iter()
1727 .flat_map(|relationship| relationship.columns.iter().cloned()),
1728 )
1729 .collect()
1730}
1731
1732fn relationship_of(table: &TableModel, column: &str) -> Option<String> {
1734 table
1735 .relationships
1736 .iter()
1737 .find(|relationship| relationship.columns.iter().any(|c| c == column))
1738 .and_then(|relationship| relationship.name.clone())
1739 .or_else(|| {
1740 table
1741 .schema
1742 .relationships
1743 .iter()
1744 .find(|relationship| relationship.columns.iter().any(|c| c == column))
1745 .and_then(|relationship| relationship.name.clone())
1746 })
1747}
1748
1749fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
1751 match seed {
1752 ResolvedTableSeed::Inherited(root)
1753 | ResolvedTableSeed::Fixed(root)
1754 | ResolvedTableSeed::Random(root) => *root,
1755 }
1756}
1757
1758#[derive(Clone, PartialEq, Eq)]
1760enum DepNode {
1761 Column(String),
1762 Planner(usize),
1763}
1764
1765fn report_dependency_cycles(
1770 table_name: &str,
1771 table: &TableModel,
1772 columns: &[PlannedColumn],
1773 planners: &[PlannerInfo],
1774 bag: &mut DiagnosticBag,
1775) {
1776 let mut nodes: Vec<DepNode> = columns
1777 .iter()
1778 .map(|column| DepNode::Column(column.schema.name.clone()))
1779 .collect();
1780 nodes.extend((0..planners.len()).map(DepNode::Planner));
1781
1782 let index_of = |node: &DepNode| nodes.iter().position(|candidate| candidate == node);
1783 let mut edges: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
1784 let add_edge = |from: &DepNode, to: &DepNode, edges: &mut Vec<Vec<usize>>| {
1785 if let (Some(from), Some(to)) = (index_of(from), index_of(to)) {
1786 edges[from].push(to);
1787 }
1788 };
1789
1790 for planned in columns {
1792 if matches!(planned.owner, ColumnOwner::Generator { .. }) {
1793 for read in generator_reads(table, &planned.schema.name) {
1794 add_edge(
1795 &DepNode::Column(read),
1796 &DepNode::Column(planned.schema.name.clone()),
1797 &mut edges,
1798 );
1799 }
1800 }
1801 }
1802 for (index, planner) in planners.iter().enumerate() {
1805 for read in &planner.reads {
1806 add_edge(
1807 &DepNode::Column(read.clone()),
1808 &DepNode::Planner(index),
1809 &mut edges,
1810 );
1811 }
1812 for write in &planner.writes {
1813 add_edge(
1814 &DepNode::Planner(index),
1815 &DepNode::Column(write.clone()),
1816 &mut edges,
1817 );
1818 }
1819 }
1820
1821 for component in strongly_connected_components(&edges) {
1822 let self_loop = component.len() == 1 && edges[component[0]].contains(&component[0]);
1823 if component.len() <= 1 && !self_loop {
1824 continue;
1825 }
1826 let cycle_columns: Vec<String> = component
1827 .iter()
1828 .filter_map(|&node| match &nodes[node] {
1829 DepNode::Column(name) => Some(name.clone()),
1830 DepNode::Planner(_) => None,
1831 })
1832 .collect();
1833 if owned_by_single_planner(&cycle_columns, columns) {
1834 continue;
1835 }
1836 bag.error(
1837 crate::diagnostic::codes::COLUMN_CYCLE.code,
1838 format!("tables.{table_name}.columns"),
1839 format!(
1840 "columns on table `{table_name}` form a read/write dependency cycle: {}",
1841 cycle_columns.join(", ")
1842 ),
1843 );
1844 }
1845}
1846
1847fn column_eval_order(table: &TableModel, columns: &[PlannedColumn]) -> Vec<usize> {
1858 let n = columns.len();
1859 let index_of: BTreeMap<&str, usize> = columns
1860 .iter()
1861 .enumerate()
1862 .map(|(index, column)| (column.schema.name.as_str(), index))
1863 .collect();
1864
1865 let mut successors: Vec<Vec<usize>> = vec![Vec::new(); n];
1866 let mut in_degree = vec![0usize; n];
1867 for (reader, column) in columns.iter().enumerate() {
1868 if !matches!(column.owner, ColumnOwner::Generator { .. }) {
1869 continue;
1870 }
1871 for read in generator_reads(table, &column.schema.name) {
1872 if let Some(&source) = index_of.get(read.as_str()) {
1873 if source != reader {
1874 successors[source].push(reader);
1875 in_degree[reader] += 1;
1876 }
1877 }
1878 }
1879 }
1880
1881 let mut ready: BinaryHeap<Reverse<usize>> = (0..n)
1884 .filter(|&index| in_degree[index] == 0)
1885 .map(Reverse)
1886 .collect();
1887 let mut order = Vec::with_capacity(n);
1888 while let Some(Reverse(node)) = ready.pop() {
1889 order.push(node);
1890 for &next in &successors[node] {
1891 in_degree[next] -= 1;
1892 if in_degree[next] == 0 {
1893 ready.push(Reverse(next));
1894 }
1895 }
1896 }
1897
1898 if order.len() < n {
1901 let mut placed = vec![false; n];
1902 for &node in &order {
1903 placed[node] = true;
1904 }
1905 for (node, &is_placed) in placed.iter().enumerate() {
1906 if !is_placed {
1907 order.push(node);
1908 }
1909 }
1910 }
1911 order
1912}
1913
1914fn generator_reads(table: &TableModel, column: &str) -> Vec<String> {
1928 let Some(config) = table
1929 .columns
1930 .get(column)
1931 .and_then(|rule| rule.generator.as_ref())
1932 else {
1933 return Vec::new();
1934 };
1935
1936 let mut reads = Vec::new();
1937 let mut push = |name: &str| {
1938 let name = name.to_string();
1939 if !reads.contains(&name) {
1940 reads.push(name);
1941 }
1942 };
1943
1944 if let Some(serde_yaml_ng::Value::Sequence(items)) = config.args.get("reads") {
1945 for name in items.iter().filter_map(serde_yaml_ng::Value::as_str) {
1946 push(name);
1947 }
1948 }
1949
1950 match config.kind.as_str() {
1951 "copy" | "slug" | "before" | "after" => {
1952 if let Some(source) = config
1953 .args
1954 .get("source")
1955 .and_then(serde_yaml_ng::Value::as_str)
1956 {
1957 push(source);
1958 }
1959 }
1960 "template" => {
1961 if let Some(serde_yaml_ng::Value::Sequence(parts)) = config.args.get("parts") {
1962 for part in parts {
1963 if let Some(field) = part.get("field").and_then(serde_yaml_ng::Value::as_str) {
1964 push(field);
1965 }
1966 }
1967 }
1968 }
1969 _ => {}
1970 }
1971
1972 reads
1973}
1974
1975fn owned_by_single_planner(cycle_columns: &[String], columns: &[PlannedColumn]) -> bool {
1977 let mut planner: Option<usize> = None;
1978 for name in cycle_columns {
1979 let owner = columns
1980 .iter()
1981 .find(|planned| &planned.schema.name == name)
1982 .map(|planned| &planned.owner);
1983 match owner {
1984 Some(ColumnOwner::Planner { planner_index, .. }) => {
1985 if planner.is_some_and(|existing| existing != *planner_index) {
1986 return false;
1987 }
1988 planner = Some(*planner_index);
1989 }
1990 _ => return false,
1991 }
1992 }
1993 planner.is_some()
1994}
1995
1996fn strongly_connected_components(edges: &[Vec<usize>]) -> Vec<Vec<usize>> {
1999 struct State<'a> {
2000 edges: &'a [Vec<usize>],
2001 index: usize,
2002 indices: Vec<Option<usize>>,
2003 low: Vec<usize>,
2004 on_stack: Vec<bool>,
2005 stack: Vec<usize>,
2006 components: Vec<Vec<usize>>,
2007 }
2008
2009 fn connect(state: &mut State, v: usize) {
2010 state.indices[v] = Some(state.index);
2011 state.low[v] = state.index;
2012 state.index += 1;
2013 state.stack.push(v);
2014 state.on_stack[v] = true;
2015
2016 for &w in &state.edges[v] {
2017 match state.indices[w] {
2018 None => {
2019 connect(state, w);
2020 state.low[v] = state.low[v].min(state.low[w]);
2021 }
2022 Some(w_index) if state.on_stack[w] => {
2023 state.low[v] = state.low[v].min(w_index);
2024 }
2025 Some(_) => {}
2026 }
2027 }
2028
2029 if state.low[v] == state.indices[v].expect("v was assigned an index") {
2030 let mut component = Vec::new();
2031 while let Some(w) = state.stack.pop() {
2032 state.on_stack[w] = false;
2033 component.push(w);
2034 if w == v {
2035 break;
2036 }
2037 }
2038 state.components.push(component);
2039 }
2040 }
2041
2042 let n = edges.len();
2043 let mut state = State {
2044 edges,
2045 index: 0,
2046 indices: vec![None; n],
2047 low: vec![0; n],
2048 on_stack: vec![false; n],
2049 stack: Vec::new(),
2050 components: Vec::new(),
2051 };
2052 for v in 0..n {
2053 if state.indices[v].is_none() {
2054 connect(&mut state, v);
2055 }
2056 }
2057 state.components
2058}
2059
2060#[derive(Default)]
2067struct FamilyContext {
2068 facts: BTreeMap<(String, usize), serde_yaml_ng::Value>,
2070 external_owners: BTreeMap<(String, String), ExternalChildOwner>,
2072 families: Vec<FamilyMembership>,
2074}
2075
2076struct ExternalChildOwner {
2078 planner_kind: String,
2079}
2080
2081struct FamilyMembership {
2083 parent: String,
2084 child: String,
2085}
2086
2087fn is_family_producer(registry: &ExtensionRegistry, config: &PlannerConfig) -> bool {
2097 registry
2098 .planner(&config.kind)
2099 .is_some_and(|factory| factory.descriptor().cross_table)
2100 && config.args.contains_key("children")
2101}
2102
2103impl ModelCompiler {
2104 fn collect_family_facts(
2113 &self,
2114 model: &SyntheticModel,
2115 bag: &mut DiagnosticBag,
2116 ) -> FamilyContext {
2117 collect_family_facts(&self.registry, model, bag)
2118 }
2119}
2120
2121fn collect_family_facts(
2122 registry: &ExtensionRegistry,
2123 model: &SyntheticModel,
2124 bag: &mut DiagnosticBag,
2125) -> FamilyContext {
2126 let mut ctx = FamilyContext::default();
2127 for (parent_name, table) in &model.tables {
2128 for (index, config) in table.planners.iter().enumerate() {
2129 if !is_family_producer(registry, config) {
2130 continue;
2131 }
2132 let child_name = config.args.get("children").and_then(|v| v.as_str());
2133 let child = child_name.and_then(|name| model.tables.get(name).map(|t| (name, t)));
2134
2135 let mut facts = serde_yaml_ng::Mapping::new();
2136 facts.insert("child_found".into(), (child.is_some()).into());
2137
2138 if let Some((child_name, child_model)) = child {
2139 let mut columns = serde_yaml_ng::Mapping::new();
2140 for column in &child_model.schema.columns {
2141 columns.insert(
2142 column.name.clone().into(),
2143 column.source_type.clone().into(),
2144 );
2145 }
2146 facts.insert(
2147 "child_columns".into(),
2148 serde_yaml_ng::Value::Mapping(columns),
2149 );
2150
2151 if let RowsModel::RelationChildren { distribution, .. } = &child_model.rows {
2152 let (mean, min, max) = distribution_bounds(distribution);
2153 facts.insert("dist_kind".into(), distribution_kind(distribution).into());
2154 facts.insert("dist_mean".into(), mean.into());
2155 facts.insert("dist_min".into(), min.into());
2156 facts.insert("dist_max".into(), max.into());
2157 }
2158
2159 let rel_name = config.args.get("relationship").and_then(|v| v.as_str());
2160 let rel_on_child = rel_name.is_some_and(|name| {
2161 child_relationship_references(child_model, name, parent_name)
2162 });
2163 facts.insert("rel_on_child".into(), rel_on_child.into());
2164
2165 if let Some(serde_yaml_ng::Value::Mapping(mapping)) =
2168 config.args.get("child_columns")
2169 {
2170 for column_name in mapping.values().filter_map(|v| v.as_str()) {
2171 let exists = child_model
2172 .schema
2173 .columns
2174 .iter()
2175 .any(|column| column.name == column_name);
2176 if !exists {
2177 continue;
2178 }
2179 let has_generator = child_model
2180 .columns
2181 .get(column_name)
2182 .is_some_and(|rule| rule.generator.is_some());
2183 if has_generator {
2184 bag.error(
2185 crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
2186 format!("tables.{child_name}.columns.{column_name}"),
2187 format!(
2188 "column `{column_name}` on table `{child_name}` is produced by both its own generator and the `commerce.order_family` planner on table `{parent_name}`"
2189 ),
2190 );
2191 }
2192 ctx.external_owners.insert(
2193 (child_name.to_string(), column_name.to_string()),
2194 ExternalChildOwner {
2195 planner_kind: config.kind.clone(),
2196 },
2197 );
2198 }
2199 }
2200
2201 if ctx.families.iter().any(|f| f.child == child_name) {
2202 bag.error(
2205 crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
2206 format!("tables.{child_name}"),
2207 format!(
2208 "child table `{child_name}` is claimed as a family child by more than one parent; a family child must have a single producing parent"
2209 ),
2210 );
2211 } else {
2212 ctx.families.push(FamilyMembership {
2213 parent: parent_name.clone(),
2214 child: child_name.to_string(),
2215 });
2216 }
2217 }
2218
2219 ctx.facts.insert(
2220 (parent_name.clone(), index),
2221 serde_yaml_ng::Value::Mapping(facts),
2222 );
2223 }
2224 }
2225 ctx
2226}
2227
2228fn yaml_to_i128(value: &serde_yaml_ng::Value) -> Option<i128> {
2239 match value {
2240 serde_yaml_ng::Value::Number(n) => n
2241 .as_i64()
2242 .map(i128::from)
2243 .or_else(|| n.as_f64().map(|f| f as i128)),
2244 serde_yaml_ng::Value::String(s) => s.trim().parse::<i128>().ok(),
2245 _ => None,
2246 }
2247}
2248
2249fn dense_key_recipe(table: &TableModel, column: &str) -> Option<(i128, i128)> {
2250 if let Some(rule) = table.columns.get(column) {
2251 if let Some(generator) = &rule.generator {
2252 if generator.kind == "sequence" {
2253 let start = generator
2259 .args
2260 .get("start")
2261 .and_then(yaml_to_i128)
2262 .unwrap_or(0);
2263 let step = generator
2264 .args
2265 .get("step")
2266 .and_then(yaml_to_i128)
2267 .unwrap_or(1);
2268 return Some((start, step));
2269 }
2270 return None;
2272 }
2273 }
2274 let column = table.schema.columns.iter().find(|c| c.name == column)?;
2275 if column.primary_key
2281 && !column.generated
2282 && matches!(
2283 column.family,
2284 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
2285 )
2286 {
2287 return Some((1, 1));
2288 }
2289 None
2290}
2291
2292fn build_relation_facts(
2299 model: &SyntheticModel,
2300 table: &TableModel,
2301 resolved: &BTreeMap<String, u64>,
2302) -> serde_yaml_ng::Value {
2303 use serde_yaml_ng::{Mapping, Value};
2304
2305 let recipe_map = |recipe: Option<(i128, i128)>| -> Mapping {
2306 let mut m = Mapping::new();
2307 match recipe {
2308 Some((start, step)) => {
2309 m.insert("dense".into(), true.into());
2310 m.insert("start".into(), (start as i64).into());
2311 m.insert("step".into(), (step as i64).into());
2312 }
2313 None => {
2314 m.insert("dense".into(), false.into());
2315 }
2316 }
2317 m
2318 };
2319
2320 let mut relationships = Mapping::new();
2321 let generation = table.relationships.iter().map(|rel| {
2322 (
2323 rel.name.clone(),
2324 rel.references.table.clone(),
2325 rel.references.columns.clone(),
2326 )
2327 });
2328 let schema = table.schema.relationships.iter().map(|rel| {
2329 (
2330 rel.name.clone(),
2331 rel.referenced_table.clone(),
2332 rel.referenced_columns.clone(),
2333 )
2334 });
2335 for (name, parent_table, parent_columns) in generation.chain(schema) {
2336 let Some(name) = name else { continue };
2337 let parent_column = parent_columns.first().cloned().unwrap_or_default();
2338 let recipe = model
2339 .tables
2340 .get(&parent_table)
2341 .and_then(|parent| dense_key_recipe(parent, &parent_column));
2342 let mut entry = recipe_map(recipe);
2343 entry.insert("parent_table".into(), parent_table.clone().into());
2344 entry.insert("parent_column".into(), parent_column.into());
2345 entry.insert(
2346 "count".into(),
2347 resolved.get(&parent_table).copied().unwrap_or(0).into(),
2348 );
2349 relationships.insert(name.into(), Value::Mapping(entry));
2350 }
2351
2352 let mut tables = Mapping::new();
2353 for (name, target) in &model.tables {
2354 let count = resolved.get(name).copied().unwrap_or(0);
2355 let mut keys = Mapping::new();
2356 for column in &target.schema.columns {
2357 if let Some(recipe) = dense_key_recipe(target, &column.name) {
2358 let mut key_entry = recipe_map(Some(recipe));
2359 key_entry.insert("count".into(), count.into());
2363 keys.insert(column.name.clone().into(), Value::Mapping(key_entry));
2364 }
2365 }
2366 let mut entry = Mapping::new();
2367 entry.insert("count".into(), count.into());
2368 entry.insert("keys".into(), Value::Mapping(keys));
2369 let primary_key = target.schema.primary_key.first().cloned().or_else(|| {
2372 target
2373 .schema
2374 .columns
2375 .iter()
2376 .find(|column| column.primary_key)
2377 .map(|column| column.name.clone())
2378 });
2379 if let Some(primary_key) = primary_key {
2380 entry.insert("primary_key".into(), primary_key.into());
2381 }
2382 tables.insert(name.clone().into(), Value::Mapping(entry));
2383 }
2384
2385 let mut root = Mapping::new();
2386 root.insert("relationships".into(), Value::Mapping(relationships));
2387 root.insert("tables".into(), Value::Mapping(tables));
2388 root.insert(
2392 "self_count".into(),
2393 resolved
2394 .get(&table.schema.name)
2395 .copied()
2396 .unwrap_or(0)
2397 .into(),
2398 );
2399 Value::Mapping(root)
2400}
2401
2402fn child_relationship_references(child: &TableModel, name: &str, parent: &str) -> bool {
2408 let generation = child.relationships.iter().any(|relationship| {
2409 relationship.name.as_deref() == Some(name) && relationship.references.table == parent
2410 });
2411 let schema = child.schema.relationships.iter().any(|relationship| {
2412 relationship.name.as_deref() == Some(name) && relationship.referenced_table == parent
2413 });
2414 generation || schema
2415}
2416
2417fn build_phases(
2421 order: &[String],
2422 family_ctx: &FamilyContext,
2423 budget_bytes: u64,
2424 bag: &mut DiagnosticBag,
2425) -> Vec<ExecutionPhase> {
2426 let ordered: BTreeSet<&str> = order.iter().map(String::as_str).collect();
2427 let child_tables: BTreeSet<&str> = family_ctx
2428 .families
2429 .iter()
2430 .map(|family| family.child.as_str())
2431 .collect();
2432 let mut phases = Vec::with_capacity(order.len());
2433 for name in order {
2434 if child_tables.contains(name.as_str()) {
2435 continue;
2436 }
2437 match family_ctx
2438 .families
2439 .iter()
2440 .find(|family| &family.parent == name)
2441 {
2442 Some(family) if ordered.contains(family.child.as_str()) => {
2446 phases.push(ExecutionPhase::Family(FamilyPhase {
2447 name: name.clone(),
2448 tables: vec![name.clone(), family.child.clone()],
2449 budget_bytes,
2450 }));
2451 }
2452 Some(family) => {
2453 bag.warning(
2454 crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
2455 format!("tables.{name}.planners"),
2456 format!(
2457 "family child `{}` of `{name}` was excluded; generating `{name}` without its correlated child rows",
2458 family.child
2459 ),
2460 );
2461 phases.push(ExecutionPhase::Table(name.clone()));
2462 }
2463 None => phases.push(ExecutionPhase::Table(name.clone())),
2464 }
2465 }
2466 phases
2467}
2468
2469fn compile_relationship(relationship: &RelationshipModel) -> CompiledRelationship {
2472 CompiledRelationship {
2473 name: relationship.name.clone(),
2474 columns: relationship.columns.clone(),
2475 parent_table: relationship.references.table.clone(),
2476 parent_columns: relationship.references.columns.clone(),
2477 distribution: parse_distribution(relationship.distribution.as_deref()),
2478 null_permille: 0,
2479 }
2480}
2481
2482fn parse_distribution(name: Option<&str>) -> RelationshipDistribution {
2485 match name {
2486 Some("sequential") => RelationshipDistribution::Sequential,
2487 Some("weighted") => RelationshipDistribution::Weighted,
2488 Some("observed") => RelationshipDistribution::Observed,
2489 _ => RelationshipDistribution::Uniform,
2490 }
2491}
2492
2493fn fold_foreign_key_generators(
2502 table_name: &str,
2503 table: &TableModel,
2504 relationships: &mut [CompiledRelationship],
2505 bag: &mut DiagnosticBag,
2506) {
2507 for (column, rule) in &table.columns {
2508 let Some(generator) = &rule.generator else {
2509 continue;
2510 };
2511 if generator.kind != "relation.foreign_key" && generator.kind != "relation.composite_key" {
2512 continue;
2513 }
2514 let Some(relationship) = relationships
2515 .iter_mut()
2516 .find(|relationship| relationship.columns.iter().any(|c| c == column))
2517 else {
2518 bag.error(
2519 crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
2520 format!("tables.{table_name}.columns.{column}.generator"),
2521 format!(
2522 "column `{column}` on table `{table_name}` uses generator `{}` but no relationship declares it as a foreign key; declare a `relationships:` entry covering it",
2523 generator.kind
2524 ),
2525 );
2526 continue;
2527 };
2528 if let Some(name) = generator.args.get("distribution").and_then(|v| v.as_str()) {
2529 relationship.distribution = parse_distribution(Some(name));
2530 }
2531 if let Some(rate) = generator.args.get("null_rate").and_then(|v| v.as_f64()) {
2532 relationship.null_permille = (rate.clamp(0.0, 1.0) * 1000.0).round() as u16;
2533 }
2534 }
2535}
2536
2537fn resolve_seed(seed: &TableSeed, root_seed: u64) -> ResolvedTableSeed {
2539 match seed {
2540 TableSeed::Inherit => ResolvedTableSeed::Inherited(SeedRoot::new(root_seed)),
2541 TableSeed::Random => ResolvedTableSeed::Random(SeedRoot::new(rand::random())),
2542 TableSeed::Fixed(seed) => ResolvedTableSeed::Fixed(SeedRoot::new(*seed)),
2543 }
2544}
2545
2546fn compile_output(model: &SyntheticModel) -> CompiledOutput {
2548 CompiledOutput {
2549 dialect: model.output.dialect.as_ref().and_then(|d| d.parse().ok()),
2550 mode: model.output.mode,
2551 inserts: model.output.inserts,
2552 batch_size: model.output.batch_size,
2553 }
2554}
2555
2556fn compile_globs(patterns: &[String], bag: &mut DiagnosticBag) -> Vec<Pattern> {
2559 patterns
2560 .iter()
2561 .filter_map(|pattern| match Pattern::new(pattern) {
2562 Ok(compiled) => Some(compiled),
2563 Err(error) => {
2564 bag.error(
2565 crate::diagnostic::codes::INVALID_GLOB.code,
2566 "options",
2567 format!("invalid table glob `{pattern}`: {error}"),
2568 );
2569 None
2570 }
2571 })
2572 .collect()
2573}