use std::collections::BTreeMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::error::{Result, SeedKitError};
pub const CONFIG_FILE_NAME: &str = "seedkit.toml";
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct SeedKitConfig {
pub database: DatabaseConfig,
pub generate: GenerateConfig,
pub scenarios: BTreeMap<String, crate::generate::scenario::Scenario>,
pub tables: BTreeMap<String, TableConfig>,
pub columns: BTreeMap<String, ColumnConfig>,
pub existing_parents: Vec<crate::generate::existing::ExistingParent>,
pub graph: GraphConfig,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct DatabaseConfig {
pub url: Option<String>,
pub schema: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct GenerateConfig {
pub rows: Option<usize>,
pub seed: Option<u64>,
pub ai: Option<bool>,
pub include: Option<Vec<String>>,
pub exclude: Option<Vec<String>>,
pub locale: Option<crate::generate::locale::Locale>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct TableConfig {
pub rows: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FixtureValue {
Text(String),
Integer(i64),
Boolean(bool),
Float(#[serde(deserialize_with = "finite_float")] f64),
}
fn finite_float<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<f64, D::Error> {
let value = f64::deserialize(deserializer)?;
if value.is_finite() {
Ok(value)
} else {
Err(serde::de::Error::custom("fixture number must be finite"))
}
}
impl From<&str> for FixtureValue {
fn from(value: &str) -> Self {
Self::Text(value.into())
}
}
impl FixtureValue {
pub(crate) fn fits(&self, column: &crate::schema::types::Column) -> bool {
use crate::schema::types::DataType;
match self {
Self::Text(s) => column
.enum_values
.as_ref()
.is_none_or(|labels| labels.contains(s)),
Self::Boolean(_) => {
matches!(column.data_type, DataType::Boolean) || column.raw_type == "tinyint"
}
Self::Integer(_) => column.data_type.is_numeric(),
Self::Float(_) => matches!(
column.data_type,
DataType::Float | DataType::Double | DataType::Numeric | DataType::Money
),
}
}
pub fn to_value(&self) -> crate::generate::value::Value {
use crate::generate::value::Value;
match self {
Self::Text(s) => Value::String(s.clone().into()),
Self::Integer(i) => Value::Int(*i),
Self::Boolean(b) => Value::Bool(*b),
Self::Float(f) => Value::Float(*f),
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ColumnConfig {
pub values: Option<Vec<FixtureValue>>,
pub weights: Option<Vec<f64>>,
pub pattern: Option<String>,
pub range: Option<[f64; 2]>,
pub semantic: Option<crate::classify::semantic::SemanticType>,
pub null_rate: Option<f64>,
pub custom: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct GraphConfig {
pub break_cycle_at: Vec<String>,
}
pub fn read_config(dir: &Path) -> Result<Option<SeedKitConfig>> {
let path = dir.join(CONFIG_FILE_NAME);
if !path.exists() {
return Ok(None);
}
let content = std::fs::read_to_string(&path).map_err(|e| SeedKitError::Config {
message: format!("Failed to read {}: {}", path.display(), e),
})?;
let config: SeedKitConfig = toml::from_str(&content).map_err(|e| SeedKitError::Config {
message: format!("Failed to parse {}: {}", path.display(), e),
})?;
config.validate()?;
Ok(Some(config))
}
impl SeedKitConfig {
pub fn table_row_overrides(&self) -> BTreeMap<String, usize> {
let mut map = BTreeMap::new();
for (name, tc) in &self.tables {
if let Some(rows) = tc.rows {
map.insert(name.clone(), rows);
}
}
map
}
pub fn cycle_break_edges(&self) -> Vec<(String, String)> {
self.graph
.break_cycle_at
.iter()
.filter_map(|entry| {
let parts: Vec<&str> = entry.splitn(2, '.').collect();
if parts.len() == 2 {
Some((parts[0].to_string(), parts[1].to_string()))
} else {
tracing::warn!(
"Invalid graph.break_cycle_at entry: '{}'. \
Expected format 'table.column'. Ignoring.",
entry
);
None
}
})
.collect()
}
pub fn validate(&self) -> Result<()> {
for (key, col_cfg) in &self.columns {
let invalid = |message: String| SeedKitError::Config {
message: format!("Column '{key}': {message}"),
};
if col_cfg.custom.is_some() {
return Err(invalid(
"custom providers are not supported. Use values, pattern, range, or \
semantic instead."
.into(),
));
}
let generators = [
col_cfg.values.is_some(),
col_cfg.pattern.is_some(),
col_cfg.range.is_some(),
];
if generators.iter().filter(|set| **set).count() > 1 {
return Err(invalid("set only one of values, pattern, or range.".into()));
}
if let Some(pattern) = &col_cfg.pattern {
crate::generate::pattern::Pattern::parse(pattern)
.map_err(|e| invalid(format!("invalid pattern: {e}")))?;
}
if let Some([min, max]) = col_cfg.range {
if !(min.is_finite() && max.is_finite() && min <= max) {
return Err(invalid(format!(
"range must be [min, max] with min <= max, got [{min}, {max}]"
)));
}
}
if let Some(rate) = col_cfg.null_rate {
if !(0.0..=1.0).contains(&rate) {
return Err(invalid(format!(
"null_rate must be between 0 and 1, got {rate}"
)));
}
}
if let Some(ref weights) = col_cfg.weights {
match col_cfg.values {
Some(ref values) => {
if values.len() != weights.len() {
return Err(SeedKitError::Config {
message: format!(
"Column '{}': weights has {} entries but values has {} entries. \
They must be the same length.",
key,
weights.len(),
values.len(),
),
});
}
}
None => {
return Err(SeedKitError::Config {
message: format!(
"Column '{}': weights provided without values. \
Add a matching values list or remove the weights.",
key,
),
});
}
}
}
}
Ok(())
}
pub fn validate_against_schema(
&self,
schema: &crate::schema::types::DatabaseSchema,
) -> Vec<String> {
let mut warnings = Vec::new();
for key in self.columns.keys() {
if let Some((table, col)) = key.split_once('.') {
if let Some(table_def) = schema.tables.get(table) {
if !table_def.columns.contains_key(col) {
warnings.push(format!(
"seedkit.toml: [columns.\"{}\"] references column '{}' \
which does not exist in table '{}'",
key, col, table
));
}
} else {
warnings.push(format!(
"seedkit.toml: [columns.\"{}\"] references table '{}' \
which does not exist in schema",
key, table
));
}
} else {
warnings.push(format!(
"seedkit.toml: [columns.\"{}\"] is not in 'table.column' format",
key
));
}
}
warnings
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_full_config() {
let toml = r#"
[database]
url = "postgres://localhost/myapp"
schema = "public"
[generate]
rows = 500
seed = 42
ai = false
[tables.users]
rows = 1000
[tables.orders]
rows = 5000
[columns."products.color"]
values = ["red", "blue", "green"]
weights = [0.5, 0.3, 0.2]
[columns."orders.tax_code"]
custom = "./scripts/tax_gen.js"
[graph]
break_cycle_at = ["users.invited_by_id", "comments.parent_id"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
assert_eq!(
config.database.url.as_deref(),
Some("postgres://localhost/myapp")
);
assert_eq!(config.database.schema.as_deref(), Some("public"));
assert_eq!(config.generate.rows, Some(500));
assert_eq!(config.generate.seed, Some(42));
assert_eq!(config.generate.ai, Some(false));
assert_eq!(config.tables["users"].rows, Some(1000));
assert_eq!(config.tables["orders"].rows, Some(5000));
let colors = config.columns["products.color"].values.as_ref().unwrap();
assert_eq!(colors, &["red", "blue", "green"].map(FixtureValue::from));
let weights = config.columns["products.color"].weights.as_ref().unwrap();
assert_eq!(weights.len(), 3);
assert_eq!(
config.columns["orders.tax_code"].custom.as_deref(),
Some("./scripts/tax_gen.js")
);
assert_eq!(config.graph.break_cycle_at.len(), 2);
}
#[test]
fn test_parse_empty_config() {
let toml = "";
let config: SeedKitConfig = toml::from_str(toml).unwrap();
assert!(config.database.url.is_none());
assert!(config.generate.rows.is_none());
assert!(config.tables.is_empty());
assert!(config.columns.is_empty());
assert!(config.graph.break_cycle_at.is_empty());
}
#[test]
fn test_parse_minimal_config() {
let toml = r#"
[database]
url = "sqlite://dev.db"
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
assert_eq!(config.database.url.as_deref(), Some("sqlite://dev.db"));
assert!(config.generate.rows.is_none());
}
#[test]
fn test_table_row_overrides() {
let toml = r#"
[tables.users]
rows = 1000
[tables.orders]
rows = 5000
[tables.products]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let overrides = config.table_row_overrides();
assert_eq!(overrides.len(), 2);
assert_eq!(overrides["users"], 1000);
assert_eq!(overrides["orders"], 5000);
}
#[test]
fn test_cycle_break_edges() {
let toml = r#"
[graph]
break_cycle_at = ["users.invited_by_id", "comments.parent_id", "invalid"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let edges = config.cycle_break_edges();
assert_eq!(edges.len(), 2);
assert_eq!(edges[0], ("users".to_string(), "invited_by_id".to_string()));
assert_eq!(edges[1], ("comments".to_string(), "parent_id".to_string()));
}
#[test]
fn test_read_config_nonexistent() {
let result = read_config(Path::new("/nonexistent/dir"));
assert!(result.is_ok());
assert!(result.unwrap().is_none());
}
#[test]
fn test_read_config_from_disk() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("seedkit.toml");
std::fs::write(
&config_path,
r#"
[database]
url = "postgres://localhost/test"
[generate]
rows = 200
"#,
)
.unwrap();
let result = read_config(dir.path()).unwrap();
assert!(result.is_some());
let config = result.unwrap();
assert_eq!(
config.database.url.as_deref(),
Some("postgres://localhost/test")
);
assert_eq!(config.generate.rows, Some(200));
}
#[test]
fn test_read_config_invalid_toml() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("seedkit.toml");
std::fs::write(&config_path, "this is not valid [[[toml").unwrap();
let result = read_config(dir.path());
assert!(result.is_err());
}
#[test]
fn test_cycle_break_edges_malformed_entry_still_parses_valid() {
let toml = r#"
[graph]
break_cycle_at = ["users.invited_by_id", "no_dot_here", "comments.parent_id"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let edges = config.cycle_break_edges();
assert_eq!(edges.len(), 2);
assert_eq!(edges[0], ("users".to_string(), "invited_by_id".to_string()));
assert_eq!(edges[1], ("comments".to_string(), "parent_id".to_string()));
}
#[test]
fn read_config_rejects_custom_providers_with_a_replacement() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("seedkit.toml"),
"[columns.\"orders.tax_code\"]\ncustom = \"./scripts/tax_gen.js\"\n",
)
.unwrap();
let err = read_config(dir.path()).unwrap_err().to_string();
assert!(
err.contains("orders.tax_code") && err.contains("pattern"),
"{err}"
);
}
#[test]
fn test_validate_matching_values_weights() {
let toml = r#"
[columns."products.color"]
values = ["red", "blue", "green"]
weights = [0.5, 0.3, 0.2]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
assert!(config.validate().is_ok());
}
#[test]
fn test_validate_mismatched_values_weights_fails() {
let toml = r#"
[columns."products.color"]
values = ["red", "blue", "green", "black", "white"]
weights = [0.25, 0.20, 0.20, 0.20]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let err = config.validate();
assert!(err.is_err());
let msg = format!("{}", err.unwrap_err());
assert!(
msg.contains("products.color"),
"Error should name the column: {}",
msg
);
assert!(
msg.contains("5"),
"Error should mention values count: {}",
msg
);
assert!(
msg.contains("4"),
"Error should mention weights count: {}",
msg
);
}
#[test]
fn test_validate_weights_without_values_fails() {
let toml = r#"
[columns."orders.status"]
weights = [0.5, 0.3, 0.2]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let err = config.validate();
assert!(err.is_err());
let msg = format!("{}", err.unwrap_err());
assert!(
msg.contains("orders.status"),
"Error should name the column: {}",
msg
);
}
#[test]
fn test_validate_values_without_weights_ok() {
let toml = r#"
[columns."products.color"]
values = ["red", "blue", "green"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
assert!(config.validate().is_ok());
}
#[test]
fn test_validate_no_columns_ok() {
let toml = r#"
[generate]
rows = 100
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
assert!(config.validate().is_ok());
}
fn columns(toml: &str) -> Result<SeedKitConfig> {
let config: SeedKitConfig = toml::from_str(toml).map_err(|e| SeedKitError::Config {
message: e.to_string(),
})?;
config.validate().map(|_| config)
}
#[test]
fn column_generators_parse() {
let config = columns(
r#"
[columns."orders.number"]
pattern = "INV-{row:06}"
[columns."orders.total"]
range = [5, 500.5]
null_rate = 0.25
[columns."users.employer"]
semantic = "CompanyName"
"#,
)
.unwrap();
assert_eq!(
config.columns["orders.number"].pattern.as_deref(),
Some("INV-{row:06}")
);
assert_eq!(config.columns["orders.total"].range, Some([5.0, 500.5]));
assert_eq!(config.columns["orders.total"].null_rate, Some(0.25));
assert_eq!(
config.columns["users.employer"].semantic,
Some(crate::classify::semantic::SemanticType::CompanyName)
);
}
#[test]
fn invalid_column_generators_are_rejected_before_introspection() {
let cases = [
("null_rate = 1.5", "null_rate"),
("range = [10, 1]", "range"),
("values = [\"a\"]\npattern = \"X-#\"", "only one of"),
("pattern = \"INV-{row\"", "pattern"),
("pattern = \"\"", "pattern"),
("semantic = \"ProductCode\"", "ProductCode"),
(
"custom = \"./tax.js\"",
"custom providers are not supported",
),
];
for (body, expected) in cases {
let err = columns(&format!("[columns.\"orders.code\"]\n{body}\n"))
.err()
.unwrap_or_else(|| panic!("{body} should be rejected"))
.to_string();
assert!(
err.contains("orders.code") || err.contains(expected),
"{body}: {err}"
);
assert!(err.contains(expected), "{body}: {err}");
}
}
#[test]
fn test_validate_against_schema_valid_override() {
use crate::schema::types::*;
let toml = r#"
[columns."users.email"]
values = ["a@b.com", "c@d.com"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut users = Table::new("users".to_string());
users.columns.insert(
"email".to_string(),
Column::new(
"email".to_string(),
DataType::VarChar,
"varchar".to_string(),
),
);
schema.tables.insert("users".to_string(), users);
let warnings = config.validate_against_schema(&schema);
assert!(
warnings.is_empty(),
"Valid override should produce no warnings: {:?}",
warnings
);
}
#[test]
fn test_validate_against_schema_nonexistent_table() {
use crate::schema::types::*;
let toml = r#"
[columns."ghost.name"]
values = ["x"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let warnings = config.validate_against_schema(&schema);
assert_eq!(warnings.len(), 1);
assert!(
warnings[0].contains("ghost"),
"Should mention table: {}",
warnings[0]
);
}
#[test]
fn test_validate_against_schema_nonexistent_column() {
use crate::schema::types::*;
let toml = r#"
[columns."users.nonexistent"]
values = ["x"]
"#;
let config: SeedKitConfig = toml::from_str(toml).unwrap();
let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
let mut users = Table::new("users".to_string());
users.columns.insert(
"email".to_string(),
Column::new(
"email".to_string(),
DataType::VarChar,
"varchar".to_string(),
),
);
schema.tables.insert("users".to_string(), users);
let warnings = config.validate_against_schema(&schema);
assert_eq!(warnings.len(), 1);
assert!(
warnings[0].contains("nonexistent"),
"Should mention column: {}",
warnings[0]
);
}
}