use std::collections::BTreeMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use anyhow::{bail, Context, Result};
use indicatif::{ProgressBar, ProgressStyle};
use seedkit_core::check::compute_schema_hash;
use seedkit_core::classify::rules::classify_schema;
use seedkit_core::classify::semantic::SemanticType;
use seedkit_core::config::ColumnConfig;
use seedkit_core::generate::engine;
use seedkit_core::generate::plan::{filter_insertion_order, GenerationPlan};
use seedkit_core::graph::cycle::break_cycles;
use seedkit_core::graph::dag::DependencyGraph;
use seedkit_core::graph::topo::topological_sort;
use seedkit_core::llm;
use seedkit_core::llm::classify::ClassificationTarget;
use seedkit_core::lock;
use seedkit_core::lock::types::{LockConfig, LockFile};
use seedkit_core::output;
use seedkit_core::schema::types::{DatabaseSchema, DatabaseType};
use crate::args::{GenerateArgs, GenerationOptions, OutputFormat};
pub(super) struct Prepared {
pub plan: GenerationPlan,
pub schema: DatabaseSchema,
db_url: String,
original_schema: Option<DatabaseSchema>,
parent_locks: Vec<seedkit_core::generate::existing::LockedParent>,
lock_config: LockConfig,
scenario: Option<seedkit_core::generate::scenario::NamedScenario>,
}
impl Prepared {
pub(super) fn db_url(&self) -> &str {
&self.db_url
}
pub(super) fn introspected(&self) -> &DatabaseSchema {
self.original_schema.as_ref().unwrap_or(&self.schema)
}
pub(super) fn write_lock(self) -> Result<()> {
let lock_schema = self.original_schema.unwrap_or(self.schema);
let mut lock_file = LockFile::new(
compute_schema_hash(&lock_schema),
self.plan.seed,
self.plan.base_time,
self.lock_config,
lock_schema,
);
lock_file.generator_version = self.plan.generator_version;
lock_file.existing_parents = self.parent_locks;
lock_file.scenario = self.scenario;
lock::write_lock_file(&lock_file, Path::new(lock::LOCK_FILE_NAME))?;
eprintln!("Lock file written to {}", lock::LOCK_FILE_NAME);
Ok(())
}
}
pub(super) async fn prepare(args: &GenerationOptions) -> Result<Prepared> {
let config = seedkit_core::config::read_config(Path::new("."))?;
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.cyan} [{prefix}] {msg}")
.unwrap(),
);
pb.set_prefix("1/4");
pb.set_message("Introspecting schema...");
pb.enable_steady_tick(std::time::Duration::from_millis(100));
let (db_url, mut schema) = super::database::introspect(
args.db.as_deref(),
args.schema.as_deref(),
config.as_ref(),
&args.schema_file,
)
.await?;
pb.finish_with_message(format!(
"Introspecting schema... ✓ {} tables, {} foreign keys",
schema.table_count(),
schema.foreign_key_count()
));
let flag_tables = [
("--include", args.include.iter().collect::<Vec<_>>()),
("--exclude", args.exclude.iter().collect()),
(
"--table-rows",
args.table_rows.iter().map(|(t, _)| t).collect(),
),
];
for (flag, names) in flag_tables {
if let Some(unknown) = names.into_iter().find(|t| !schema.tables.contains_key(*t)) {
bail!(
"Unknown table '{unknown}' in {flag}. Tables in this schema: {}",
table_list(&schema)
);
}
}
if let (Some(cfg), false) = (&config, args.from_lock) {
for warning in config_warnings(cfg, &schema) {
eprintln!("Warning: {warning}");
}
}
let lock_path = Path::new(lock::LOCK_FILE_NAME);
let restored_lock = if args.from_lock {
if !lock_path.exists() {
bail!(
"No {} found in current directory. Run `seedkit generate` first to create one.",
lock::LOCK_FILE_NAME
);
}
let lf = lock::read_lock_file(lock_path)?;
let current_hash = compute_schema_hash(&schema);
if current_hash != lf.schema_hash && !args.force {
bail!(
"Schema has changed since {} was created.\n\
Lock hash: {:.16}\n\
Current: {:.16}\n\
\n\
Run with --force to regenerate, or delete {} and run fresh.",
lock::LOCK_FILE_NAME,
lf.schema_hash,
current_hash,
lock::LOCK_FILE_NAME,
);
}
Some(lf)
} else {
None
};
let pb2 = ProgressBar::new_spinner();
pb2.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.cyan} [{prefix}] {msg}")
.unwrap(),
);
pb2.set_prefix("2/4");
pb2.set_message("Analyzing dependencies...");
pb2.enable_steady_tick(std::time::Duration::from_millis(100));
let relationships = match &restored_lock {
Some(lf) => lf
.existing_parents
.iter()
.map(|p| p.relationship.clone())
.collect(),
None => config
.as_ref()
.map(|c| c.existing_parents.clone())
.unwrap_or_default(),
};
let original_schema = (!relationships.is_empty()).then(|| schema.clone());
if args.schema_file.schema_file.is_some() && !relationships.is_empty() {
return Err(super::database::needs_database(
"[[existing_parents]] reads parent keys from the database and",
));
}
let external = seedkit_core::generate::existing::detach(&mut schema, &relationships)?;
let mut dep_graph = DependencyGraph::from_schema(&schema);
let cycle_break_hints: Vec<String> = match restored_lock
.as_ref()
.and_then(|lf| lf.config.break_cycle_at.clone())
{
Some(recorded) => recorded,
None => config
.as_ref()
.map(|c| c.graph.break_cycle_at.clone())
.unwrap_or_default(),
};
let deferred = break_cycles(&mut dep_graph, &cycle_break_hints)?;
let insertion_order = topological_sort(&dep_graph)?;
pb2.finish_with_message(format!(
"Analyzing dependencies... ✓ {} circular dependencies resolved",
deferred.len()
));
let introspected = original_schema.as_ref().unwrap_or(&schema);
let rule_classifications = classify_schema(introspected);
let use_ai = args.ai
|| (restored_lock.is_none()
&& config.as_ref().and_then(|c| c.generate.ai).unwrap_or(false));
let (classifications, ai_cache) = if use_ai {
enhance_with_llm(&rule_classifications, introspected, args.model.as_deref()).await?
} else if let Some(ref lf) = restored_lock {
restore_ai_from_lock(&rule_classifications, lf)
} else {
(rule_classifications, None)
};
let (seed, row_count, table_row_overrides, base_time) = if let Some(ref lf) = restored_lock {
let overrides = lf.config.table_row_overrides.clone();
let bt = lf
.parse_base_time()
.context("Invalid base_time in seedkit.lock")?;
(lf.seed, lf.config.default_row_count, overrides, Some(bt))
} else {
let seed = args.seed.unwrap_or_else(|| {
if let Some(ref cfg) = config {
if let Some(s) = cfg.generate.seed {
return s;
}
}
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
});
let mut overrides = config
.as_ref()
.map(|c| c.table_row_overrides())
.unwrap_or_default();
for (k, v) in args.parse_table_rows() {
overrides.insert(k, v);
}
let rows = args
.rows
.or_else(|| config.as_ref().and_then(|c| c.generate.rows))
.unwrap_or(100);
(seed, rows, overrides, None)
};
let (include, exclude) = if let Some(ref lf) = restored_lock {
(
lf.config.include_tables.clone(),
lf.config.exclude_tables.clone(),
)
} else {
(
if args.include.is_empty() {
config
.as_ref()
.and_then(|c| c.generate.include.clone())
.unwrap_or_default()
} else {
args.include.clone()
},
if args.exclude.is_empty() {
config
.as_ref()
.and_then(|c| c.generate.exclude.clone())
.unwrap_or_default()
} else {
args.exclude.clone()
},
)
};
let filtered_order =
filter_insertion_order(&insertion_order.tables, &schema, &include, &exclude);
let column_overrides = match &restored_lock {
Some(lf) => lf
.config
.column_overrides
.iter()
.flatten()
.map(|(name, saved)| (name.clone(), ColumnConfig::from(saved)))
.collect(),
None => config
.as_ref()
.map(|c| c.columns.clone())
.unwrap_or_default(),
};
let scenario = if let Some(lf) = &restored_lock {
lf.scenario.clone()
} else if let Some(name) = &args.scenario {
let definition = config
.as_ref()
.and_then(|c| c.scenarios.get(name))
.with_context(|| format!("Unknown scenario '{name}' in seedkit.toml"))?;
Some(seedkit_core::generate::scenario::NamedScenario {
name: name.clone(),
definition: definition.clone(),
})
} else {
None
};
let locked_subset = restored_lock
.as_ref()
.and_then(|lf| lf.config.subset.as_ref());
let subset_path = args
.subset
.as_deref()
.map(Path::new)
.or_else(|| locked_subset.map(|source| source.path.as_path()));
let (dist_profiles, subset) = if let Some(path) = subset_path {
let (profiles, sha256) = seedkit_core::sample::load_profiles_with_hash(path)
.with_context(|| format!("Loading distribution profile {}", path.display()))?;
if locked_subset.is_some_and(|source| source.sha256 != sha256) {
bail!("Distribution profile {} differs from seedkit.lock. Restore the recorded file or generate a new lock with --subset.", path.display());
}
eprintln!(
"Loaded {} distribution profiles from {}",
profiles.len(),
path.display()
);
let source = seedkit_core::sample::ProfileSource {
path: profile_lock_path(path)?,
sha256,
};
(Some(profiles), Some(source))
} else {
(None, None)
};
let mut plan = GenerationPlan::build(
&schema,
&classifications,
&filtered_order,
deferred,
row_count,
&table_row_overrides,
seed,
base_time,
&column_overrides,
dist_profiles.as_deref(),
);
if let Some(lf) = &restored_lock {
plan.generator_version = lf.generator_version;
}
plan.locale = match &restored_lock {
Some(lf) => lf.config.locale.unwrap_or_default(),
None => args
.locale
.or_else(|| config.as_ref().and_then(|c| c.generate.locale))
.unwrap_or_default(),
};
if let Some(selected) = &scenario {
selected
.definition
.apply(&mut plan, introspected)
.with_context(|| format!("Invalid scenario '{}'", selected.name))?;
}
let parent_locks =
seedkit_core::generate::existing::load(&mut plan, introspected, &external, &db_url).await?;
if let Some(lf) = &restored_lock {
if parent_locks != lf.existing_parents && !args.force {
bail!("Existing parent keys have changed since seedkit.lock was written. Run with --force to use the current keys.");
}
}
let lock_config = LockConfig {
subset,
default_row_count: row_count,
table_row_overrides,
ai_enabled: use_ai
|| restored_lock
.as_ref()
.is_some_and(|lf| lf.config.ai_enabled),
include_tables: include,
exclude_tables: exclude,
break_cycle_at: Some(cycle_break_hints),
locale: (plan.locale != Default::default()).then_some(plan.locale),
ai_classifications: ai_cache,
column_overrides: if column_overrides.is_empty() {
None
} else {
Some(
column_overrides
.iter()
.filter_map(|(k, cfg)| {
seedkit_core::lock::types::ColumnOverrideLock::capture(cfg)
.map(|saved| (k.clone(), saved))
})
.collect(),
)
},
};
Ok(Prepared {
plan,
schema,
db_url,
original_schema,
parent_locks,
lock_config,
scenario,
})
}
fn table_list(schema: &DatabaseSchema) -> String {
let mut names: Vec<&str> = schema.tables.keys().map(String::as_str).collect();
names.sort_unstable();
names.join(", ")
}
fn config_warnings(
config: &seedkit_core::config::SeedKitConfig,
schema: &DatabaseSchema,
) -> Vec<String> {
let missing = |table: &String| !schema.tables.contains_key(table);
let generate = &config.generate;
let listed = [
("include", generate.include.iter().flatten()),
("exclude", generate.exclude.iter().flatten()),
];
let mut warnings: Vec<String> = listed
.into_iter()
.flat_map(|(key, names)| {
names.filter(|t| missing(t)).map(move |t| {
format!(
"seedkit.toml: [generate] {key} names table '{t}', which is not in this schema"
)
})
})
.collect();
warnings.extend(
config
.tables
.keys()
.filter(|t| missing(t))
.map(|t| format!("seedkit.toml: [tables.{t}] does not match a table in this schema")),
);
warnings.extend(config.validate_against_schema(schema));
warnings
}
fn profile_lock_path(path: &Path) -> Result<std::path::PathBuf> {
if path.is_absolute() {
let dir = std::env::current_dir()?;
for (levels, ancestor) in dir.ancestors().enumerate() {
if let Ok(suffix) = path.strip_prefix(ancestor) {
let mut relative = std::path::PathBuf::new();
relative.extend(std::iter::repeat_n("..", levels));
return Ok(relative.join(suffix));
}
}
}
Ok(path.to_owned())
}
pub async fn run(args: &GenerateArgs) -> Result<()> {
if args.output.as_deref() == Some("direct") && args.options.schema_file.schema_file.is_some() {
return Err(super::database::needs_database("--output direct"));
}
let csv_dir = args.csv_directory();
if let Some(dir) = csv_dir {
if !matches!(args.format, Some(OutputFormat::Csv)) {
bail!(
"--output {} is a directory. Add --format csv to write one CSV file per table.",
dir.display()
);
}
}
let prepared = prepare(&args.options).await?;
let (plan, schema, db_url) = (&prepared.plan, &prepared.schema, prepared.db_url());
let total_rows: usize = plan.table_plans.iter().map(|t| t.row_count).sum();
let pb3 = ProgressBar::new(total_rows as u64);
pb3.set_style(
ProgressStyle::default_bar()
.template(
"{spinner:.cyan} [3/4] Generating data... {bar:40.cyan/dim} {pos}/{len} ({eta})",
)
.unwrap()
.progress_chars("█▓░"),
);
let data = engine::execute_plan(
plan,
schema,
Some(&|_table, current, _total| {
pb3.set_position(current as u64);
}),
)?;
pb3.finish_with_message(format!("Generating data... ✓ ({} rows)", total_rows));
let is_direct = args.output.as_deref() == Some("direct");
if args.copy
&& (is_direct
|| schema.database_type != DatabaseType::PostgreSQL
|| !matches!(args.output_format(), OutputFormat::Sql))
{
eprintln!("Warning: --copy applies only to PostgreSQL SQL output; ignoring it");
}
if is_direct {
let pb4 = ProgressBar::new(total_rows as u64);
pb4.set_style(
ProgressStyle::default_bar()
.template("{spinner:.cyan} [4/4] Inserting into database... {bar:40.cyan/dim} {pos}/{len} ({eta})")
.unwrap()
.progress_chars("█▓░"),
);
output::direct::insert_direct_with_offset(
&data,
schema,
db_url,
plan.sequence_offset,
Some(&|current, _total| {
pb4.set_position(current as u64);
}),
)
.await?;
pb4.finish_with_message(format!(
"Inserting into database... ✓ ({} rows)",
total_rows
));
eprintln!(
"\n✓ Inserted {} rows across {} tables into {}",
total_rows,
data.tables.len(),
schema.database_type,
);
} else {
let pb4 = ProgressBar::new_spinner();
pb4.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.cyan} [4/4] {msg}")
.unwrap(),
);
pb4.set_prefix("4/4");
match &args.output {
Some(path) if csv_dir.is_some() => {
pb4.set_message(format!("Writing to {}...", path));
let files = output::csv::write_csv_dir(Path::new(path), &data)?;
pb4.finish_with_message(format!("Writing to {}... ✓", path));
eprintln!(
"\n✓ Generated {} rows across {} tables → {} files in {}",
total_rows,
data.tables.len(),
files.len(),
path
);
}
Some(path) => {
pb4.set_message(format!("Writing to {}...", path));
let file = File::create(path)
.with_context(|| format!("Failed to create output file: {}", path))?;
let mut writer = BufWriter::new(file);
write_output(&mut writer, args, &data, schema)?;
pb4.finish_with_message(format!("Writing to {}... ✓", path));
eprintln!(
"\n✓ Generated {} rows across {} tables → {}",
total_rows,
data.tables.len(),
path
);
}
None => {
pb4.set_message("Writing to stdout...");
let stdout = std::io::stdout();
let mut writer = BufWriter::new(stdout.lock());
write_output(&mut writer, args, &data, schema)?;
pb4.finish_with_message("Writing to stdout... ✓");
}
}
}
prepared.write_lock()?;
Ok(())
}
async fn enhance_with_llm(
rule_classifications: &BTreeMap<(String, String), SemanticType>,
schema: &DatabaseSchema,
model_override: Option<&str>,
) -> Result<(
BTreeMap<(String, String), SemanticType>,
Option<BTreeMap<String, BTreeMap<String, SemanticType>>>,
)> {
let provider = llm::client::LlmProvider::from_env(model_override)
.context("--ai flag requires an LLM API key")?;
let targets: Vec<ClassificationTarget> = rule_classifications
.iter()
.filter(|(_, semantic)| **semantic == SemanticType::Unknown)
.filter_map(|((table, column), _)| {
let col = schema.tables.get(table)?.columns.get(column)?;
(!col.is_generated).then(|| ClassificationTarget::new(table, column, &col.raw_type))
})
.collect();
if targets.is_empty() {
eprintln!("Every column already has a semantic type; skipping LLM classification");
return Ok((rule_classifications.clone(), None));
}
let requested: String = targets
.iter()
.map(|t| format!("{}.{}\n", t.table, t.column))
.collect();
let cache_key = provider.cache_key(&format!("{}\n{requested}", compute_schema_hash(schema)));
let response = if let Some(cached) = llm::client::load_cached_response(&cache_key) {
eprintln!("Using cached LLM classification (schema unchanged)");
cached
} else {
eprintln!(
"Asking {} to classify {} columns...",
provider.model(),
targets.len()
);
let ddl = llm::prompt::schema_to_compact_ddl(schema);
let provider = &provider;
let resp = llm::classify::classify_columns(&ddl, &targets, |prompt| async move {
provider.classify(&prompt).await
})
.await
.context("LLM classification request failed")?;
llm::client::save_cached_response(&cache_key, &resp);
resp
};
let merged = llm::parse::merge_classifications(rule_classifications, &response);
let cache = llm::parse::build_ai_classification_cache(rule_classifications, &merged);
let ai_cache = if cache.is_empty() { None } else { Some(cache) };
Ok((merged, ai_cache))
}
#[allow(clippy::type_complexity)]
fn restore_ai_from_lock(
rule_classifications: &BTreeMap<(String, String), SemanticType>,
lock_file: &LockFile,
) -> (
BTreeMap<(String, String), SemanticType>,
Option<BTreeMap<String, BTreeMap<String, SemanticType>>>,
) {
let mut merged = rule_classifications.clone();
if let Some(ref ai_cache) = lock_file.config.ai_classifications {
for (table, columns) in ai_cache {
for (column, semantic_type) in columns {
let key = (table.clone(), column.clone());
if merged.get(&key).copied().unwrap_or(SemanticType::Unknown)
== SemanticType::Unknown
{
merged.insert(key, *semantic_type);
}
}
}
}
(merged, lock_file.config.ai_classifications.clone())
}
fn write_output<W: Write>(
writer: &mut W,
args: &GenerateArgs,
data: &engine::GeneratedData,
schema: &DatabaseSchema,
) -> seedkit_core::error::Result<()> {
match args.output_format() {
OutputFormat::Sql if args.copy && schema.database_type == DatabaseType::PostgreSQL => {
output::sql::write_postgres_copy(writer, data, schema)
}
OutputFormat::Sql => output::sql::write_sql(writer, data, schema),
OutputFormat::Json => output::json::write_json(writer, data),
OutputFormat::Csv => output::csv::write_csv(writer, data),
}
}
#[cfg(test)]
mod output_tests {
use super::*;
use clap::Parser;
use seedkit_core::generate::value::Value;
#[test]
fn copy_to_stdout_emits_default_inserts_and_copy_blocks() {
let args = GenerateArgs::parse_from(["seedkit", "--copy"]);
let data = engine::GeneratedData {
tables: [
("roles".into(), vec![Default::default()]),
(
"members".into(),
vec![[("role_id".into(), Value::Int(1))].into_iter().collect()],
),
]
.into_iter()
.collect(),
deferred_updates: vec![],
};
let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".into());
let mut output = Vec::new();
write_output(&mut output, &args, &data, &schema).unwrap();
let sql = String::from_utf8(output).unwrap();
assert!(sql.contains("INSERT INTO \"roles\" DEFAULT VALUES;"));
assert!(sql.contains("COPY \"members\" (\"role_id\") FROM stdin;"));
}
}