seedkit 2.1.1

Generate realistic, constraint-safe seed data for PostgreSQL, MySQL, and SQLite
//! `seedkit reset`: empty the generated tables and reseed them.

use std::io::{IsTerminal, Write};

use anyhow::{bail, Result};

use seedkit_core::generate::engine;
use seedkit_core::output;
use seedkit_core::schema::types::DatabaseSchema;

use crate::args::ResetArgs;

pub async fn run(args: &ResetArgs) -> Result<()> {
    if args.options.schema_file.schema_file.is_some() {
        return Err(super::database::needs_database("seedkit reset"));
    }
    let prepared = super::generate::prepare(&args.options).await?;
    let tables: Vec<String> = prepared
        .plan
        .table_plans
        .iter()
        .map(|t| t.table_name.clone())
        .collect();
    if tables.is_empty() {
        bail!("No tables to reset.");
    }
    refuse_outside_references(prepared.introspected(), &tables)?;
    confirm(&tables, args.yes)?;

    let data = engine::execute_plan(&prepared.plan, &prepared.schema, None)?;
    let rows: usize = data.tables.values().map(Vec::len).sum();
    output::direct::replace_direct(
        &data,
        &prepared.schema,
        prepared.db_url(),
        &tables,
        prepared.plan.sequence_offset,
        None,
    )
    .await?;
    eprintln!("✓ Reset {} tables with {rows} rows", tables.len());
    prepared.write_lock()
}

/// Deleting rows that a table outside the reset references would fail, or
/// worse, cascade into that table. Stop before touching anything.
fn refuse_outside_references(schema: &DatabaseSchema, tables: &[String]) -> Result<()> {
    let mut references = Vec::new();
    for (name, table) in &schema.tables {
        if tables.contains(name) {
            continue;
        }
        for fk in table.local_foreign_keys() {
            if tables.contains(&fk.referenced_table) {
                references.push(format!(
                    "{name}.{} references {}",
                    fk.source_columns.join(", "),
                    fk.referenced_table
                ));
            }
        }
    }
    if !references.is_empty() {
        bail!(
            "seedkit reset would delete rows that tables outside the reset reference:\n  {}\n\
             Include those tables in the reset, or exclude the tables they reference.",
            references.join("\n  ")
        );
    }
    Ok(())
}

fn confirm(tables: &[String], yes: bool) -> Result<()> {
    if yes {
        return Ok(());
    }
    let list = tables.join(", ");
    if !std::io::stdin().is_terminal() {
        bail!(
            "seedkit reset deletes every row in {} tables ({list}) before reseeding them. \
             Pass --yes to confirm.",
            tables.len()
        );
    }
    eprint!(
        "This deletes every row in {} tables and reseeds them:\n  {list}\nContinue? [y/N] ",
        tables.len()
    );
    std::io::stderr().flush()?;
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    if matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
        Ok(())
    } else {
        bail!("Reset cancelled.")
    }
}