seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};

use super::WriteResultExt;
use crate::error::{Result, SeedKitError};
use crate::generate::engine::GeneratedData;
use crate::generate::value::Value;

/// Write generated data as CSV files (one section per table).
/// Tables are separated by a comment header line.
pub fn write_csv<W: Write>(writer: &mut W, data: &GeneratedData) -> Result<()> {
    for (table_name, rows) in &data.tables {
        if rows.is_empty() {
            continue;
        }

        // Table header
        writeln!(writer, "# Table: {}", table_name)
            .with_context(|| format!("writing CSV header for {}", table_name))?;

        // Column headers
        let columns: Vec<&String> = rows[0].keys().collect();
        writeln!(
            writer,
            "{}",
            columns
                .iter()
                .map(|c| csv_escape(c))
                .collect::<Vec<_>>()
                .join(",")
        )
        .with_context(|| format!("writing CSV columns for {}", table_name))?;

        // Data rows
        for row in rows {
            let values: Vec<String> = columns
                .iter()
                .map(|col| {
                    row.get(*col)
                        .map(|v| csv_escape(&v.to_csv_string()))
                        .unwrap_or_default()
                })
                .collect();

            writeln!(writer, "{}", values.join(","))
                .with_context(|| format!("writing CSV row for {}", table_name))?;
        }

        writeln!(writer).context("writing newline")?;
    }

    Ok(())
}

/// Write CSV for a single table to a writer.
pub fn write_csv_table<W: Write>(
    writer: &mut W,
    table_name: &str,
    rows: &[indexmap::IndexMap<String, Value>],
) -> Result<()> {
    if rows.is_empty() {
        return Ok(());
    }

    let columns: Vec<&String> = rows[0].keys().collect();
    writeln!(
        writer,
        "{}",
        columns
            .iter()
            .map(|c| csv_escape(c))
            .collect::<Vec<_>>()
            .join(",")
    )
    .with_context(|| format!("writing CSV columns for {}", table_name))?;

    for row in rows {
        let values: Vec<String> = columns
            .iter()
            .map(|col| {
                row.get(*col)
                    .map(|v| csv_escape(&v.to_csv_string()))
                    .unwrap_or_default()
            })
            .collect();

        writeln!(writer, "{}", values.join(","))
            .with_context(|| format!("writing CSV row for {}", table_name))?;
    }

    Ok(())
}

/// Write one CSV file per table into `dir`, plus `_deferred_updates.csv`
/// when cycle resolution left foreign keys to set after the inserts.
///
/// Each file has a header row and no comment lines, so loaders such as
/// `\copy … CSV HEADER`, `LOAD DATA`, and spreadsheets read it directly.
/// Tables without rows get no file. Returns the paths written.
pub fn write_csv_dir(dir: &Path, data: &GeneratedData) -> Result<Vec<PathBuf>> {
    std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    // File name -> the table that claimed it.
    let mut claimed: HashMap<String, String> = HashMap::new();
    let mut written = Vec::new();
    let mut create = |name: &str| -> Result<(PathBuf, BufWriter<File>)> {
        let file = file_name(name);
        if let Some(other) = claimed.get(&file) {
            return Err(SeedKitError::Other(format!(
                "Tables '{other}' and '{name}' would both be written to {file}"
            )));
        }
        let path = dir.join(&file);
        let handle = File::create(&path).with_context(|| format!("creating {}", path.display()))?;
        claimed.insert(file, name.to_owned());
        Ok((path, BufWriter::new(handle)))
    };

    for (table_name, rows) in data.tables.iter().filter(|(_, rows)| !rows.is_empty()) {
        let (path, mut writer) = create(table_name)?;
        write_csv_table(&mut writer, table_name, rows)?;
        writer
            .flush()
            .with_context(|| format!("writing {}", path.display()))?;
        written.push(path);
    }

    if !data.deferred_updates.is_empty() {
        let (path, mut writer) = create("_deferred_updates")?;
        writeln!(writer, "table,row_index,column,value").context("writing deferred updates")?;
        for update in &data.deferred_updates {
            writeln!(
                writer,
                "{},{},{},{}",
                csv_escape(&update.table_name),
                update.row_index,
                csv_escape(&update.column_name),
                csv_escape(&update.value.to_csv_string())
            )
            .context("writing deferred updates")?;
        }
        writer
            .flush()
            .with_context(|| format!("writing {}", path.display()))?;
        written.push(path);
    }
    Ok(written)
}

