use std::collections::{BTreeMap, HashMap};
use crate::classify::semantic::{CorrelationGroup, SemanticType};
use crate::config::ColumnConfig;
use crate::generate::numeric::NumericFallback;
use crate::generate::value::Value;
use crate::graph::topo::DeferredEdge;
use crate::sample::stats::{ColumnDistribution, DistributionProfile};
use crate::schema::types::{Column, DataType, DatabaseSchema, DatabaseType, ParsedCheck};
#[derive(Debug, Clone)]
pub struct GenerationPlan {
pub scenario: BTreeMap<String, super::scenario::TableRules>,
pub table_plans: Vec<TableGenerationPlan>,
pub deferred_edges: Vec<DeferredEdge>,
pub seed: u64,
pub generator_version: crate::generate::random::GeneratorVersion,
pub default_row_count: usize,
pub base_time: chrono::NaiveDateTime,
pub sequence_offset: u64,
pub locale: crate::generate::locale::Locale,
}
#[derive(Debug, Clone)]
pub struct TableGenerationPlan {
pub records: Vec<BTreeMap<String, crate::generate::value::Value>>,
pub table_name: String,
pub row_count: usize,
pub column_plans: Vec<ColumnGenerationPlan>,
pub correlation_groups: Vec<CorrelationGroupPlan>,
}
#[derive(Debug, Clone)]
pub struct ColumnGenerationPlan {
pub column_name: String,
pub semantic_type: SemanticType,
pub strategy: GenerationStrategy,
pub nullable: bool,
pub null_probability: f64,
pub allowed_values: Option<Vec<Value>>,
pub check_constraints: Vec<ParsedCheck>,
}
#[derive(Debug, Clone)]
pub enum GenerationStrategy {
AutoIncrement,
ExternalReference { target: String },
ForeignKeyReference {
referenced_table: String,
referenced_column: String,
},
CompositeReference,
SharedPrimaryKey {
referenced_table: String,
referenced_column: String,
},
SemanticProvider,
NumericFallback(NumericFallback),
Typed(crate::generate::typed::TypedFallback),
EnumValue { values: Vec<String> },
Correlated { group_index: usize },
Deferred,
Skip,
Pattern(crate::generate::pattern::Pattern),
Range {
min: f64,
max: f64,
decimals: Option<u32>,
},
ValueList {
values: Vec<crate::config::FixtureValue>,
weights: Option<Vec<f64>>,
},
ReferenceKeys(Vec<crate::generate::value::Value>),
Distribution { distribution: ColumnDistribution },
}
#[derive(Debug, Clone)]
pub struct CorrelationGroupPlan {
pub group: CorrelationGroup,
pub columns: Vec<(String, SemanticType)>,
}
impl GenerationPlan {
#[allow(clippy::too_many_arguments)]
pub fn build(
schema: &DatabaseSchema,
classifications: &BTreeMap<(String, String), SemanticType>,
insertion_order: &[String],
deferred_edges: Vec<DeferredEdge>,
default_row_count: usize,
table_row_overrides: &BTreeMap<String, usize>,
seed: u64,
base_time: Option<chrono::NaiveDateTime>,
column_overrides: &BTreeMap<String, ColumnConfig>,
distribution_profiles: Option<&[DistributionProfile]>,
) -> Self {
let deferred_columns: HashMap<(&str, &str), bool> = deferred_edges
.iter()
.flat_map(|e| {
e.source_columns
.iter()
.map(move |col| (e.source_table.as_str(), col.as_str()))
})
.map(|k| (k, true))
.collect();
let dist_lookup: HashMap<(&str, &str), &ColumnDistribution> = distribution_profiles
.unwrap_or(&[])
.iter()
.flat_map(|p| {
p.column_distributions
.iter()
.filter(|(_, d)| !matches!(d, ColumnDistribution::Ratio { .. }))
.map(move |(col, dist)| ((p.table_name.as_str(), col.as_str()), dist))
})
.collect();
let ratio_lookup: HashMap<(&str, &str), f64> = distribution_profiles
.unwrap_or(&[])
.iter()
.flat_map(|p| {
p.column_distributions.values().filter_map(move |dist| {
if let ColumnDistribution::Ratio {
related_table,
ratio,
} = dist
{
Some(((p.table_name.as_str(), related_table.as_str()), *ratio))
} else {
None
}
})
})
.collect();
let mut table_plans = Vec::new();
for table_name in insertion_order {
let table = match schema.tables.get(table_name) {
Some(t) => t,
None => continue,
};
let row_count = if let Some(&explicit) = table_row_overrides.get(table_name) {
explicit
} else {
let ratio_adjusted = table.local_foreign_keys().find_map(|fk| {
ratio_lookup
.get(&(table_name.as_str(), fk.referenced_table.as_str()))
.map(|ratio| {
let parent_count = table_row_overrides
.get(&fk.referenced_table)
.copied()
.unwrap_or(default_row_count);
(parent_count as f64 * ratio).round() as usize
})
});
ratio_adjusted.unwrap_or(default_row_count)
};
let mut correlation_groups = Vec::new();
let mut correlated_columns: HashMap<String, usize> = HashMap::new();
let mut group_map: BTreeMap<CorrelationGroup, Vec<(String, SemanticType)>> =
BTreeMap::new();
let writable_columns = || table.columns.iter().filter(|(_, c)| !c.is_generated);
let semantic_of = |col_name: &String| {
column_overrides
.get(&format!("{table_name}.{col_name}"))
.and_then(|cfg| cfg.semantic)
.or_else(|| {
classifications
.get(&(table_name.clone(), col_name.clone()))
.copied()
})
};
for (col_name, _) in writable_columns() {
if let Some(st) = semantic_of(col_name).as_ref() {
if let Some(group) = st.correlation_group() {
group_map
.entry(group)
.or_default()
.push((col_name.clone(), *st));
}
}
}
for (group, columns) in group_map {
if columns.len() >= 2 {
let group_index = correlation_groups.len();
for (col_name, _) in &columns {
correlated_columns.insert(col_name.clone(), group_index);
}
correlation_groups.push(CorrelationGroupPlan { group, columns });
}
}
let mut column_plans = Vec::new();
let pk_columns: Vec<&str> = table
.primary_key
.as_ref()
.map(|pk| pk.columns.iter().map(|s| s.as_str()).collect())
.unwrap_or_default();
for (col_name, column) in writable_columns() {
let semantic_type = semantic_of(col_name).unwrap_or(SemanticType::Unknown);
let col_key = format!("{}.{}", table_name, col_name);
let column_config = column_overrides.get(&col_key);
let config_strategy = column_config.and_then(|cfg| {
if let Some(values) = &cfg.values {
return Some(GenerationStrategy::ValueList {
values: values.clone(),
weights: cfg.weights.clone(),
});
}
if let Some(pattern) = &cfg.pattern {
return crate::generate::pattern::Pattern::parse(pattern)
.ok()
.map(GenerationStrategy::Pattern);
}
cfg.range.map(|[min, max]| GenerationStrategy::Range {
min,
max,
decimals: (!column.data_type.is_integer())
.then(|| column.numeric_scale.unwrap_or(2).min(6)),
})
});
let external_key = table.foreign_keys.iter().find(|fk| {
fk.referenced_schema.is_some() && fk.source_columns.contains(col_name)
});
let foreign_key = table.local_foreign_keys().find(|fk| {
fk.source_columns.len() == 1
&& fk.referenced_columns.len() == 1
&& fk.source_columns[0] == *col_name
});
let shared_key = foreign_key.filter(|fk| {
(pk_columns.as_slice() == [col_name.as_str()]
|| table
.unique_constraints
.iter()
.any(|u| u.columns.as_slice() == [col_name.as_str()]))
&& fk.referenced_table != *table_name
&& insertion_order.contains(&fk.referenced_table)
});
let strategy = if let Some(fk) = external_key {
GenerationStrategy::ExternalReference {
target: fk.target_name(),
}
} else if let Some(s) = config_strategy {
s
} else if deferred_columns.contains_key(&(table_name.as_str(), col_name.as_str())) {
GenerationStrategy::Deferred
} else if table.local_foreign_keys().any(|fk| {
fk.source_columns.len() > 1
&& fk.source_columns.contains(col_name)
&& insertion_order.contains(&fk.referenced_table)
}) {
GenerationStrategy::CompositeReference
} else if let Some(fk) = shared_key {
GenerationStrategy::SharedPrimaryKey {
referenced_table: fk.referenced_table.clone(),
referenced_column: fk.referenced_columns[0].clone(),
}
} else if column.is_auto_increment || column.data_type.is_serial() {
if pk_columns.contains(&col_name.as_str()) {
GenerationStrategy::AutoIncrement
} else {
GenerationStrategy::SemanticProvider
}
} else if let Some(fk) = foreign_key {
if insertion_order.contains(&fk.referenced_table) {
GenerationStrategy::ForeignKeyReference {
referenced_table: fk.referenced_table.clone(),
referenced_column: fk.referenced_columns[0].clone(),
}
} else {
GenerationStrategy::SemanticProvider
}
} else if let Some(dist) =
dist_lookup.get(&(table_name.as_str(), col_name.as_str()))
{
GenerationStrategy::Distribution {
distribution: (*dist).clone(),
}
} else if let Some(ref values) = column.enum_values {
GenerationStrategy::EnumValue {
values: values.clone(),
}
} else if let Some(&group_index) = correlated_columns.get(col_name) {
GenerationStrategy::Correlated { group_index }
} else {
GenerationStrategy::SemanticProvider
};
let strategy = if semantic_type == SemanticType::Unknown
&& matches!(strategy, GenerationStrategy::SemanticProvider)
{
NumericFallback::for_column(column)
.map(GenerationStrategy::NumericFallback)
.unwrap_or(strategy)
} else {
strategy
};
let strategy = match strategy {
generated @ (GenerationStrategy::SemanticProvider
| GenerationStrategy::Correlated { .. }
| GenerationStrategy::NumericFallback(_)) => {
crate::generate::typed::TypedFallback::for_column(column, &schema.enums)
.map_or(generated, GenerationStrategy::Typed)
}
other => other,
};
let check_constraints: Vec<ParsedCheck> = table
.check_constraints
.iter()
.filter_map(|cc| {
cc.parsed.as_ref().and_then(|p| {
if check_applies_to_column(p, col_name, schema.database_type) {
Some(p.clone())
} else {
None
}
})
})
.collect();
let allowed_values = allowed_values(column, &check_constraints);
let strategy = if allowed_values.is_some()
&& matches!(
strategy,
GenerationStrategy::Correlated { .. }
| GenerationStrategy::EnumValue { .. }
) {
GenerationStrategy::SemanticProvider
} else {
strategy
};
let null_probability =
if column.nullable && !pk_columns.contains(&col_name.as_str()) {
column_config
.and_then(|cfg| cfg.null_rate)
.unwrap_or(match semantic_type {
SemanticType::DeletedAt => 0.8, _ => 0.05, })
} else {
0.0
};
column_plans.push(ColumnGenerationPlan {
column_name: col_name.clone(),
semantic_type,
strategy,
nullable: column.nullable,
null_probability,
check_constraints,
allowed_values,
});
}
table_plans.push(TableGenerationPlan {
records: Vec::new(),
table_name: table_name.clone(),
row_count,
column_plans,
correlation_groups,
});
}
GenerationPlan {
scenario: BTreeMap::new(),
table_plans,
deferred_edges,
seed,
default_row_count,
base_time: base_time.unwrap_or_else(|| chrono::Utc::now().naive_utc()),
generator_version: Default::default(),
sequence_offset: 0,
locale: Default::default(),
}
}
}
pub fn filter_insertion_order(
insertion_order: &[String],
schema: &DatabaseSchema,
include: &[String],
exclude: &[String],
) -> Vec<String> {
if include.is_empty() && exclude.is_empty() {
return insertion_order.to_vec();
}
let mut wanted: std::collections::HashSet<String> = if include.is_empty() {
insertion_order.iter().cloned().collect()
} else {
let mut set: std::collections::HashSet<String> = include.iter().cloned().collect();
let mut queue: Vec<String> = include.to_vec();
while let Some(table_name) = queue.pop() {
if let Some(table) = schema.tables.get(&table_name) {
for fk in table.local_foreign_keys() {
if set.insert(fk.referenced_table.clone()) {
queue.push(fk.referenced_table.clone());
}
}
}
}
set
};
for table_name in exclude {
wanted.remove(table_name);
}
insertion_order
.iter()
.filter(|t| wanted.contains(t.as_str()))
.cloned()
.collect()
}
fn allowed_values(column: &Column, checks: &[ParsedCheck]) -> Option<Vec<Value>> {
fn literal(data_type: &DataType, s: &str) -> Option<Value> {
match data_type {
DataType::SmallInt
| DataType::Integer
| DataType::BigInt
| DataType::Serial
| DataType::BigSerial => {
let integer = s
.split_once('.')
.filter(|(_, fraction)| fraction.bytes().all(|b| b == b'0'))
.map_or(s, |(whole, _)| whole);
integer.parse().ok().map(Value::Int)
}
DataType::Numeric | DataType::Float | DataType::Double => {
s.parse().ok().map(Value::Float)
}
DataType::Boolean => match s.to_ascii_lowercase().as_str() {
"true" | "1" => Some(Value::Bool(true)),
"false" | "0" => Some(Value::Bool(false)),
_ => None,
},
_ => Some(Value::String(s.to_owned().into())),
}
}
let mut lists = checks.iter().filter_map(|check| match check {
ParsedCheck::InValues { values, .. } => Some(
values
.iter()
.filter(|v| {
column
.enum_values
.as_ref()
.is_none_or(|labels| labels.contains(v))
})
.filter_map(|s| literal(&column.data_type, s))
.collect::<Vec<_>>(),
),
_ => None,
});
let mut allowed = lists.next()?;
for list in lists {
allowed.retain(|v| list.contains(v));
}
Some(allowed)
}
fn check_applies_to_column(check: &ParsedCheck, column_name: &str, db: DatabaseType) -> bool {
match check {
ParsedCheck::GreaterThanOrEqual { column, .. }
| ParsedCheck::GreaterThan { column, .. }
| ParsedCheck::LessThanOrEqual { column, .. }
| ParsedCheck::LessThan { column, .. }
| ParsedCheck::MinLength { column, .. } => column == column_name,
ParsedCheck::InValues { column, .. } if db != DatabaseType::PostgreSQL => {
column.eq_ignore_ascii_case(column_name)
}
ParsedCheck::InValues { column, .. } => column == column_name,
ParsedCheck::Between { column, .. } => column == column_name,
ParsedCheck::ColumnLessThan { left, right } => left == column_name || right == column_name,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::types::*;
fn build_chain_schema() -> DatabaseSchema {
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let users = Table::new("users".to_string());
schema.tables.insert("users".to_string(), users);
let mut orders = Table::new("orders".to_string());
orders.foreign_keys.push(ForeignKey {
name: None,
source_columns: vec!["user_id".to_string()],
referenced_schema: None,
referenced_table: "users".to_string(),
referenced_columns: vec!["id".to_string()],
on_delete: ForeignKeyAction::NoAction,
on_update: ForeignKeyAction::NoAction,
is_deferrable: false,
});
schema.tables.insert("orders".to_string(), orders);
let mut order_items = Table::new("order_items".to_string());
order_items.foreign_keys.push(ForeignKey {
name: None,
source_columns: vec!["order_id".to_string()],
referenced_schema: None,
referenced_table: "orders".to_string(),
referenced_columns: vec!["id".to_string()],
on_delete: ForeignKeyAction::NoAction,
on_update: ForeignKeyAction::NoAction,
is_deferrable: false,
});
schema.tables.insert("order_items".to_string(), order_items);
let products = Table::new("products".to_string());
schema.tables.insert("products".to_string(), products);
schema
}
#[test]
fn test_filter_no_include_no_exclude_returns_all() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(&order, &schema, &[], &[]);
assert_eq!(result, order);
}
#[test]
fn test_filter_include_single_table_no_fk_deps() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(&order, &schema, &["products".into()], &[]);
assert_eq!(result, vec!["products"]);
}
#[test]
fn test_filter_include_auto_adds_fk_dependencies() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(&order, &schema, &["orders".into()], &[]);
assert_eq!(result, vec!["users", "orders"]);
}
#[test]
fn test_filter_include_transitive_fk_dependencies() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(&order, &schema, &["order_items".into()], &[]);
assert_eq!(result, vec!["users", "orders", "order_items"]);
}
#[test]
fn test_filter_exclude_removes_table() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(&order, &schema, &[], &["products".into()]);
assert_eq!(result, vec!["users", "orders", "order_items"]);
}
#[test]
fn test_filter_include_and_exclude_combined() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(&order, &schema, &["orders".into()], &["users".into()]);
assert_eq!(result, vec!["orders"]);
}
#[test]
fn test_filter_preserves_topological_order() {
let schema = build_chain_schema();
let order = vec![
"users".into(),
"products".into(),
"orders".into(),
"order_items".into(),
];
let result = filter_insertion_order(
&order,
&schema,
&["order_items".into(), "products".into()],
&[],
);
assert_eq!(result, vec!["users", "products", "orders", "order_items"]);
}
#[test]
fn test_filter_include_nonexistent_table_ignored() {
let schema = build_chain_schema();
let order = vec!["users".into(), "products".into()];
let result = filter_insertion_order(
&order,
&schema,
&["users".into(), "nonexistent".into()],
&[],
);
assert_eq!(result, vec!["users"]);
}
#[test]
fn test_unclassified_integer_fk_to_excluded_parent_uses_numeric_fallback() {
let mut schema = build_chain_schema();
let user_id_col = Column::new(
"user_id".to_string(),
DataType::Integer,
"integer".to_string(),
);
schema
.tables
.get_mut("orders")
.unwrap()
.columns
.insert("user_id".to_string(), user_id_col);
let classifications = BTreeMap::new();
let insertion_order = vec!["orders".to_string()];
let plan = GenerationPlan::build(
&schema,
&classifications,
&insertion_order,
Vec::new(),
10,
&BTreeMap::new(),
42,
None,
&BTreeMap::new(),
None,
);
let orders_plan = plan
.table_plans
.iter()
.find(|t| t.table_name == "orders")
.unwrap();
let user_id_plan = orders_plan
.column_plans
.iter()
.find(|c| c.column_name == "user_id")
.unwrap();
assert!(matches!(
user_id_plan.strategy,
GenerationStrategy::NumericFallback(NumericFallback::Integer { .. })
));
}
#[test]
fn test_fk_to_included_parent_uses_fk_reference() {
let mut schema = build_chain_schema();
let user_id_col = Column::new(
"user_id".to_string(),
DataType::Integer,
"integer".to_string(),
);
schema
.tables
.get_mut("orders")
.unwrap()
.columns
.insert("user_id".to_string(), user_id_col);
let classifications = BTreeMap::new();
let insertion_order = vec!["users".to_string(), "orders".to_string()];
let plan = GenerationPlan::build(
&schema,
&classifications,
&insertion_order,
Vec::new(),
10,
&BTreeMap::new(),
42,
None,
&BTreeMap::new(),
None,
);
let orders_plan = plan
.table_plans
.iter()
.find(|t| t.table_name == "orders")
.unwrap();
let user_id_plan = orders_plan
.column_plans
.iter()
.find(|c| c.column_name == "user_id")
.unwrap();
assert!(
matches!(
user_id_plan.strategy,
GenerationStrategy::ForeignKeyReference { .. }
),
"Expected ForeignKeyReference for FK to included parent, got {:?}",
user_id_plan.strategy
);
}
#[test]
fn test_value_list_override_takes_priority_over_semantic() {
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut table = Table::new("products".to_string());
let col = Column::new(
"color".to_string(),
DataType::VarChar,
"varchar".to_string(),
);
table.columns.insert("color".to_string(), col);
schema.tables.insert("products".to_string(), table);
let classifications = BTreeMap::new();
let insertion_order = vec!["products".to_string()];
let mut overrides = BTreeMap::new();
overrides.insert(
"products.color".to_string(),
crate::config::ColumnConfig {
values: Some(vec!["red".into(), "blue".into()]),
weights: Some(vec![0.7, 0.3]),
..Default::default()
},
);
let plan = GenerationPlan::build(
&schema,
&classifications,
&insertion_order,
Vec::new(),
10,
&BTreeMap::new(),
42,
None,
&overrides,
None,
);
let col_plan = plan.table_plans[0]
.column_plans
.iter()
.find(|c| c.column_name == "color")
.unwrap();
assert!(
matches!(col_plan.strategy, GenerationStrategy::ValueList { .. }),
"Expected ValueList from config override, got {:?}",
col_plan.strategy
);
}
#[test]
fn pattern_and_range_overrides_choose_their_strategies() {
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut table = Table::new("orders".to_string());
for (name, data_type) in [("tax_code", DataType::VarChar), ("qty", DataType::Integer)] {
let col = Column::new(name.to_string(), data_type.clone(), data_type.to_string());
table.columns.insert(name.to_string(), col);
}
schema.tables.insert("orders".to_string(), table);
let overrides = BTreeMap::from([
(
"orders.tax_code".to_string(),
crate::config::ColumnConfig {
pattern: Some("TX-####".into()),
..Default::default()
},
),
(
"orders.qty".to_string(),
crate::config::ColumnConfig {
range: Some([1.0, 9.0]),
..Default::default()
},
),
]);
let plan = GenerationPlan::build(
&schema,
&BTreeMap::new(),
&["orders".to_string()],
Vec::new(),
10,
&BTreeMap::new(),
42,
None,
&overrides,
None,
);
let strategy = |name: &str| {
&plan.table_plans[0]
.column_plans
.iter()
.find(|c| c.column_name == name)
.unwrap()
.strategy
};
assert!(matches!(
strategy("tax_code"),
GenerationStrategy::Pattern(_)
));
assert!(matches!(
strategy("qty"),
GenerationStrategy::Range { decimals: None, .. }
));
}
#[test]
fn test_override_for_nonexistent_column_is_harmless() {
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut table = Table::new("users".to_string());
let col = Column::new("name".to_string(), DataType::VarChar, "varchar".to_string());
table.columns.insert("name".to_string(), col);
schema.tables.insert("users".to_string(), table);
let mut overrides = BTreeMap::new();
overrides.insert(
"users.nonexistent".to_string(),
crate::config::ColumnConfig {
values: Some(vec!["x".into()]),
weights: None,
..Default::default()
},
);
let plan = GenerationPlan::build(
&schema,
&BTreeMap::new(),
&["users".to_string()],
Vec::new(),
10,
&BTreeMap::new(),
42,
None,
&overrides,
None,
);
let col_plan = plan.table_plans[0]
.column_plans
.iter()
.find(|c| c.column_name == "name")
.unwrap();
assert!(
matches!(col_plan.strategy, GenerationStrategy::SemanticProvider),
"Nonexistent override should not affect other columns, got {:?}",
col_plan.strategy
);
}
#[test]
fn test_ratio_adjusts_row_counts() {
use crate::sample::stats::{ColumnDistribution, DistributionProfile};
let schema = build_chain_schema();
let classifications = BTreeMap::new();
let insertion_order = vec![
"users".to_string(),
"products".to_string(),
"orders".to_string(),
"order_items".to_string(),
];
let profiles = vec![
DistributionProfile {
table_name: "users".to_string(),
row_count: 1000,
column_distributions: std::collections::HashMap::new(),
},
DistributionProfile {
table_name: "orders".to_string(),
row_count: 3200,
column_distributions: {
let mut m = std::collections::HashMap::new();
m.insert(
"__ratio_user_id".to_string(),
ColumnDistribution::Ratio {
related_table: "users".to_string(),
ratio: 3.2,
},
);
m
},
},
];
let plan = GenerationPlan::build(
&schema,
&classifications,
&insertion_order,
Vec::new(),
100, &BTreeMap::new(),
42,
None,
&BTreeMap::new(),
Some(&profiles),
);
let users_plan = plan
.table_plans
.iter()
.find(|t| t.table_name == "users")
.unwrap();
assert_eq!(users_plan.row_count, 100);
let orders_plan = plan
.table_plans
.iter()
.find(|t| t.table_name == "orders")
.unwrap();
assert_eq!(
orders_plan.row_count, 320,
"orders should be ratio-adjusted to 320 (100 * 3.2)"
);
}
#[test]
fn test_distribution_profile_overrides_semantic_provider() {
use crate::sample::stats::{ColumnDistribution, DistributionProfile};
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut table = Table::new("products".to_string());
let col = Column::new(
"status".to_string(),
DataType::VarChar,
"varchar".to_string(),
);
table.columns.insert("status".to_string(), col);
schema.tables.insert("products".to_string(), table);
let profiles = vec![DistributionProfile {
table_name: "products".to_string(),
row_count: 500,
column_distributions: {
let mut m = std::collections::HashMap::new();
m.insert(
"status".to_string(),
ColumnDistribution::Categorical {
values: vec![("active".to_string(), 0.9), ("draft".to_string(), 0.1)],
},
);
m
},
}];
let plan = GenerationPlan::build(
&schema,
&BTreeMap::new(),
&["products".to_string()],
Vec::new(),
10,
&BTreeMap::new(),
42,
None,
&BTreeMap::new(),
Some(&profiles),
);
let col_plan = plan.table_plans[0]
.column_plans
.iter()
.find(|c| c.column_name == "status")
.unwrap();
assert!(
matches!(col_plan.strategy, GenerationStrategy::Distribution { .. }),
"Expected Distribution strategy from profile, got {:?}",
col_plan.strategy
);
}
}