use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
use glob::Pattern;
use rand::RngExt;
use crate::diagnostic::{DiagnosticBag, Severity, SourceLocation};
use crate::synthetic::model::{
ChildDistribution, InferenceMode, ModifierConfig, PlannerConfig, RelationshipModel, RowsModel,
SyntheticModel, TableModel, TableSeed,
};
use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
use super::plan::{
ColumnOwner, CompiledOutput, CompiledRelationship, ExecutionPhase, FamilyPhase, GenerationPlan,
PlanEstimates, PlannedColumn, PlannedTable, RelationshipDistribution, ResolvedTableSeed,
};
use super::registry::{
ColumnScope, CompileContext, CompiledModifier, CompiledPlanner, ExtensionRegistry,
};
use super::seed::{SeedRoot, StreamId};
#[derive(Debug, Clone, PartialEq)]
pub struct TableCountOverride {
pub table: String,
pub kind: TableCountKind,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TableCountKind {
Rows(u64),
Scale(f64),
}
impl TableCountOverride {
pub fn rows(table: impl Into<String>, rows: u64) -> Self {
Self {
table: table.into(),
kind: TableCountKind::Rows(rows),
}
}
pub fn scale(table: impl Into<String>, scale: f64) -> Self {
Self {
table: table.into(),
kind: TableCountKind::Scale(scale),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct CompileOptions {
pub seed: Option<u64>,
pub scale: Option<f64>,
pub rows: Option<u64>,
pub max_rows: Option<u64>,
pub table_rows: Vec<TableCountOverride>,
pub tables: Vec<String>,
pub exclude: Vec<String>,
pub family_budget_bytes: Option<u64>,
}
const DEFAULT_FAMILY_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
pub struct ModelCompiler {
registry: ExtensionRegistry,
}
impl ModelCompiler {
pub fn new(registry: ExtensionRegistry) -> Self {
Self { registry }
}
pub fn standard() -> Self {
Self::new(ExtensionRegistry::standard())
}
pub fn registry(&self) -> &ExtensionRegistry {
&self.registry
}
pub fn compile(
&self,
model: SyntheticModel,
options: CompileOptions,
) -> Result<GenerationPlan, DiagnosticBag> {
let mut bag = DiagnosticBag::default();
if options.scale.is_some() && options.rows.is_some() {
bag.error(
crate::diagnostic::codes::COUNT_CONTROL_CONFLICT.code,
"options",
"`--scale` and `--rows` are mutually exclusive global row controls",
);
}
if let Some(scale) = options.scale {
if !scale.is_finite() || scale < 0.0 {
bag.error(
crate::diagnostic::codes::TABLE_SCALE_INVALID.code,
"options",
format!("`--scale` must be a finite, non-negative number (got {scale})"),
);
}
}
let overrides = self.collect_table_overrides(&options, &mut bag);
let selected = self.select_tables(&model, &options, &mut bag);
let all_parents = parent_edges(&model, EdgeKind::All);
let required = parent_edges(&model, EdgeKind::Required);
self.report_excluded_dependencies(&selected, &required, &mut bag);
let schema_changed = selected.len() < model.tables.len();
let root_seed = options.seed.or(model.seed).unwrap_or_else(rand::random);
let rounding_root = SeedRoot::new(root_seed);
let (mut order, mut cyclic) = topo_order(&selected, &all_parents);
if !cyclic.is_empty() {
let (required_order, required_cyclic) = topo_order(&selected, &required);
if required_cyclic.is_empty() {
order = required_order;
cyclic = Vec::new();
bag.warning(
crate::diagnostic::codes::FOREIGN_KEY_CYCLE.code,
"tables",
"nullable foreign keys form a dependency cycle; the cyclic tables cannot all be ordered parent-before-child in the output",
);
}
}
if !cyclic.is_empty() {
bag.error(
crate::diagnostic::codes::ROWS_CYCLE.code,
"tables",
format!(
"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",
cyclic.join(", ")
),
);
}
let family_ctx = self.collect_family_facts(&model, &mut bag);
let family_budget_bytes = options
.family_budget_bytes
.unwrap_or(DEFAULT_FAMILY_BUDGET_BYTES);
let mut resolved: BTreeMap<String, u64> = BTreeMap::new();
let mut tables: Vec<PlannedTable> = Vec::with_capacity(order.len());
for name in &order {
let table = &model.tables[name];
let count = self.resolve_count(
&model,
name,
table,
&options,
overrides.get(name),
rounding_root,
&resolved,
&mut bag,
);
resolved.insert(name.clone(), count);
tables.push(self.plan_table(
&model,
name,
table,
count,
root_seed,
model.defaults.inference,
&family_ctx,
&resolved,
&selected,
!schema_changed,
&mut bag,
));
}
let phases = build_phases(&order, &family_ctx, family_budget_bytes, &mut bag);
let estimates = PlanEstimates {
total_rows: resolved.values().copied().fold(0u64, u64::saturating_add),
..PlanEstimates::default()
};
if bag.has_errors() {
return Err(bag);
}
let diagnostics = bag
.diagnostics
.into_iter()
.filter(|diagnostic| diagnostic.severity == Severity::Warning)
.collect();
Ok(GenerationPlan {
input_dialect: model
.source
.as_ref()
.and_then(|source| source.dialect.parse().ok()),
output: compile_output(&model),
tables,
phases,
diagnostics,
estimates,
family_budget_bytes,
})
}
fn collect_table_overrides(
&self,
options: &CompileOptions,
bag: &mut DiagnosticBag,
) -> BTreeMap<String, TableOverride> {
let mut map: BTreeMap<String, TableOverride> = BTreeMap::new();
for over in &options.table_rows {
let entry = map.entry(over.table.clone()).or_default();
match over.kind {
TableCountKind::Rows(rows) => entry.rows = Some(rows),
TableCountKind::Scale(scale) => entry.scale = Some(scale),
}
}
for (table, over) in &map {
if over.rows.is_some() && over.scale.is_some() {
bag.error(
crate::diagnostic::codes::TABLE_COUNT_CONFLICT.code,
format!("tables.{table}"),
format!(
"table `{table}` has both `--table-rows` and `--table-scale`; they are mutually exclusive"
),
);
}
}
map
}
fn select_tables(
&self,
model: &SyntheticModel,
options: &CompileOptions,
bag: &mut DiagnosticBag,
) -> BTreeSet<String> {
let includes = compile_globs(&options.tables, bag);
let excludes = compile_globs(&options.exclude, bag);
model
.tables
.keys()
.filter(|name| {
let included =
includes.is_empty() || includes.iter().any(|pattern| pattern.matches(name));
let excluded = excludes.iter().any(|pattern| pattern.matches(name));
included && !excluded
})
.cloned()
.collect()
}
fn report_excluded_dependencies(
&self,
selected: &BTreeSet<String>,
parents: &BTreeMap<String, BTreeSet<String>>,
bag: &mut DiagnosticBag,
) {
for start in selected {
let mut reported: BTreeSet<String> = BTreeSet::new();
let mut visited: BTreeSet<String> = BTreeSet::new();
let mut stack: Vec<Vec<String>> = vec![vec![start.clone()]];
while let Some(path) = stack.pop() {
let node = path.last().expect("path is never empty");
let Some(node_parents) = parents.get(node) else {
continue;
};
for parent in node_parents {
let mut extended = path.clone();
extended.push(parent.clone());
if selected.contains(parent) {
if visited.insert(parent.clone()) {
stack.push(extended);
}
} else if reported.insert(parent.clone()) {
bag.error(
crate::diagnostic::codes::EXCLUDED_DEPENDENCY.code,
format!("tables.{start}"),
format!(
"table `{start}` requires excluded table `{parent}` via dependency path {}",
extended.join(" -> ")
),
);
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn resolve_count(
&self,
model: &SyntheticModel,
name: &str,
table: &TableModel,
options: &CompileOptions,
over: Option<&TableOverride>,
rounding_root: SeedRoot,
resolved: &BTreeMap<String, u64>,
bag: &mut DiagnosticBag,
) -> u64 {
match &table.rows {
RowsModel::RelationChildren {
parent,
distribution,
..
} => self.resolve_child_count(
name,
parent,
distribution,
options,
over,
rounding_root,
resolved,
bag,
),
rows => self.resolve_root_count(model, name, rows, options, over, rounding_root, bag),
}
}
#[allow(clippy::too_many_arguments)]
fn resolve_root_count(
&self,
model: &SyntheticModel,
name: &str,
rows: &RowsModel,
options: &CompileOptions,
over: Option<&TableOverride>,
rounding_root: SeedRoot,
bag: &mut DiagnosticBag,
) -> u64 {
if matches!(rows, RowsModel::Observed { .. }) && !has_observed_provenance(model, name) {
bag.error(
crate::diagnostic::codes::ROWS_OBSERVED_MISSING.code,
format!("tables.{name}.rows"),
format!(
"table `{name}` uses `rows.kind: observed` but the model has no attached source or profile to resolve the observed count from"
),
);
}
let base = declared_count(rows).unwrap_or(0) as f64;
let mut target = match (options.scale, options.rows) {
(Some(scale), _) => base * scale,
(None, Some(rows)) => rows as f64,
(None, None) => base,
};
match over.map(TableOverride::effective) {
Some(EffectiveOverride::Rows(rows)) => target = rows as f64,
Some(EffectiveOverride::Scale(scale)) => target = base * scale,
None | Some(EffectiveOverride::Conflict) => {}
}
let count = stochastic_round(target, rounding_root, name);
apply_max_rows(count, options.max_rows, name, bag)
}
#[allow(clippy::too_many_arguments)]
fn resolve_child_count(
&self,
name: &str,
parent: &str,
distribution: &ChildDistribution,
options: &CompileOptions,
over: Option<&TableOverride>,
rounding_root: SeedRoot,
resolved: &BTreeMap<String, u64>,
bag: &mut DiagnosticBag,
) -> u64 {
let Some(&parent_count) = resolved.get(parent) else {
return 0;
};
let (mean, min, _max) = distribution_bounds(distribution);
let derived = parent_count as f64 * mean;
let target = match over.map(TableOverride::effective) {
Some(EffectiveOverride::Rows(rows)) => rows as f64,
Some(EffectiveOverride::Scale(scale)) => derived * scale,
None | Some(EffectiveOverride::Conflict) => derived,
};
let count = stochastic_round(target, rounding_root, name);
let count = apply_max_rows(count, options.max_rows, name, bag);
let minimum = (parent_count as f64 * min).ceil() as u64;
if count < minimum {
bag.error(
crate::diagnostic::codes::CHILD_COUNT_IMPOSSIBLE.code,
format!("tables.{name}.rows"),
format!(
"table `{name}` resolves to {count} rows, but its {parent_count} parents in `{parent}` each require at least {min} child(ren) ({minimum} total)"
),
);
}
count
}
#[allow(clippy::too_many_arguments)]
fn plan_table(
&self,
model: &SyntheticModel,
name: &str,
table: &TableModel,
rows: u64,
root_seed: u64,
inference: InferenceMode,
family_ctx: &FamilyContext,
resolved: &BTreeMap<String, u64>,
selected: &BTreeSet<String>,
preserve_raw: bool,
bag: &mut DiagnosticBag,
) -> PlannedTable {
let seed = resolve_seed(&table.seed, root_seed);
let compile_seed = seed_root_of(&seed);
let mut seen_columns: BTreeSet<&str> = BTreeSet::new();
for column in &table.schema.columns {
if !seen_columns.insert(column.name.as_str()) {
bag.error(
crate::diagnostic::codes::DUPLICATE_COLUMN.code,
format!("tables.{name}.schema.columns"),
format!(
"table `{name}` declares column `{}` more than once",
column.name
),
);
}
}
self.validate_column_operator_arguments(name, table, bag);
let mut relationships: Vec<CompiledRelationship> = table
.relationships
.iter()
.map(compile_relationship)
.collect();
for schema_rel in &table.schema.relationships {
if relationships
.iter()
.any(|existing| existing.columns == schema_rel.columns)
{
continue;
}
relationships.push(CompiledRelationship {
name: schema_rel.name.clone(),
columns: schema_rel.columns.clone(),
parent_table: schema_rel.referenced_table.clone(),
parent_columns: schema_rel.referenced_columns.clone(),
distribution: RelationshipDistribution::default(),
null_permille: 0,
});
}
fold_foreign_key_generators(name, table, &mut relationships, bag);
relationships.retain(|relationship| {
if selected.contains(&relationship.parent_table) {
return true;
}
if !fk_columns_all_non_null(table, &relationship.columns) {
bag.warning(
crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
format!("tables.{name}"),
format!(
"optional relationship `{}` on table `{name}` references excluded table `{}`; its foreign key is detached and omitted from the rendered DDL",
relationship.name.as_deref().unwrap_or("(unnamed)"),
relationship.parent_table
),
);
}
false
});
for relationship in &relationships {
let parent_is_empty = resolved
.get(&relationship.parent_table)
.is_some_and(|count| *count == 0);
if rows > 0 && parent_is_empty && !fk_columns_all_nullable(table, &relationship.columns)
{
bag.error(
crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
format!("tables.{name}.relationships"),
format!(
"table `{name}` resolves to {rows} row(s), but required relationship `{}` targets empty parent table `{}`",
relationship.name.as_deref().unwrap_or("(unnamed)"),
relationship.parent_table
),
);
}
}
let planners =
self.compile_planners(model, name, table, compile_seed, family_ctx, resolved, bag);
let claims = collect_claims(table, &planners);
let columns: Vec<PlannedColumn> = table
.schema
.columns
.iter()
.map(|column| {
let owner = self.resolve_owner(
name,
table,
column,
claims.get(&column.name).map(Vec::as_slice).unwrap_or(&[]),
&planners,
family_ctx,
compile_seed,
inference,
bag,
);
let modifiers =
self.compile_modifiers(name, table, column, &owner, compile_seed, bag);
PlannedColumn {
schema: column.clone(),
owner,
modifiers,
}
})
.collect();
report_dependency_cycles(name, table, &columns, &planners, bag);
let eval_order = column_eval_order(table, &columns);
let compiled_planners = planners.into_iter().filter_map(|p| p.compiled).collect();
let present_columns: BTreeSet<&str> = table
.schema
.columns
.iter()
.map(|c| c.name.as_str())
.collect();
let mut schema = table.schema.clone();
schema
.relationships
.retain(|relationship| selected.contains(&relationship.referenced_table));
schema.indexes.retain(|index| {
index
.columns
.iter()
.all(|c| present_columns.contains(c.as_str()))
});
if !preserve_raw {
schema.create_statement = None;
}
PlannedTable {
name: name.to_string(),
rows,
schema,
seed,
columns,
relationships,
planners: compiled_planners,
eval_order,
}
}
#[allow(clippy::too_many_arguments)]
fn compile_planners(
&self,
model: &SyntheticModel,
table_name: &str,
table: &TableModel,
seed: SeedRoot,
family_ctx: &FamilyContext,
resolved: &BTreeMap<String, u64>,
bag: &mut DiagnosticBag,
) -> Vec<PlannerInfo> {
let relationship_names = relationship_names(table);
let relation_facts = build_relation_facts(model, table, resolved);
table
.planners
.iter()
.enumerate()
.map(|(index, config)| {
let path = format!("tables.{table_name}.planners[{index}]");
let Some(factory) = self.registry.planner(&config.kind) else {
bag.error(
crate::diagnostic::codes::PLANNER_UNKNOWN.code,
path,
format!("no planner registered for kind `{}`", config.kind),
);
return PlannerInfo::unresolved(&config.kind);
};
let descriptor = factory.descriptor();
validate_operator_arguments(
&config.args,
descriptor.arguments,
&path,
"planner",
&config.kind,
bag,
);
let is_family = config.args.contains_key("children");
let is_cross_table = descriptor.cross_table;
let injected;
let config = if let Some(facts) = family_ctx.facts.get(&(table_name.to_string(), index)) {
let mut cloned = config.clone();
cloned.args.insert(
super::planners::order_family::FAMILY_FACTS_KEY.to_string(),
facts.clone(),
);
injected = cloned;
&injected
} else if !is_family
&& (is_cross_table || config.args.contains_key("relationship"))
{
let mut cloned = config.clone();
cloned.args.insert(
super::planners::structural::RELATION_FACTS_KEY.to_string(),
relation_facts.clone(),
);
injected = cloned;
&injected
} else {
config
};
let writes = match descriptor.writes {
ColumnScope::Configured => configured_columns(config, &["columns", "writes"]),
_ => Vec::new(),
};
let reads = match descriptor.reads {
ColumnScope::Configured => configured_columns(config, &["reads"]),
_ => Vec::new(),
};
if !is_family {
if let Some(referenced) = string_arg(config, "relationship") {
if !relationship_names.iter().any(|n| n == referenced) {
bag.error(
crate::diagnostic::codes::RELATIONSHIP_UNKNOWN.code,
format!("{path}.relationship"),
format!(
"planner `{}` references relationship `{referenced}`, which is not declared on table `{table_name}`",
config.kind
),
);
}
}
}
let context = CompileContext::for_table(&table.schema, seed, &path);
let compiled = match factory.compile(config, &context) {
Ok(compiled) => Some(compiled),
Err(errors) => {
bag.diagnostics.extend(errors.diagnostics);
None
}
};
PlannerInfo {
kind: descriptor.kind.to_string(),
writes,
reads,
compiled,
}
})
.collect()
}
fn validate_column_operator_arguments(
&self,
table_name: &str,
table: &TableModel,
bag: &mut DiagnosticBag,
) {
for (column_name, rule) in &table.columns {
if let Some(config) = &rule.generator {
if let Some(factory) = self.registry.generator(&config.kind) {
validate_operator_arguments(
&config.args,
factory.descriptor().arguments,
&format!("tables.{table_name}.columns.{column_name}.generator"),
"generator",
&config.kind,
bag,
);
}
}
for (index, config) in rule.modifiers.iter().enumerate() {
if let Some(factory) = self.registry.modifier(&config.kind) {
validate_operator_arguments(
&config.args,
factory.descriptor().arguments,
&format!("tables.{table_name}.columns.{column_name}.modifiers[{index}]"),
"modifier",
&config.kind,
bag,
);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn resolve_owner(
&self,
table_name: &str,
table: &TableModel,
column: &PortableColumn,
claimants: &[Claim],
planners: &[PlannerInfo],
family_ctx: &FamilyContext,
seed: SeedRoot,
inference: InferenceMode,
bag: &mut DiagnosticBag,
) -> ColumnOwner {
if claimants.len() > 1 {
let diagnostic = bag.error(
crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
format!("tables.{table_name}.columns.{}", column.name),
format!(
"tables.{table_name}.columns.{} is produced by more than one owner",
column.name
),
);
diagnostic.related = claimants
.iter()
.map(|claim| SourceLocation {
path: claim.path.clone(),
description: claim.description.clone(),
})
.collect();
diagnostic.help = Some(format!(
"keep a single owner for `{}`: remove the column generator or drop it from the planner mapping",
column.name
));
return ColumnOwner::GeneratedByDatabase;
}
if let Some(claim) = claimants.first() {
return match &claim.source {
ClaimSource::Generator => {
self.compile_generator(table_name, table, column, seed, bag)
}
ClaimSource::Planner { index } => ColumnOwner::Planner {
kind: planners[*index].kind.clone(),
planner_index: *index,
},
};
}
if let Some(external) = family_ctx
.external_owners
.get(&(table_name.to_string(), column.name.clone()))
{
return ColumnOwner::FamilyChild {
planner_kind: external.planner_kind.clone(),
};
}
self.infer_structural_owner(table_name, table, column, inference, seed, bag)
}
fn compile_generator(
&self,
table_name: &str,
table: &TableModel,
column: &PortableColumn,
seed: SeedRoot,
bag: &mut DiagnosticBag,
) -> ColumnOwner {
let path = format!("tables.{table_name}.columns.{}.generator", column.name);
let config = table.columns[&column.name]
.generator
.as_ref()
.expect("generator claim implies a generator rule");
self.compile_generator_config(table, column, config, path, seed, bag)
}
fn compile_generator_config(
&self,
table: &TableModel,
column: &PortableColumn,
config: &crate::synthetic::model::GeneratorConfig,
path: String,
seed: SeedRoot,
bag: &mut DiagnosticBag,
) -> ColumnOwner {
let Some(factory) = self.registry.generator(&config.kind) else {
bag.error(
crate::diagnostic::codes::GENERATOR_UNKNOWN.code,
path,
format!("no generator registered for kind `{}`", config.kind),
);
return ColumnOwner::GeneratedByDatabase;
};
let descriptor = factory.descriptor();
if !descriptor.accepts.contains(&column.family) {
bag.error(
crate::diagnostic::codes::GENERATOR_TYPE.code,
path,
format!(
"generator `{}` cannot produce column `{}` of type family {:?}",
config.kind, column.name, column.family
),
);
return ColumnOwner::GeneratedByDatabase;
}
let context = CompileContext::for_column(&table.schema, column, seed, &path);
match factory.compile(config, &context) {
Ok(compiled) => ColumnOwner::Generator {
kind: descriptor.kind.to_string(),
compiled,
},
Err(errors) => {
bag.diagnostics.extend(errors.diagnostics);
ColumnOwner::GeneratedByDatabase
}
}
}
fn infer_structural_owner(
&self,
table_name: &str,
table: &TableModel,
column: &PortableColumn,
inference: InferenceMode,
seed: SeedRoot,
bag: &mut DiagnosticBag,
) -> ColumnOwner {
if column.generated || column.identity {
return ColumnOwner::GeneratedByDatabase;
}
if foreign_key_columns(table).contains(&column.name) {
return ColumnOwner::Relationship {
relationship: relationship_of(table, &column.name),
};
}
if column.default_sql.is_some() {
return ColumnOwner::DatabaseDefault;
}
if matches!(inference, InferenceMode::Schema)
&& column.primary_key
&& matches!(
column.family,
SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
)
{
return ColumnOwner::GeneratedByDatabase;
}
match inference {
InferenceMode::Schema => {
let config =
crate::profile::heuristics::schema_inferred_generator(&table.schema, column);
let path = format!(
"tables.{table_name}.columns.{}.generator[inferred]",
column.name
);
self.compile_generator_config(table, column, &config, path, seed, bag)
}
InferenceMode::Disabled => {
bag.error(
crate::diagnostic::codes::COLUMN_OWNER_MISSING.code,
format!("tables.{table_name}.columns.{}", column.name),
format!(
"column `{}` on table `{table_name}` has no generator, planner, relationship, or database default to produce its value",
column.name
),
);
ColumnOwner::GeneratedByDatabase
}
}
}
fn compile_modifiers(
&self,
table_name: &str,
table: &TableModel,
column: &PortableColumn,
owner: &ColumnOwner,
seed: SeedRoot,
bag: &mut DiagnosticBag,
) -> Vec<Box<dyn CompiledModifier>> {
let empty_rule;
let rule = match table.columns.get(&column.name) {
Some(rule) => rule,
None => {
empty_rule = crate::synthetic::model::ColumnRule {
semantic: None,
generator: None,
modifiers: Vec::new(),
};
&empty_rule
}
};
let is_generator = matches!(owner, ColumnOwner::Generator { .. });
let mut compiled: Vec<Box<dyn CompiledModifier>> = Vec::new();
for (index, modifier) in rule.modifiers.iter().enumerate() {
let path = format!(
"tables.{table_name}.columns.{}.modifiers[{index}]",
column.name
);
let Some(factory) = self.registry.modifier(&modifier.kind) else {
bag.error(
crate::diagnostic::codes::MODIFIER_UNKNOWN.code,
path,
format!("no modifier registered for kind `{}`", modifier.kind),
);
continue;
};
if !factory.descriptor().accepts.contains(&column.family) {
bag.error(
crate::diagnostic::codes::MODIFIER_TYPE.code,
path,
format!(
"modifier `{}` cannot transform column `{}` of type family {:?}",
modifier.kind, column.name, column.family
),
);
continue;
}
if !is_generator {
continue;
}
let context = CompileContext::for_column(&table.schema, column, seed, &path);
match factory.compile(modifier, &context) {
Ok(operator) => compiled.push(operator),
Err(errors) => bag.diagnostics.extend(errors.diagnostics),
}
}
self.enforce_key_uniqueness(
table_name,
table,
column,
owner,
rule,
seed,
&mut compiled,
bag,
);
compiled
}
#[allow(clippy::too_many_arguments)]
fn enforce_key_uniqueness(
&self,
table_name: &str,
table: &TableModel,
column: &PortableColumn,
owner: &ColumnOwner,
rule: &crate::synthetic::model::ColumnRule,
seed: SeedRoot,
compiled: &mut Vec<Box<dyn CompiledModifier>>,
bag: &mut DiagnosticBag,
) {
let ColumnOwner::Generator {
compiled: generator,
..
} = owner
else {
return;
};
if !is_single_column_key(&table.schema, column) {
return;
}
if generator.is_inherently_unique() {
return;
}
if rule
.modifiers
.iter()
.any(|modifier| modifier.kind == "unique")
{
return;
}
let Some(factory) = self.registry.modifier("unique") else {
return;
};
let path = format!(
"tables.{table_name}.columns.{}.modifiers[auto-unique]",
column.name
);
let config = ModifierConfig {
kind: "unique".to_string(),
args: [(
"on_exhaustion".to_string(),
serde_yaml_ng::Value::from("error"),
)]
.into_iter()
.collect(),
};
let context = CompileContext::for_column(&table.schema, column, seed, &path);
match factory.compile(&config, &context) {
Ok(operator) => compiled.push(operator),
Err(errors) => bag.diagnostics.extend(errors.diagnostics),
}
}
}
fn validate_operator_arguments(
args: &BTreeMap<String, serde_yaml_ng::Value>,
expected: &[super::registry::ArgumentSpec],
path: &str,
operator_type: &str,
kind: &str,
bag: &mut DiagnosticBag,
) {
for argument in args.keys() {
if expected.iter().any(|spec| spec.name == argument) {
continue;
}
let diagnostic = bag.error(
crate::diagnostic::codes::OPERATOR_UNKNOWN_ARGUMENT.code,
format!("{path}.{argument}"),
format!("{operator_type} `{kind}` does not accept argument `{argument}`"),
);
if !expected.is_empty() {
diagnostic.help = Some(format!(
"supported arguments: {}",
expected
.iter()
.map(|spec| spec.name)
.collect::<Vec<_>>()
.join(", ")
));
}
}
}
fn primary_key_columns(table: &PortableTable) -> BTreeSet<&str> {
let mut columns: BTreeSet<&str> = table.primary_key.iter().map(String::as_str).collect();
columns.extend(
table
.columns
.iter()
.filter(|column| column.primary_key)
.map(|column| column.name.as_str()),
);
columns
}
fn is_single_column_key(table: &PortableTable, column: &PortableColumn) -> bool {
let primary = primary_key_columns(table);
if primary.len() == 1 && primary.contains(column.name.as_str()) {
return true;
}
if column.unique {
return true;
}
let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
table
.unique_constraints
.iter()
.any(|constraint| single(&constraint.columns))
|| table
.indexes
.iter()
.any(|index| index.unique && single(&index.columns))
}
#[derive(Debug, Default, Clone, Copy)]
struct TableOverride {
rows: Option<u64>,
scale: Option<f64>,
}
enum EffectiveOverride {
Rows(u64),
Scale(f64),
Conflict,
}
impl TableOverride {
fn effective(&self) -> EffectiveOverride {
match (self.rows, self.scale) {
(Some(_), Some(_)) => EffectiveOverride::Conflict,
(Some(rows), None) => EffectiveOverride::Rows(rows),
(None, Some(scale)) => EffectiveOverride::Scale(scale),
(None, None) => EffectiveOverride::Conflict,
}
}
}
fn apply_max_rows(count: u64, max_rows: Option<u64>, name: &str, bag: &mut DiagnosticBag) -> u64 {
match max_rows {
Some(max) if count > max => {
bag.warning(
crate::diagnostic::codes::MAX_ROWS_CAPPED.code,
format!("tables.{name}.rows"),
format!("table `{name}` row count capped from {count} to {max} by `--max-rows`"),
);
max
}
_ => count,
}
}
fn stochastic_round(value: f64, root: SeedRoot, table: &str) -> u64 {
if value <= 0.0 {
return 0;
}
let floor = value.floor();
let fraction = value - floor;
let mut count = floor as u64;
if fraction > 0.0 {
let mut rng = root.stream(StreamId::rounding(table));
if rng.random::<f64>() < fraction {
count += 1;
}
}
count
}
fn declared_count(rows: &RowsModel) -> Option<u64> {
match rows {
RowsModel::Fixed { count }
| RowsModel::Observed { count }
| RowsModel::Scale { count, .. } => Some(*count),
RowsModel::RelationChildren { .. } => None,
}
}
fn distribution_kind(distribution: &ChildDistribution) -> &'static str {
match distribution {
ChildDistribution::Observed { .. } => "observed",
ChildDistribution::Fixed { .. } => "fixed",
ChildDistribution::Uniform { .. } => "uniform",
ChildDistribution::Poisson { .. } => "poisson",
ChildDistribution::Histogram { .. } => "histogram",
}
}
fn distribution_bounds(distribution: &ChildDistribution) -> (f64, f64, f64) {
match distribution {
ChildDistribution::Observed { mean, min, max }
| ChildDistribution::Fixed { mean, min, max }
| ChildDistribution::Uniform { mean, min, max }
| ChildDistribution::Poisson { mean, min, max }
| ChildDistribution::Histogram { mean, min, max } => (*mean, *min, *max),
}
}
fn has_observed_provenance(model: &SyntheticModel, table: &str) -> bool {
model.source.is_some()
|| model
.profiles
.keys()
.filter_map(|key| key.split_once('.'))
.any(|(profiled_table, _)| profiled_table == table)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum EdgeKind {
All,
Required,
}
fn fk_columns_all_non_null(table: &TableModel, columns: &[String]) -> bool {
columns.iter().all(|column| {
table
.schema
.columns
.iter()
.find(|candidate| &candidate.name == column)
.map(|candidate| !candidate.nullable)
.unwrap_or(true)
})
}
fn fk_columns_all_nullable(table: &TableModel, columns: &[String]) -> bool {
columns.iter().all(|column| {
table
.schema
.columns
.iter()
.find(|candidate| &candidate.name == column)
.is_some_and(|candidate| candidate.nullable)
})
}
fn parent_edges(model: &SyntheticModel, kind: EdgeKind) -> BTreeMap<String, BTreeSet<String>> {
model
.tables
.iter()
.map(|(name, table)| {
let generation = table
.relationships
.iter()
.map(|relationship| (relationship.references.table.clone(), &relationship.columns));
let schema =
table.schema.relationships.iter().map(|relationship| {
(relationship.referenced_table.clone(), &relationship.columns)
});
let mut parents: BTreeSet<String> = BTreeSet::new();
for (parent, columns) in generation.chain(schema) {
if kind == EdgeKind::All || fk_columns_all_non_null(table, columns) {
parents.insert(parent);
}
}
if let RowsModel::RelationChildren { parent, .. } = &table.rows {
parents.insert(parent.clone());
}
for planner in &table.planners {
if let Some(serde_yaml_ng::Value::Sequence(items)) = planner.args.get("targets") {
for item in items {
if let Some(target) =
item.get("table").and_then(serde_yaml_ng::Value::as_str)
{
parents.insert(target.to_string());
}
}
}
}
parents.remove(name);
(name.clone(), parents)
})
.collect()
}
fn topo_order(
selected: &BTreeSet<String>,
parents: &BTreeMap<String, BTreeSet<String>>,
) -> (Vec<String>, Vec<String>) {
let mut in_degree: BTreeMap<String, usize> = BTreeMap::new();
let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
for name in selected {
let selected_parents: Vec<&String> = parents
.get(name)
.into_iter()
.flatten()
.filter(|parent| selected.contains(*parent))
.collect();
in_degree.insert(name.clone(), selected_parents.len());
for parent in selected_parents {
children
.entry(parent.clone())
.or_default()
.push(name.clone());
}
}
let mut queue: Vec<String> = in_degree
.iter()
.filter(|(_, °ree)| degree == 0)
.map(|(name, _)| name.clone())
.collect();
queue.sort();
queue.reverse();
let mut order: Vec<String> = Vec::with_capacity(selected.len());
while let Some(name) = queue.pop() {
order.push(name.clone());
if let Some(kids) = children.get(&name) {
for kid in kids {
let degree = in_degree.get_mut(kid).expect("child has an in-degree");
*degree -= 1;
if *degree == 0 {
queue.push(kid.clone());
}
}
}
queue.sort();
queue.reverse();
}
let cyclic: Vec<String> = selected
.iter()
.filter(|name| !order.contains(name))
.cloned()
.collect();
(order, cyclic)
}
struct PlannerInfo {
kind: String,
writes: Vec<String>,
reads: Vec<String>,
compiled: Option<Box<dyn CompiledPlanner>>,
}
impl PlannerInfo {
fn unresolved(kind: &str) -> Self {
Self {
kind: kind.to_string(),
writes: Vec::new(),
reads: Vec::new(),
compiled: None,
}
}
}
struct Claim {
source: ClaimSource,
path: String,
description: Option<String>,
}
enum ClaimSource {
Generator,
Planner { index: usize },
}
fn collect_claims(table: &TableModel, planners: &[PlannerInfo]) -> BTreeMap<String, Vec<Claim>> {
let mut claims: BTreeMap<String, Vec<Claim>> = BTreeMap::new();
for (name, rule) in &table.columns {
if rule.generator.is_some() {
claims.entry(name.clone()).or_default().push(Claim {
source: ClaimSource::Generator,
path: format!("columns.{name}.generator"),
description: None,
});
}
}
for (index, planner) in planners.iter().enumerate() {
let mut claimed: BTreeSet<&str> = BTreeSet::new();
for column in &planner.writes {
if !claimed.insert(column.as_str()) {
continue;
}
claims.entry(column.clone()).or_default().push(Claim {
source: ClaimSource::Planner { index },
path: format!("planners[{index}]"),
description: Some(planner.kind.clone()),
});
}
}
claims
}
fn configured_columns(config: &PlannerConfig, keys: &[&str]) -> Vec<String> {
let mut columns = Vec::new();
for key in keys {
match config.args.get(*key) {
Some(serde_yaml_ng::Value::Sequence(items)) => columns.extend(
items
.iter()
.filter_map(serde_yaml_ng::Value::as_str)
.map(str::to_string),
),
Some(serde_yaml_ng::Value::Mapping(map)) => columns.extend(
map.values()
.filter_map(serde_yaml_ng::Value::as_str)
.map(str::to_string),
),
_ => {}
}
}
columns
}
fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
config.args.get(key).and_then(serde_yaml_ng::Value::as_str)
}
fn relationship_names(table: &TableModel) -> Vec<String> {
table
.relationships
.iter()
.filter_map(|relationship| relationship.name.clone())
.chain(
table
.schema
.relationships
.iter()
.filter_map(|relationship| relationship.name.clone()),
)
.collect()
}
fn foreign_key_columns(table: &TableModel) -> BTreeSet<String> {
table
.relationships
.iter()
.flat_map(|relationship| relationship.columns.iter().cloned())
.chain(
table
.schema
.relationships
.iter()
.flat_map(|relationship| relationship.columns.iter().cloned()),
)
.collect()
}
fn relationship_of(table: &TableModel, column: &str) -> Option<String> {
table
.relationships
.iter()
.find(|relationship| relationship.columns.iter().any(|c| c == column))
.and_then(|relationship| relationship.name.clone())
.or_else(|| {
table
.schema
.relationships
.iter()
.find(|relationship| relationship.columns.iter().any(|c| c == column))
.and_then(|relationship| relationship.name.clone())
})
}
fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
match seed {
ResolvedTableSeed::Inherited(root)
| ResolvedTableSeed::Fixed(root)
| ResolvedTableSeed::Random(root) => *root,
}
}
#[derive(Clone, PartialEq, Eq)]
enum DepNode {
Column(String),
Planner(usize),
}
fn report_dependency_cycles(
table_name: &str,
table: &TableModel,
columns: &[PlannedColumn],
planners: &[PlannerInfo],
bag: &mut DiagnosticBag,
) {
let mut nodes: Vec<DepNode> = columns
.iter()
.map(|column| DepNode::Column(column.schema.name.clone()))
.collect();
nodes.extend((0..planners.len()).map(DepNode::Planner));
let index_of = |node: &DepNode| nodes.iter().position(|candidate| candidate == node);
let mut edges: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
let add_edge = |from: &DepNode, to: &DepNode, edges: &mut Vec<Vec<usize>>| {
if let (Some(from), Some(to)) = (index_of(from), index_of(to)) {
edges[from].push(to);
}
};
for planned in columns {
if matches!(planned.owner, ColumnOwner::Generator { .. }) {
for read in generator_reads(table, &planned.schema.name) {
add_edge(
&DepNode::Column(read),
&DepNode::Column(planned.schema.name.clone()),
&mut edges,
);
}
}
}
for (index, planner) in planners.iter().enumerate() {
for read in &planner.reads {
add_edge(
&DepNode::Column(read.clone()),
&DepNode::Planner(index),
&mut edges,
);
}
for write in &planner.writes {
add_edge(
&DepNode::Planner(index),
&DepNode::Column(write.clone()),
&mut edges,
);
}
}
for component in strongly_connected_components(&edges) {
let self_loop = component.len() == 1 && edges[component[0]].contains(&component[0]);
if component.len() <= 1 && !self_loop {
continue;
}
let cycle_columns: Vec<String> = component
.iter()
.filter_map(|&node| match &nodes[node] {
DepNode::Column(name) => Some(name.clone()),
DepNode::Planner(_) => None,
})
.collect();
if owned_by_single_planner(&cycle_columns, columns) {
continue;
}
bag.error(
crate::diagnostic::codes::COLUMN_CYCLE.code,
format!("tables.{table_name}.columns"),
format!(
"columns on table `{table_name}` form a read/write dependency cycle: {}",
cycle_columns.join(", ")
),
);
}
}
fn column_eval_order(table: &TableModel, columns: &[PlannedColumn]) -> Vec<usize> {
let n = columns.len();
let index_of: BTreeMap<&str, usize> = columns
.iter()
.enumerate()
.map(|(index, column)| (column.schema.name.as_str(), index))
.collect();
let mut successors: Vec<Vec<usize>> = vec![Vec::new(); n];
let mut in_degree = vec![0usize; n];
for (reader, column) in columns.iter().enumerate() {
if !matches!(column.owner, ColumnOwner::Generator { .. }) {
continue;
}
for read in generator_reads(table, &column.schema.name) {
if let Some(&source) = index_of.get(read.as_str()) {
if source != reader {
successors[source].push(reader);
in_degree[reader] += 1;
}
}
}
}
let mut ready: BinaryHeap<Reverse<usize>> = (0..n)
.filter(|&index| in_degree[index] == 0)
.map(Reverse)
.collect();
let mut order = Vec::with_capacity(n);
while let Some(Reverse(node)) = ready.pop() {
order.push(node);
for &next in &successors[node] {
in_degree[next] -= 1;
if in_degree[next] == 0 {
ready.push(Reverse(next));
}
}
}
if order.len() < n {
let mut placed = vec![false; n];
for &node in &order {
placed[node] = true;
}
for (node, &is_placed) in placed.iter().enumerate() {
if !is_placed {
order.push(node);
}
}
}
order
}
fn generator_reads(table: &TableModel, column: &str) -> Vec<String> {
let Some(config) = table
.columns
.get(column)
.and_then(|rule| rule.generator.as_ref())
else {
return Vec::new();
};
let mut reads = Vec::new();
let mut push = |name: &str| {
let name = name.to_string();
if !reads.contains(&name) {
reads.push(name);
}
};
if let Some(serde_yaml_ng::Value::Sequence(items)) = config.args.get("reads") {
for name in items.iter().filter_map(serde_yaml_ng::Value::as_str) {
push(name);
}
}
match config.kind.as_str() {
"copy" | "slug" | "before" | "after" => {
if let Some(source) = config
.args
.get("source")
.and_then(serde_yaml_ng::Value::as_str)
{
push(source);
}
}
"template" => {
if let Some(serde_yaml_ng::Value::Sequence(parts)) = config.args.get("parts") {
for part in parts {
if let Some(field) = part.get("field").and_then(serde_yaml_ng::Value::as_str) {
push(field);
}
}
}
}
_ => {}
}
reads
}
fn owned_by_single_planner(cycle_columns: &[String], columns: &[PlannedColumn]) -> bool {
let mut planner: Option<usize> = None;
for name in cycle_columns {
let owner = columns
.iter()
.find(|planned| &planned.schema.name == name)
.map(|planned| &planned.owner);
match owner {
Some(ColumnOwner::Planner { planner_index, .. }) => {
if planner.is_some_and(|existing| existing != *planner_index) {
return false;
}
planner = Some(*planner_index);
}
_ => return false,
}
}
planner.is_some()
}
fn strongly_connected_components(edges: &[Vec<usize>]) -> Vec<Vec<usize>> {
struct State<'a> {
edges: &'a [Vec<usize>],
index: usize,
indices: Vec<Option<usize>>,
low: Vec<usize>,
on_stack: Vec<bool>,
stack: Vec<usize>,
components: Vec<Vec<usize>>,
}
fn connect(state: &mut State, v: usize) {
state.indices[v] = Some(state.index);
state.low[v] = state.index;
state.index += 1;
state.stack.push(v);
state.on_stack[v] = true;
for &w in &state.edges[v] {
match state.indices[w] {
None => {
connect(state, w);
state.low[v] = state.low[v].min(state.low[w]);
}
Some(w_index) if state.on_stack[w] => {
state.low[v] = state.low[v].min(w_index);
}
Some(_) => {}
}
}
if state.low[v] == state.indices[v].expect("v was assigned an index") {
let mut component = Vec::new();
while let Some(w) = state.stack.pop() {
state.on_stack[w] = false;
component.push(w);
if w == v {
break;
}
}
state.components.push(component);
}
}
let n = edges.len();
let mut state = State {
edges,
index: 0,
indices: vec![None; n],
low: vec![0; n],
on_stack: vec![false; n],
stack: Vec::new(),
components: Vec::new(),
};
for v in 0..n {
if state.indices[v].is_none() {
connect(&mut state, v);
}
}
state.components
}
#[derive(Default)]
struct FamilyContext {
facts: BTreeMap<(String, usize), serde_yaml_ng::Value>,
external_owners: BTreeMap<(String, String), ExternalChildOwner>,
families: Vec<FamilyMembership>,
}
struct ExternalChildOwner {
planner_kind: String,
}
struct FamilyMembership {
parent: String,
child: String,
}
fn is_family_producer(registry: &ExtensionRegistry, config: &PlannerConfig) -> bool {
registry
.planner(&config.kind)
.is_some_and(|factory| factory.descriptor().cross_table)
&& config.args.contains_key("children")
}
impl ModelCompiler {
fn collect_family_facts(
&self,
model: &SyntheticModel,
bag: &mut DiagnosticBag,
) -> FamilyContext {
collect_family_facts(&self.registry, model, bag)
}
}
fn collect_family_facts(
registry: &ExtensionRegistry,
model: &SyntheticModel,
bag: &mut DiagnosticBag,
) -> FamilyContext {
let mut ctx = FamilyContext::default();
for (parent_name, table) in &model.tables {
for (index, config) in table.planners.iter().enumerate() {
if !is_family_producer(registry, config) {
continue;
}
let child_name = config.args.get("children").and_then(|v| v.as_str());
let child = child_name.and_then(|name| model.tables.get(name).map(|t| (name, t)));
let mut facts = serde_yaml_ng::Mapping::new();
facts.insert("child_found".into(), (child.is_some()).into());
if let Some((child_name, child_model)) = child {
let mut columns = serde_yaml_ng::Mapping::new();
for column in &child_model.schema.columns {
columns.insert(
column.name.clone().into(),
column.source_type.clone().into(),
);
}
facts.insert(
"child_columns".into(),
serde_yaml_ng::Value::Mapping(columns),
);
if let RowsModel::RelationChildren { distribution, .. } = &child_model.rows {
let (mean, min, max) = distribution_bounds(distribution);
facts.insert("dist_kind".into(), distribution_kind(distribution).into());
facts.insert("dist_mean".into(), mean.into());
facts.insert("dist_min".into(), min.into());
facts.insert("dist_max".into(), max.into());
}
let rel_name = config.args.get("relationship").and_then(|v| v.as_str());
let rel_on_child = rel_name.is_some_and(|name| {
child_relationship_references(child_model, name, parent_name)
});
facts.insert("rel_on_child".into(), rel_on_child.into());
if let Some(serde_yaml_ng::Value::Mapping(mapping)) =
config.args.get("child_columns")
{
for column_name in mapping.values().filter_map(|v| v.as_str()) {
let exists = child_model
.schema
.columns
.iter()
.any(|column| column.name == column_name);
if !exists {
continue;
}
let has_generator = child_model
.columns
.get(column_name)
.is_some_and(|rule| rule.generator.is_some());
if has_generator {
bag.error(
crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
format!("tables.{child_name}.columns.{column_name}"),
format!(
"column `{column_name}` on table `{child_name}` is produced by both its own generator and the `commerce.order_family` planner on table `{parent_name}`"
),
);
}
ctx.external_owners.insert(
(child_name.to_string(), column_name.to_string()),
ExternalChildOwner {
planner_kind: config.kind.clone(),
},
);
}
}
if ctx.families.iter().any(|f| f.child == child_name) {
bag.error(
crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
format!("tables.{child_name}"),
format!(
"child table `{child_name}` is claimed as a family child by more than one parent; a family child must have a single producing parent"
),
);
} else {
ctx.families.push(FamilyMembership {
parent: parent_name.clone(),
child: child_name.to_string(),
});
}
}
ctx.facts.insert(
(parent_name.clone(), index),
serde_yaml_ng::Value::Mapping(facts),
);
}
}
ctx
}
fn yaml_to_i128(value: &serde_yaml_ng::Value) -> Option<i128> {
match value {
serde_yaml_ng::Value::Number(n) => n
.as_i64()
.map(i128::from)
.or_else(|| n.as_f64().map(|f| f as i128)),
serde_yaml_ng::Value::String(s) => s.trim().parse::<i128>().ok(),
_ => None,
}
}
fn dense_key_recipe(table: &TableModel, column: &str) -> Option<(i128, i128)> {
if let Some(rule) = table.columns.get(column) {
if let Some(generator) = &rule.generator {
if generator.kind == "sequence" {
let start = generator
.args
.get("start")
.and_then(yaml_to_i128)
.unwrap_or(0);
let step = generator
.args
.get("step")
.and_then(yaml_to_i128)
.unwrap_or(1);
return Some((start, step));
}
return None;
}
}
let column = table.schema.columns.iter().find(|c| c.name == column)?;
if column.primary_key
&& !column.generated
&& matches!(
column.family,
SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
)
{
return Some((1, 1));
}
None
}
fn build_relation_facts(
model: &SyntheticModel,
table: &TableModel,
resolved: &BTreeMap<String, u64>,
) -> serde_yaml_ng::Value {
use serde_yaml_ng::{Mapping, Value};
let recipe_map = |recipe: Option<(i128, i128)>| -> Mapping {
let mut m = Mapping::new();
match recipe {
Some((start, step)) => {
m.insert("dense".into(), true.into());
m.insert("start".into(), (start as i64).into());
m.insert("step".into(), (step as i64).into());
}
None => {
m.insert("dense".into(), false.into());
}
}
m
};
let mut relationships = Mapping::new();
let generation = table.relationships.iter().map(|rel| {
(
rel.name.clone(),
rel.references.table.clone(),
rel.references.columns.clone(),
)
});
let schema = table.schema.relationships.iter().map(|rel| {
(
rel.name.clone(),
rel.referenced_table.clone(),
rel.referenced_columns.clone(),
)
});
for (name, parent_table, parent_columns) in generation.chain(schema) {
let Some(name) = name else { continue };
let parent_column = parent_columns.first().cloned().unwrap_or_default();
let recipe = model
.tables
.get(&parent_table)
.and_then(|parent| dense_key_recipe(parent, &parent_column));
let mut entry = recipe_map(recipe);
entry.insert("parent_table".into(), parent_table.clone().into());
entry.insert("parent_column".into(), parent_column.into());
entry.insert(
"count".into(),
resolved.get(&parent_table).copied().unwrap_or(0).into(),
);
relationships.insert(name.into(), Value::Mapping(entry));
}
let mut tables = Mapping::new();
for (name, target) in &model.tables {
let count = resolved.get(name).copied().unwrap_or(0);
let mut keys = Mapping::new();
for column in &target.schema.columns {
if let Some(recipe) = dense_key_recipe(target, &column.name) {
let mut key_entry = recipe_map(Some(recipe));
key_entry.insert("count".into(), count.into());
keys.insert(column.name.clone().into(), Value::Mapping(key_entry));
}
}
let mut entry = Mapping::new();
entry.insert("count".into(), count.into());
entry.insert("keys".into(), Value::Mapping(keys));
let primary_key = target.schema.primary_key.first().cloned().or_else(|| {
target
.schema
.columns
.iter()
.find(|column| column.primary_key)
.map(|column| column.name.clone())
});
if let Some(primary_key) = primary_key {
entry.insert("primary_key".into(), primary_key.into());
}
tables.insert(name.clone().into(), Value::Mapping(entry));
}
let mut root = Mapping::new();
root.insert("relationships".into(), Value::Mapping(relationships));
root.insert("tables".into(), Value::Mapping(tables));
root.insert(
"self_count".into(),
resolved
.get(&table.schema.name)
.copied()
.unwrap_or(0)
.into(),
);
Value::Mapping(root)
}
fn child_relationship_references(child: &TableModel, name: &str, parent: &str) -> bool {
let generation = child.relationships.iter().any(|relationship| {
relationship.name.as_deref() == Some(name) && relationship.references.table == parent
});
let schema = child.schema.relationships.iter().any(|relationship| {
relationship.name.as_deref() == Some(name) && relationship.referenced_table == parent
});
generation || schema
}
fn build_phases(
order: &[String],
family_ctx: &FamilyContext,
budget_bytes: u64,
bag: &mut DiagnosticBag,
) -> Vec<ExecutionPhase> {
let ordered: BTreeSet<&str> = order.iter().map(String::as_str).collect();
let child_tables: BTreeSet<&str> = family_ctx
.families
.iter()
.map(|family| family.child.as_str())
.collect();
let mut phases = Vec::with_capacity(order.len());
for name in order {
if child_tables.contains(name.as_str()) {
continue;
}
match family_ctx
.families
.iter()
.find(|family| &family.parent == name)
{
Some(family) if ordered.contains(family.child.as_str()) => {
phases.push(ExecutionPhase::Family(FamilyPhase {
name: name.clone(),
tables: vec![name.clone(), family.child.clone()],
budget_bytes,
}));
}
Some(family) => {
bag.warning(
crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
format!("tables.{name}.planners"),
format!(
"family child `{}` of `{name}` was excluded; generating `{name}` without its correlated child rows",
family.child
),
);
phases.push(ExecutionPhase::Table(name.clone()));
}
None => phases.push(ExecutionPhase::Table(name.clone())),
}
}
phases
}
fn compile_relationship(relationship: &RelationshipModel) -> CompiledRelationship {
CompiledRelationship {
name: relationship.name.clone(),
columns: relationship.columns.clone(),
parent_table: relationship.references.table.clone(),
parent_columns: relationship.references.columns.clone(),
distribution: parse_distribution(relationship.distribution.as_deref()),
null_permille: 0,
}
}
fn parse_distribution(name: Option<&str>) -> RelationshipDistribution {
match name {
Some("sequential") => RelationshipDistribution::Sequential,
Some("weighted") => RelationshipDistribution::Weighted,
Some("observed") => RelationshipDistribution::Observed,
_ => RelationshipDistribution::Uniform,
}
}
fn fold_foreign_key_generators(
table_name: &str,
table: &TableModel,
relationships: &mut [CompiledRelationship],
bag: &mut DiagnosticBag,
) {
for (column, rule) in &table.columns {
let Some(generator) = &rule.generator else {
continue;
};
if generator.kind != "relation.foreign_key" && generator.kind != "relation.composite_key" {
continue;
}
let Some(relationship) = relationships
.iter_mut()
.find(|relationship| relationship.columns.iter().any(|c| c == column))
else {
bag.error(
crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
format!("tables.{table_name}.columns.{column}.generator"),
format!(
"column `{column}` on table `{table_name}` uses generator `{}` but no relationship declares it as a foreign key; declare a `relationships:` entry covering it",
generator.kind
),
);
continue;
};
if let Some(name) = generator.args.get("distribution").and_then(|v| v.as_str()) {
relationship.distribution = parse_distribution(Some(name));
}
if let Some(rate) = generator.args.get("null_rate").and_then(|v| v.as_f64()) {
relationship.null_permille = (rate.clamp(0.0, 1.0) * 1000.0).round() as u16;
}
}
}
fn resolve_seed(seed: &TableSeed, root_seed: u64) -> ResolvedTableSeed {
match seed {
TableSeed::Inherit => ResolvedTableSeed::Inherited(SeedRoot::new(root_seed)),
TableSeed::Random => ResolvedTableSeed::Random(SeedRoot::new(rand::random())),
TableSeed::Fixed(seed) => ResolvedTableSeed::Fixed(SeedRoot::new(*seed)),
}
}
fn compile_output(model: &SyntheticModel) -> CompiledOutput {
CompiledOutput {
dialect: model.output.dialect.as_ref().and_then(|d| d.parse().ok()),
mode: model.output.mode,
inserts: model.output.inserts,
batch_size: model.output.batch_size,
}
}
fn compile_globs(patterns: &[String], bag: &mut DiagnosticBag) -> Vec<Pattern> {
patterns
.iter()
.filter_map(|pattern| match Pattern::new(pattern) {
Ok(compiled) => Some(compiled),
Err(error) => {
bag.error(
crate::diagnostic::codes::INVALID_GLOB.code,
"options",
format!("invalid table glob `{pattern}`: {error}"),
);
None
}
})
.collect()
}