/// A table's CSV file name, restricted to characters that are safe in a path
/// so a name such as `../x` stays inside the output directory.
fn file_name(table: &str) -> String {
    let stem: String = table
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
                c
            } else {
                '_'
            }
        })
        .collect();
    format!("{stem}.csv")
}

/// Escape a string for CSV: quote if it contains comma, quote, or newline.
fn csv_escape(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_csv_escape() {
        assert_eq!(csv_escape("hello"), "hello");
        assert_eq!(csv_escape("hello,world"), "\"hello,world\"");
        assert_eq!(csv_escape("say \"hi\""), "\"say \"\"hi\"\"\"");
    }

    use crate::generate::engine::DeferredUpdate;
    use indexmap::IndexMap;

    fn row(pairs: &[(&str, Value)]) -> IndexMap<String, Value> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect()
    }

    fn files(dir: &std::path::Path) -> Vec<(String, String)> {
        let mut found: Vec<_> = std::fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().path())
            .map(|p| {
                let name = p.file_name().unwrap().to_string_lossy().into_owned();
                (name, std::fs::read_to_string(&p).unwrap())
            })
            .collect();
        found.sort();
        found
    }

    #[test]
    fn directory_output_writes_one_plain_csv_per_table() {
        let data = GeneratedData {
            tables: IndexMap::from([
                (
                    "users".to_string(),
                    vec![row(&[("email", Value::String("a@b.c".into()))])],
                ),
                (
                    "employees".to_string(),
                    vec![row(&[
                        ("name", Value::String("Ada, PhD".into())),
                        ("manager_id", Value::Null),
                    ])],
                ),
                ("empty".to_string(), vec![]),
            ]),
            deferred_updates: vec![DeferredUpdate {
                table_name: "employees".to_string(),
                row_index: 0,
                column_name: "manager_id".to_string(),
                value: Value::Int(1),
            }],
        };
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("seed");
        let written = write_csv_dir(&out, &data).unwrap();
        assert_eq!(written.len(), 3);
        assert_eq!(
            files(&out),
            [
                (
                    "_deferred_updates.csv".to_string(),
                    "table,row_index,column,value\nemployees,0,manager_id,1\n".to_string()
                ),
                (
                    "employees.csv".to_string(),
                    "name,manager_id\n\"Ada, PhD\",\n".to_string()
                ),
                ("users.csv".to_string(), "email\na@b.c\n".to_string()),
            ]
        );
    }

    #[test]
    fn directory_output_keeps_table_names_inside_the_directory() {
        let one = |name: &str| (name.to_string(), vec![row(&[("x", Value::Int(1))])]);
        let data = GeneratedData {
            tables: IndexMap::from([one("../escape"), one("Weird Name")]),
            deferred_updates: Vec::new(),
        };
        let dir = tempfile::tempdir().unwrap();
        write_csv_dir(dir.path(), &data).unwrap();
        let names: Vec<_> = files(dir.path()).into_iter().map(|(n, _)| n).collect();
        assert_eq!(names, ["Weird_Name.csv", "___escape.csv"]);

        // Two tables must never overwrite each other's file.
        let clash = GeneratedData {
            tables: IndexMap::from([one("a b"), one("a_b")]),
            deferred_updates: Vec::new(),
        };
        let err = write_csv_dir(&dir.path().join("clash"), &clash).unwrap_err();
        assert!(err.to_string().contains("a_b.csv"), "{err}");
    }
}