use crate::generate::random::RandomStreams;
use indexmap::IndexMap;
use rand::rngs::StdRng;
use rand::Rng;
use std::borrow::Cow;
use tracing::debug;
use crate::config::FixtureValue;
use crate::error::{Result, SeedKitError};
use crate::generate::foreign_key::ForeignKeyPool;
use crate::generate::locale::Locale;
use crate::generate::plan::*;
use crate::generate::providers::generate_localized;
use crate::generate::unique::UniqueTracker;
use crate::generate::value::Value;
use crate::sample::stats::ColumnDistribution;
use crate::schema::types::DatabaseSchema;
#[derive(Debug)]
pub struct GeneratedData {
pub tables: IndexMap<String, Vec<IndexMap<String, Value>>>,
pub deferred_updates: Vec<DeferredUpdate>,
}
#[derive(Debug)]
pub struct DeferredUpdate {
pub table_name: String,
pub row_index: usize,
pub column_name: String,
pub value: Value,
}
const PROGRESS_BATCH_SIZE: usize = 100;
#[allow(clippy::type_complexity)]
pub fn execute_plan(
plan: &GenerationPlan,
schema: &DatabaseSchema,
progress_callback: Option<&dyn Fn(&str, usize, usize)>,
) -> Result<GeneratedData> {
let mut streams = RandomStreams::new(plan.seed, plan.generator_version);
let mut fk_pool = ForeignKeyPool::new();
let mut unique_tracker = UniqueTracker::new();
let mut generated = GeneratedData {
tables: IndexMap::new(),
deferred_updates: Vec::new(),
};
for table_plan in &plan.table_plans {
if let Some(table) = schema.tables.get(&table_plan.table_name) {
for uc in &table.unique_constraints {
unique_tracker.register_constraint(&table_plan.table_name, &uc.columns);
}
if let Some(pk) = &table.primary_key {
unique_tracker.register_constraint(&table_plan.table_name, &pk.columns);
}
}
}
let total_rows: usize = plan.table_plans.iter().map(|t| t.row_count).sum();
let mut rows_generated = 0usize;
for table_plan in &plan.table_plans {
let bound;
let table_plan = if let Some(rules) = plan.scenario.get(&table_plan.table_name) {
bound = rules
.bind(
table_plan,
&generated,
schema,
plan.seed,
plan.sequence_offset,
)
.map_err(|err| SeedKitError::Config {
message: err.to_string(),
})?;
&bound
} else {
table_plan
};
let mut table_rows = Vec::with_capacity(table_plan.row_count);
for row_idx in 0..table_plan.row_count {
let row = generate_row(
table_plan,
row_idx,
&mut streams,
&fk_pool,
&mut unique_tracker,
schema,
RowSettings {
base_time: plan.base_time,
locale: plan.locale,
},
)?;
table_rows.push(row);
rows_generated += 1;
if let Some(cb) = progress_callback {
if rows_generated.is_multiple_of(PROGRESS_BATCH_SIZE)
|| rows_generated == total_rows
{
cb(&table_plan.table_name, rows_generated, total_rows);
}
}
}
if let Some(table) = schema.tables.get(&table_plan.table_name) {
fk_pool.record_table(table, &table_rows, schema, plan.sequence_offset);
}
generated
.tables
.insert(table_plan.table_name.clone(), table_rows);
}
for deferred in &plan.deferred_edges {
if let Some(rows) = generated.tables.get(&deferred.source_table) {
let edge = deferred.source_columns.join("\0");
for (row_idx, _row) in rows.iter().enumerate() {
let rng = streams.stream(&deferred.source_table, row_idx, 0, "deferred", &edge);
let values = if let [col] = deferred.target_columns.as_slice() {
fk_pool
.pick_reference(&deferred.target_table, col, rng)
.map(|v| vec![v])
} else {
use rand::prelude::IndexedRandom;
fk_pool
.tuples(&deferred.target_table, &deferred.target_columns)
.choose(rng)
.cloned()
};
if let Some(values) = values {
for (col, value) in deferred.source_columns.iter().zip(values) {
if schema.tables[&deferred.source_table].columns[col].is_generated {
continue;
}
generated.deferred_updates.push(DeferredUpdate {
table_name: deferred.source_table.clone(),
row_index: row_idx,
column_name: col.clone(),
value,
});
}
}
}
}
}
Ok(generated)
}
#[derive(Clone, Copy)]
struct RowSettings {
base_time: chrono::NaiveDateTime,
locale: Locale,
}
const MAX_ROW_RETRIES: usize = 50;
fn generate_row(
table_plan: &TableGenerationPlan,
row_index: usize,
streams: &mut RandomStreams,
fk_pool: &ForeignKeyPool,
unique_tracker: &mut UniqueTracker,
schema: &DatabaseSchema,
settings: RowSettings,
) -> Result<IndexMap<String, Value>> {
let mut composite_constraints = Vec::new();
if let Some(table) = schema.tables.get(&table_plan.table_name) {
for columns in table
.unique_constraints
.iter()
.map(|u| &u.columns)
.chain(table.primary_key.iter().map(|pk| &pk.columns))
{
let grouped = columns.len() > 1
|| table_plan.column_plans.iter().any(|c| {
matches!(c.strategy, GenerationStrategy::CompositeReference)
&& columns.contains(&c.column_name)
});
if grouped && !composite_constraints.contains(&columns) {
composite_constraints.push(columns);
}
}
}
let mut attempts = 0;
loop {
let row = generate_row_candidate(
table_plan,
(row_index, attempts),
streams,
fk_pool,
unique_tracker,
schema,
settings,
)?;
let mut collision = false;
for columns in &composite_constraints {
let values: Vec<&Value> = columns.iter().filter_map(|col| row.get(col)).collect();
if values.len() == columns.len()
&& values.iter().all(|v| !v.is_null())
&& unique_tracker.contains(&table_plan.table_name, columns, &values)
{
collision = true;
break;
}
}
if !collision {
if let Some(table) = schema.tables.get(&table_plan.table_name) {
for columns in table
.unique_constraints
.iter()
.map(|u| &u.columns)
.chain(table.primary_key.iter().map(|p| &p.columns))
{
let values: Option<Vec<_>> = columns
.iter()
.map(|c| row.get(c).filter(|v| !v.is_null()))
.collect();
if let Some(values) = values {
unique_tracker.try_insert(&table.name, columns, &values);
}
}
}
return Ok(row);
}
attempts += 1;
if attempts >= MAX_ROW_RETRIES {
let failed_cols = composite_constraints
.iter()
.map(|cols| cols.join(", "))
.collect::<Vec<_>>()
.join("; ");
return Err(SeedKitError::CompositeUniqueExhausted {
table: table_plan.table_name.clone(),
columns: failed_cols,
row_index,
max_retries: MAX_ROW_RETRIES,
});
}
debug!(
"Composite unique collision on {} at row {}, retrying (attempt {}/{})",
table_plan.table_name, row_index, attempts, MAX_ROW_RETRIES
);
}
}
fn generate_row_candidate(
table_plan: &TableGenerationPlan,
(row_index, attempt): (usize, usize),
streams: &mut RandomStreams,
fk_pool: &ForeignKeyPool,
unique_tracker: &mut UniqueTracker,
schema: &DatabaseSchema,
settings: RowSettings,
) -> Result<IndexMap<String, Value>> {
let RowSettings { base_time, locale } = settings;
let mut row = IndexMap::new();
let mut correlated_values: IndexMap<String, Value> = IndexMap::new();
for group_plan in &table_plan.correlation_groups {
let rng = streams.stream(
&table_plan.table_name,
row_index,
attempt,
"group",
&group_plan.group.to_string(),
);
let group_values = crate::generate::correlated::generate_correlated_group(
group_plan, row_index, rng, base_time, locale,
);
for (col_name, value) in group_values {
correlated_values.insert(col_name, value);
}
}
let record = table_plan.records.get(row_index);
for col_plan in &table_plan.column_plans {
if let Some(value) = record.and_then(|r| r.get(&col_plan.column_name)) {
if unique_tracker.contains(
&table_plan.table_name,
std::slice::from_ref(&col_plan.column_name),
&[value],
) {
return Err(SeedKitError::Config {
message: format!(
"Duplicate fixed value for {}.{} in scenario record {}",
table_plan.table_name,
col_plan.column_name,
row_index + 1
),
});
}
row.insert(col_plan.column_name.clone(), value.clone());
continue;
}
if matches!(col_plan.strategy, GenerationStrategy::CompositeReference) {
continue;
}
let rng = streams.stream(
&table_plan.table_name,
row_index,
attempt,
"column",
&col_plan.column_name,
);
if col_plan.nullable && col_plan.null_probability > 0.0 {
let roll: f64 = rng.random();
if roll < col_plan.null_probability {
row.insert(col_plan.column_name.clone(), Value::Null);
continue;
}
}
let max_chars = schema
.tables
.get(&table_plan.table_name)
.and_then(|t| t.columns.get(&col_plan.column_name))
.filter(|c| c.data_type.is_string())
.and_then(|c| c.max_length)
.map(|n| n as usize);
let provider_value = |rng: &mut StdRng, index| {
if let Some(allowed) = &col_plan.allowed_values {
use rand::prelude::IndexedRandom;
return allowed
.choose(rng)
.cloned()
.or_else(|| col_plan.nullable.then_some(Value::Null))
.ok_or_else(|| SeedKitError::Config {
message: format!(
"No value satisfies the CHECK lists for {}.{}",
table_plan.table_name, col_plan.column_name
),
});
}
match &col_plan.strategy {
GenerationStrategy::Typed(kind) => {
return Ok(kind.sample(rng, col_plan.semantic_type, index, base_time, locale))
}
GenerationStrategy::Pattern(pattern) => {
return Ok(Value::String(Cow::Owned(pattern.sample(rng, index))))
}
GenerationStrategy::Range { min, max, decimals } => {
return Ok(sample_range(rng, *min, *max, *decimals))
}
_ => {}
}
if let GenerationStrategy::NumericFallback(kind) = &col_plan.strategy {
kind.sample(rng, &col_plan.check_constraints)
.ok_or_else(|| SeedKitError::Config {
message: format!(
"No representable numeric value for {}.{} within its checks",
table_plan.table_name, col_plan.column_name
),
})
} else {
Ok(fit_length(
generate_localized(
locale,
col_plan.semantic_type,
rng,
index,
&col_plan.check_constraints,
base_time,
),
max_chars,
))
}
};
let value = match &col_plan.strategy {
GenerationStrategy::CompositeReference => unreachable!("assigned as a tuple"),
GenerationStrategy::AutoIncrement => {
continue;
}
GenerationStrategy::ExternalReference { target } => {
if !col_plan.nullable {
return Err(SeedKitError::Config {
message: format!("{}.{} references {target} outside the write schema; configure [[existing_parents]] for this relationship", table_plan.table_name, col_plan.column_name),
});
}
Value::Null
}
GenerationStrategy::ReferenceKeys(keys) => keys[row_index % keys.len()].clone(),
GenerationStrategy::Skip => {
continue;
}
GenerationStrategy::Deferred => {
Value::Null
}
GenerationStrategy::SharedPrimaryKey {
referenced_table,
referenced_column,
} => {
fk_pool.get_pool(referenced_table, referenced_column)
.and_then(|parents| parents.get(row_index)).cloned()
.ok_or_else(|| SeedKitError::Other(format!(
"No distinct parent in {referenced_table}.{referenced_column} for {}.{} row {row_index}",
table_plan.table_name, col_plan.column_name
)))?
}
GenerationStrategy::ForeignKeyReference {
referenced_table,
referenced_column,
} => match fk_pool.pick_reference(referenced_table, referenced_column, rng) {
Some(v) => v,
None => {
if col_plan.nullable {
Value::Null
} else {
return Err(SeedKitError::ForeignKeyResolution {
source_table: table_plan.table_name.clone(),
source_column: col_plan.column_name.clone(),
target_table: referenced_table.clone(),
target_column: referenced_column.clone(),
});
}
}
},
GenerationStrategy::EnumValue { values } => {
if values.is_empty() {
Value::Null
} else {
let idx = rng.random_range(0..values.len());
Value::String(Cow::Owned(values[idx].clone()))
}
}
GenerationStrategy::Correlated { .. } => {
let value = correlated_values
.shift_remove(&col_plan.column_name)
.unwrap_or_else(|| {
generate_localized(
locale,
col_plan.semantic_type,
rng,
row_index,
&col_plan.check_constraints,
base_time,
)
});
fit_length(value, max_chars)
}
GenerationStrategy::SemanticProvider
| GenerationStrategy::NumericFallback(_)
| GenerationStrategy::Typed(_)
| GenerationStrategy::Pattern(_)
| GenerationStrategy::Range { .. } => provider_value(rng, row_index)?,
GenerationStrategy::ValueList { values, weights } => {
pick_literal(values, weights.as_deref(), rng)
}
GenerationStrategy::Distribution { ref distribution } => {
fit_length(generate_from_distribution(distribution, rng), max_chars)
}
};
let value = match value {
Value::Float(sampled)
if matches!(col_plan.strategy, GenerationStrategy::Distribution { .. })
&& schema
.tables
.get(&table_plan.table_name)
.and_then(|t| t.columns.get(&col_plan.column_name))
.is_some_and(|c| c.data_type.is_integer()) =>
{
Value::Int(sampled.round() as i64)
}
value => value,
};
if let Some(table) = schema.tables.get(&table_plan.table_name) {
let needs_unique = table
.unique_constraints
.iter()
.any(|uc| uc.columns.len() == 1 && uc.columns[0] == col_plan.column_name)
|| table.primary_key.as_ref().is_some_and(|pk| {
pk.columns.len() == 1 && pk.columns[0] == col_plan.column_name
});
if needs_unique && !value.is_null() {
let mut final_value = value;
let mut col_attempts = 0;
while unique_tracker.contains(
&table_plan.table_name,
std::slice::from_ref(&col_plan.column_name),
&[&final_value],
) {
col_attempts += 1;
if matches!(col_plan.strategy, GenerationStrategy::ReferenceKeys(_))
|| col_attempts >= unique_tracker.max_retries
{
return Err(SeedKitError::UniqueExhausted {
table: table_plan.table_name.clone(),
column: col_plan.column_name.clone(),
row_index,
max_retries: unique_tracker.max_retries,
});
}
final_value = match &col_plan.strategy {
GenerationStrategy::ValueList { values, weights } => {
pick_literal(values, weights.as_deref(), rng)
}
_ => provider_value(rng, row_index + col_attempts)?,
};
}
row.insert(col_plan.column_name.clone(), final_value);
continue;
}
}
row.insert(col_plan.column_name.clone(), value);
}
if table_plan
.column_plans
.iter()
.any(|c| matches!(c.strategy, GenerationStrategy::CompositeReference))
{
let table = &schema.tables[&table_plan.table_name];
for fk in table.local_foreign_keys() {
if fk.source_columns.len() < 2
|| !table_plan.column_plans.iter().any(|c| {
matches!(c.strategy, GenerationStrategy::CompositeReference)
&& fk.source_columns.contains(&c.column_name)
})
{
continue;
}
let pool = fk_pool.tuples(&fk.referenced_table, &fk.referenced_columns);
let fixed = fk
.source_columns
.iter()
.enumerate()
.filter_map(|(i, name)| row.get(name).map(|v| (i, v)))
.collect::<Vec<_>>();
let all_nullable = fk
.source_columns
.iter()
.all(|col| table.columns[col].nullable);
let edge = fk.source_columns.join("\0");
let rng = streams.stream(
&table_plan.table_name,
row_index,
attempt,
"composite",
&edge,
);
let one_to_one = table
.primary_key
.iter()
.map(|p| &p.columns)
.chain(table.unique_constraints.iter().map(|u| &u.columns))
.any(|key| {
key.len() == fk.source_columns.len()
&& key.iter().all(|c| fk.source_columns.contains(c))
});
let values = if fixed.is_empty() && one_to_one {
pool.get(row_index)
} else if fixed.is_empty() {
use rand::prelude::IndexedRandom;
pool.choose(rng)
} else {
use rand::seq::IteratorRandom;
pool.iter()
.filter(|tuple| fixed.iter().all(|(i, v)| &tuple[*i] == *v))
.choose(rng)
};
if let Some(tuple) = values {
row.extend(
fk.source_columns
.iter()
.zip(tuple)
.filter(|(c, _)| !table.columns[*c].is_generated)
.map(|(c, v)| (c.clone(), v.clone())),
);
} else if all_nullable && fixed.is_empty() {
row.extend(
fk.source_columns
.iter()
.filter(|c| !table.columns[*c].is_generated)
.map(|c| (c.clone(), Value::Null)),
);
} else {
return Err(SeedKitError::ForeignKeyResolution {
source_table: table.name.clone(),
source_column: fk.source_columns.join(", "),
target_table: fk.referenced_table.clone(),
target_column: fk.referenced_columns.join(", "),
});
}
}
}
for col in &table_plan.column_plans {
if let (Some(allowed), Some(value)) = (&col.allowed_values, row.get(&col.column_name)) {
if !value.is_null() && !allowed.contains(value) {
return Err(SeedKitError::Config {
message: format!(
"Value for {}.{} is outside its CHECK list on row {row_index}",
table_plan.table_name, col.column_name
),
});
}
}
}
Ok(row)
}
fn fit_length(value: Value, max_chars: Option<usize>) -> Value {
let end = match (&value, max_chars) {
(Value::String(text), Some(max)) => text.char_indices().nth(max).map(|(end, _)| end),
_ => None,
};
match (value, end) {
(Value::String(text), Some(end)) => Value::String(Cow::Owned(text[..end].to_owned())),
(value, _) => value,
}
}
fn sample_range(rng: &mut impl Rng, min: f64, max: f64, decimals: Option<u32>) -> Value {
match decimals {
None => {
let (low, high) = (min.ceil() as i64, max.floor() as i64);
Value::Int(if low <= high {
rng.random_range(low..=high)
} else {
min.round() as i64
})
}
Some(places) => {
let scale = 10f64.powi(places as i32);
let raw = if min < max {
rng.random_range(min..=max)
} else {
min
};
let rounded = (raw * scale).round() / scale;
Value::Float(if rounded > max {
(max * scale).floor() / scale
} else if rounded < min {
(min * scale).ceil() / scale
} else {
rounded
})
}
}
}
fn pick_literal(values: &[FixtureValue], weights: Option<&[f64]>, rng: &mut impl Rng) -> Value {
if values.is_empty() {
return Value::Null;
}
match weights {
Some(weights) => weighted_pick(values, weights, rng),
None => values[rng.random_range(0..values.len())].to_value(),
}
}
fn weighted_pick(values: &[FixtureValue], weights: &[f64], rng: &mut impl Rng) -> Value {
if values.len() == 1 {
return values[0].to_value();
}
let clamped: Vec<f64> = weights.iter().map(|w| w.max(0.0)).collect();
let total: f64 = clamped.iter().sum();
if total <= 0.0 {
let idx = rng.random_range(0..values.len());
return values[idx].to_value();
}
let roll: f64 = rng.random::<f64>() * total;
let mut cumulative = 0.0;
for (i, w) in clamped.iter().enumerate() {
cumulative += w;
if roll < cumulative {
return values[i].to_value();
}
}
values.last().unwrap().to_value()
}
fn generate_from_distribution(distribution: &ColumnDistribution, rng: &mut impl Rng) -> Value {
match distribution {
ColumnDistribution::Categorical { values } => {
if values.is_empty() {
return Value::Null;
}
let total: f64 = values.iter().map(|(_, f)| f.max(0.0)).sum();
if total <= 0.0 {
let idx = rng.random_range(0..values.len());
return Value::String(Cow::Owned(values[idx].0.clone()));
}
let roll: f64 = rng.random::<f64>() * total;
let mut cumulative = 0.0;
for (val, freq) in values {
cumulative += freq.max(0.0);
if roll < cumulative {
return Value::String(Cow::Owned(val.clone()));
}
}
Value::String(Cow::Owned(values.last().unwrap().0.clone()))
}
ColumnDistribution::Numeric {
min,
max,
mean,
stddev,
} => {
if *stddev <= 0.0 || min == max {
let val = mean.clamp(*min, *max);
return Value::Float(val);
}
let normal = box_muller_normal(rng);
let raw = mean + stddev * normal;
let clamped = raw.clamp(*min, *max);
Value::Float(clamped)
}
ColumnDistribution::Ratio { .. } => {
Value::Null
}
}
}
fn box_muller_normal(rng: &mut impl Rng) -> f64 {
let u1: f64 = rng.random::<f64>().max(f64::MIN_POSITIVE); let u2: f64 = rng.random::<f64>();
(-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::types::*;
use rand::rngs::StdRng;
use rand::SeedableRng;
use std::borrow::Cow;
fn single_column_plan(
table: &str,
column: &str,
strategy: GenerationStrategy,
row_count: usize,
) -> GenerationPlan {
GenerationPlan {
scenario: Default::default(),
table_plans: vec![TableGenerationPlan {
records: Vec::new(),
table_name: table.to_string(),
row_count,
column_plans: vec![ColumnGenerationPlan {
column_name: column.to_string(),
semantic_type: crate::classify::semantic::SemanticType::Unknown,
strategy,
nullable: false,
null_probability: 0.0,
allowed_values: None,
check_constraints: Vec::new(),
}],
correlation_groups: Vec::new(),
}],
deferred_edges: Vec::new(),
seed: 42,
default_row_count: row_count,
base_time: chrono::Utc::now().naive_utc(),
generator_version: Default::default(),
sequence_offset: 0,
locale: Default::default(),
}
}
fn empty_schema() -> DatabaseSchema {
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let table = Table::new("items".to_string());
schema.tables.insert("items".to_string(), table);
schema
}
#[test]
fn test_value_list_uniform_distribution() {
let plan = single_column_plan(
"items",
"color",
GenerationStrategy::ValueList {
values: vec!["red".into(), "blue".into(), "green".into()],
weights: None,
},
300,
);
let schema = empty_schema();
let data = execute_plan(&plan, &schema, None).unwrap();
let rows = &data.tables["items"];
assert_eq!(rows.len(), 300);
for row in rows {
let val = row.get("color").unwrap();
match val {
Value::String(s) => {
assert!(
s == "red" || s == "blue" || s == "green",
"Unexpected value: {}",
s
);
}
_ => panic!("Expected String, got {:?}", val),
}
}
let count_red = rows
.iter()
.filter(|r| r.get("color") == Some(&Value::String(Cow::Owned("red".into()))))
.count();
let count_blue = rows
.iter()
.filter(|r| r.get("color") == Some(&Value::String(Cow::Owned("blue".into()))))
.count();
let count_green = rows
.iter()
.filter(|r| r.get("color") == Some(&Value::String(Cow::Owned("green".into()))))
.count();
assert!(count_red > 0, "red should appear");
assert!(count_blue > 0, "blue should appear");
assert!(count_green > 0, "green should appear");
assert_eq!(count_red + count_blue + count_green, 300);
}
#[test]
fn test_value_list_weighted_distribution() {
let plan = single_column_plan(
"items",
"tag",
GenerationStrategy::ValueList {
values: vec!["a".into(), "b".into()],
weights: Some(vec![0.9, 0.1]),
},
1000,
);
let schema = empty_schema();
let data = execute_plan(&plan, &schema, None).unwrap();
let rows = &data.tables["items"];
let count_a = rows
.iter()
.filter(|r| r.get("tag") == Some(&Value::String(Cow::Owned("a".into()))))
.count();
assert!(
count_a > 700,
"Expected >700 'a' values with 0.9 weight, got {}",
count_a
);
}
#[test]
fn test_value_list_single_value() {
let plan = single_column_plan(
"items",
"status",
GenerationStrategy::ValueList {
values: vec!["active".into()],
weights: Some(vec![1.0]),
},
10,
);
let schema = empty_schema();
let data = execute_plan(&plan, &schema, None).unwrap();
let rows = &data.tables["items"];
for row in rows {
assert_eq!(
row.get("status"),
Some(&Value::String(Cow::Owned("active".into())))
);
}
}
#[test]
fn test_value_list_empty_produces_null() {
let plan = single_column_plan(
"items",
"empty_col",
GenerationStrategy::ValueList {
values: Vec::new(),
weights: None,
},
5,
);
let schema = empty_schema();
let data = execute_plan(&plan, &schema, None).unwrap();
let rows = &data.tables["items"];
for row in rows {
assert_eq!(row.get("empty_col"), Some(&Value::Null));
}
}
#[test]
fn test_value_list_deterministic_with_seed() {
let strategy = GenerationStrategy::ValueList {
values: vec!["x".into(), "y".into(), "z".into()],
weights: Some(vec![0.33, 0.33, 0.34]),
};
let plan1 = single_column_plan("items", "val", strategy.clone(), 50);
let plan2 = single_column_plan("items", "val", strategy, 50);
let schema = empty_schema();
let data1 = execute_plan(&plan1, &schema, None).unwrap();
let data2 = execute_plan(&plan2, &schema, None).unwrap();
let vals1: Vec<_> = data1.tables["items"]
.iter()
.map(|r| r.get("val").unwrap().clone())
.collect();
let vals2: Vec<_> = data2.tables["items"]
.iter()
.map(|r| r.get("val").unwrap().clone())
.collect();
assert_eq!(vals1, vals2, "Same seed should produce identical output");
}
#[test]
fn test_weighted_pick_all_zeros_uniform_fallback() {
let values = vec!["a".into(), "b".into(), "c".into()];
let weights = vec![0.0, 0.0, 0.0];
let mut rng = StdRng::seed_from_u64(42);
let mut results = std::collections::HashSet::new();
for _ in 0..100 {
if let Value::String(s) = weighted_pick(&values, &weights, &mut rng) {
results.insert(s.to_string());
}
}
assert!(results.len() > 1, "Uniform fallback should produce variety");
}
#[test]
fn test_weighted_pick_negative_weights_clamped() {
let values = vec!["a".into(), "b".into()];
let weights = vec![-1.0, 1.0];
let mut rng = StdRng::seed_from_u64(42);
for _ in 0..50 {
if let Value::String(s) = weighted_pick(&values, &weights, &mut rng) {
assert_eq!(s.as_ref(), "b", "Negative weight should be clamped to 0");
}
}
}
#[test]
fn test_distribution_strategy_categorical() {
let plan = single_column_plan(
"items",
"status",
GenerationStrategy::Distribution {
distribution: ColumnDistribution::Categorical {
values: vec![
("active".to_string(), 0.8),
("inactive".to_string(), 0.15),
("suspended".to_string(), 0.05),
],
},
},
500,
);
let schema = empty_schema();
let data = execute_plan(&plan, &schema, None).unwrap();
let rows = &data.tables["items"];
assert_eq!(rows.len(), 500);
for row in rows {
match row.get("status").unwrap() {
Value::String(s) => {
assert!(
s == "active" || s == "inactive" || s == "suspended",
"Unexpected value: {}",
s
);
}
other => panic!("Expected String, got {:?}", other),
}
}
let count_active = rows
.iter()
.filter(|r| r.get("status") == Some(&Value::String(Cow::Owned("active".into()))))
.count();
assert!(
count_active > 300,
"Expected >300 'active' with 0.8 weight, got {}",
count_active
);
}
#[test]
fn test_distribution_strategy_numeric_clamped() {
let plan = single_column_plan(
"items",
"price",
GenerationStrategy::Distribution {
distribution: ColumnDistribution::Numeric {
min: 0.0,
max: 100.0,
mean: 50.0,
stddev: 15.0,
},
},
1000,
);
let schema = empty_schema();
let data = execute_plan(&plan, &schema, None).unwrap();
let rows = &data.tables["items"];
let mut values: Vec<f64> = Vec::new();
for row in rows {
match row.get("price").unwrap() {
Value::Float(f) => {
assert!(*f >= 0.0, "Value should be >= min (0.0): {}", f);
assert!(*f <= 100.0, "Value should be <= max (100.0): {}", f);
values.push(*f);
}
other => panic!("Expected Float, got {:?}", other),
}
}
let actual_mean: f64 = values.iter().sum::<f64>() / values.len() as f64;
assert!(
(actual_mean - 50.0).abs() < 10.0,
"Mean should be roughly 50.0, got {}",
actual_mean
);
}
#[test]
fn test_normal_distribution_within_bounds() {
let mut rng = StdRng::seed_from_u64(42);
for _ in 0..1000 {
let val = generate_from_distribution(
&ColumnDistribution::Numeric {
min: 10.0,
max: 20.0,
mean: 15.0,
stddev: 3.0,
},
&mut rng,
);
if let Value::Float(f) = val {
assert!((10.0..=20.0).contains(&f), "Out of bounds: {}", f);
} else {
panic!("Expected Float, got {:?}", val);
}
}
}
#[test]
fn test_distribution_zero_stddev_returns_mean() {
let mut rng = StdRng::seed_from_u64(42);
let val = generate_from_distribution(
&ColumnDistribution::Numeric {
min: 0.0,
max: 100.0,
mean: 42.5,
stddev: 0.0,
},
&mut rng,
);
assert_eq!(val, Value::Float(42.5));
}
#[test]
fn test_distribution_empty_categorical_produces_null() {
let mut rng = StdRng::seed_from_u64(42);
let val = generate_from_distribution(
&ColumnDistribution::Categorical { values: vec![] },
&mut rng,
);
assert_eq!(val, Value::Null);
}
#[test]
fn test_distribution_ratio_produces_null() {
let mut rng = StdRng::seed_from_u64(42);
let val = generate_from_distribution(
&ColumnDistribution::Ratio {
related_table: "users".to_string(),
ratio: 3.2,
},
&mut rng,
);
assert_eq!(val, Value::Null);
}
}