seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
pub mod csv;
pub mod direct;
pub mod json;
pub mod sql;

use crate::error::{Result, SeedKitError};

/// Names what was being written when an export write fails.
pub(crate) trait WriteResultExt<T> {
    fn context(self, what: &str) -> Result<T>;
    /// Like `context`, but only formats the message when the write fails.
    fn with_context(self, what: impl FnOnce() -> String) -> Result<T>;
}

impl<T> WriteResultExt<T> for std::io::Result<T> {
    fn context(self, what: &str) -> Result<T> {
        self.with_context(|| what.to_owned())
    }

    fn with_context(self, what: impl FnOnce() -> String) -> Result<T> {
        self.map_err(|source| SeedKitError::Output {
            message: what(),
            source,
        })
    }
}

#[cfg(test)]
mod tests {
    use std::io::{self, Write};

    use indexmap::IndexMap;

    use crate::error::SeedKitError;
    use crate::generate::engine::GeneratedData;
    use crate::generate::value::Value;
    use crate::schema::types::{DatabaseSchema, DatabaseType};

    /// Accepts `budget` bytes, then fails every write like a full disk.
    struct FullDisk {
        budget: usize,
    }

    impl Write for FullDisk {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if self.budget == 0 {
                return Err(io::Error::new(io::ErrorKind::StorageFull, "disk full"));
            }
            let n = buf.len().min(self.budget);
            self.budget -= n;
            Ok(n)
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    fn one_user() -> GeneratedData {
        let row = IndexMap::from([("email".to_string(), Value::String("a@b.c".into()))]);
        GeneratedData {
            tables: IndexMap::from([("users".to_string(), vec![row])]),
            deferred_updates: Vec::new(),
        }
    }

    fn assert_output_error(result: crate::error::Result<()>, context: &str) {
        match result {
            Err(SeedKitError::Output { message, source }) => {
                assert!(message.contains(context), "{message}");
                assert_eq!(source.kind(), io::ErrorKind::StorageFull);
            }
            other => panic!("expected an output error, got {other:?}"),
        }
    }

    #[test]
    fn failed_writes_report_what_was_being_written() {
        let data = one_user();
        let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "app".into());
        // Fail just past the 42-byte SQL header, inside the users table.
        assert_output_error(
            super::sql::write_sql(&mut FullDisk { budget: 50 }, &data, &schema),
            "users",
        );
        assert_output_error(
            super::sql::write_postgres_copy(&mut FullDisk { budget: 60 }, &data, &schema),
            "users",
        );
        assert_output_error(
            super::csv::write_csv(&mut FullDisk { budget: 0 }, &data),
            "users",
        );
        assert_output_error(
            super::json::write_json(&mut FullDisk { budget: 0 }, &data),
            "JSON",
        );
    }
}