seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
//! Deterministic, opt-in key pools for references to rows already in the database.

use std::collections::BTreeSet;

use anyhow::{bail, ensure, Context, Result};
use rand::{rngs::StdRng, seq::SliceRandom, SeedableRng};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sqlx::{AnyConnection, Connection, Row};

use crate::generate::plan::{GenerationPlan, GenerationStrategy};
use crate::generate::value::Value;
use crate::schema::types::{DataType, DatabaseSchema, DatabaseType, ForeignKey};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExistingParent {
    pub table: String,
    pub columns: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LockedParent {
    pub relationship: ExistingParent,
    /// None when the relationship's child table has no rows in this plan.
    pub fingerprint: Option<String>,
}

/// External references impose no insert dependency. Removing only these edges
/// from the working schema also prevents direct insertion from translating a
/// real database ID through a different relationship's logical-ID map.
pub fn detach(
    schema: &mut DatabaseSchema,
    specs: &[ExistingParent],
) -> Result<Vec<(ExistingParent, ForeignKey)>> {
    let mut external = Vec::new();
    for spec in specs {
        let table = schema
            .tables
            .get_mut(&spec.table)
            .with_context(|| format!("Unknown existing_parents table {}", spec.table))?;
        let mut matches = table
            .foreign_keys
            .iter()
            .enumerate()
            .filter(|(_, fk)| fk.source_columns == spec.columns);
        let (index, fk) = matches.next().with_context(|| {
            format!(
                "No foreign key {}.({}) for existing_parents",
                spec.table,
                spec.columns.join(", ")
            )
        })?;
        ensure!(
            matches.next().is_none(),
            "Ambiguous existing_parents relationship on {}.({})",
            spec.table,
            spec.columns.join(", ")
        );
        ensure!(
            !fk.source_columns.is_empty() && fk.source_columns.len() == fk.referenced_columns.len(),
            "Invalid foreign key on {}",
            spec.table
        );
        ensure!(
            !table
                .foreign_keys
                .iter()
                .enumerate()
                .any(|(i, other)| i != index
                    && other
                        .source_columns
                        .iter()
                        .any(|c| spec.columns.contains(c))),
            "Overlapping foreign keys cannot have independent existing_parents sources on {}.({})",
            spec.table,
            spec.columns.join(", ")
        );
        external.push((spec.clone(), table.foreign_keys.remove(index)));
    }
    Ok(external)
}

pub async fn load(
    plan: &mut GenerationPlan,
    schema: &DatabaseSchema,
    external: &[(ExistingParent, ForeignKey)],
    db_url: &str,
) -> Result<Vec<LockedParent>> {
    let mut connection = None;
    let mut locks = Vec::new();
    for (spec, fk) in external {
        let mut locked = LockedParent {
            relationship: spec.clone(),
            fingerprint: None,
        };
        if let Some(child) = plan
            .table_plans
            .iter_mut()
            .find(|t| t.table_name == spec.table && t.row_count > 0)
        {
            if connection.is_none() {
                sqlx::any::install_default_drivers();
                connection = Some(
                    AnyConnection::connect(db_url)
                        .await
                        .context("Opening existing parent key pool")?,
                );
            }
            let (mut tuples, fingerprint) =
                read_keys(connection.as_mut().unwrap(), schema, spec, fk).await?;
            ensure!(
                !tuples.is_empty(),
                "No existing parent keys in {}.({}) for {}.({})",
                fk.target_name(),
                fk.referenced_columns.join(", "),
                spec.table,
                spec.columns.join(", ")
            );
            locked.fingerprint = Some(fingerprint);
            let mut domain = Sha256::new();
            domain.update(plan.seed.to_le_bytes());
            domain.update(serde_json::to_vec(spec)?);
            tuples.shuffle(&mut StdRng::from_seed(domain.finalize().into()));

            // A unique source projection may require distinct values even when
            // several complete parent tuples share that projection.
            let table = &schema.tables[&spec.table];
            let projections: Vec<Vec<usize>> = table
                .unique_constraints
                .iter()
                .map(|u| &u.columns)
                .chain(table.primary_key.iter().map(|p| &p.columns))
                .filter_map(|cols| {
                    cols.iter()
                        .map(|c| spec.columns.iter().position(|s| s == c))
                        .collect()
                })
                .collect();
            if !projections.is_empty() {
                let mut seen = vec![BTreeSet::new(); projections.len()];
                tuples.retain(|tuple| {
                    let keys: Vec<Vec<String>> = projections
                        .iter()
                        .map(|p| p.iter().map(|&i| tuple[i].to_unique_key()).collect())
                        .collect();
                    if keys.iter().zip(&seen).any(|(k, s)| s.contains(k)) {
                        return false;
                    }
                    for (k, s) in keys.into_iter().zip(&mut seen) {
                        s.insert(k);
                    }
                    true
                });
                ensure!(
                    tuples.len() >= child.row_count,
                    "Too few distinct existing parent keys for {}.({}): {} for {} rows",
                    spec.table,
                    spec.columns.join(", "),
                    tuples.len(),
                    child.row_count
                );
            }
            for (index, name) in spec.columns.iter().enumerate() {
                let column = child
                    .column_plans
                    .iter_mut()
                    .find(|c| &c.column_name == name)
                    .with_context(|| {
                        format!("Missing existing_parents column {}.{name}", spec.table)
                    })?;
                ensure!(
                    !matches!(
                        column.strategy,
                        GenerationStrategy::ValueList { .. }
                            | GenerationStrategy::Pattern(_)
                            | GenerationStrategy::Range { .. }
                    ),
                    "Conflicting column override and existing_parents for {}.{name}",
                    spec.table
                );
                column.strategy = GenerationStrategy::ReferenceKeys(
                    tuples.iter().map(|tuple| tuple[index].clone()).collect(),
                );
                column.null_probability = 0.0;
            }
        }
        locks.push(locked);
    }
    Ok(locks)
}

async fn read_keys(
    connection: &mut AnyConnection,
    schema: &DatabaseSchema,
    spec: &ExistingParent,
    fk: &ForeignKey,
) -> Result<(Vec<Vec<Value>>, String)> {
    let db = schema.database_type;
    let (quoted_target, key_table, key_columns) = if let Some(namespace) = &fk.referenced_schema {
        // The target is outside the write scope. Decode its keys for the corresponding
        // child columns, preserving the catalog's component order for composite FKs.
        let target = format!(
            "{}.{}",
            db.quote_identifier(namespace),
            db.quote_identifier(&fk.referenced_table)
        );
        (target, &schema.tables[&spec.table], &fk.source_columns)
    } else {
        let target = schema
            .tables
            .get(&fk.referenced_table)
            .context("Unknown existing parent table")?;
        (
            schema.quoted_table(&target.name),
            target,
            &fk.referenced_columns,
        )
    };
    let mut expressions = Vec::new();
    let mut present = Vec::new();
    let mut types = Vec::new();
    for (name, key) in fk.referenced_columns.iter().zip(key_columns) {
        let column = key_table
            .columns
            .get(key)
            .with_context(|| format!("Unknown key column {}.{key}", key_table.name))?;
        let quoted = db.quote_identifier(name);
        expressions.push(match (&column.data_type, db) {
            (DataType::Binary, DatabaseType::PostgreSQL) => format!("encode({quoted}, 'hex')"),
            (DataType::Binary, _) => format!("HEX({quoted})"),
            (_, DatabaseType::MySQL) => format!("CAST({quoted} AS CHAR)"),
            _ => format!("CAST({quoted} AS TEXT)"),
        });
        present.push(format!("{quoted} IS NOT NULL"));
        types.push(&column.data_type);
    }
    let sql = format!(
        "SELECT {} FROM {} WHERE {}",
        expressions.join(", "),
        quoted_target,
        present.join(" AND ")
    );
    let mut raw: Vec<Vec<String>> = sqlx::query(&sql)
        .fetch_all(connection)
        .await
        .with_context(|| format!("Reading existing parent keys from {quoted_target}"))?
        .iter()
        .map(|row| {
            (0..types.len())
                .map(|i| row.try_get::<String, _>(i))
                .collect()
        })
        .collect::<Result<_, sqlx::Error>>()?;
    // Database collations may disagree about ordering. Use the same ordering
    // for the fingerprint and seeded selection across connections and exports.
    raw.sort_unstable();
    let mut fingerprint = Sha256::new();
    let mut tuples = Vec::with_capacity(raw.len());
    for row in raw {
        let mut tuple = Vec::with_capacity(row.len());
        for (s, ty) in row.into_iter().zip(&types) {
            fingerprint.update((s.len() as u64).to_le_bytes());
            fingerprint.update(s.as_bytes());
            tuple.push(decode(s, ty)?);
        }
        tuples.push(tuple);
    }
    Ok((tuples, format!("{:x}", fingerprint.finalize())))
}

fn decode(s: String, ty: &DataType) -> Result<Value> {
    Ok(match ty {
        DataType::SmallInt
        | DataType::Integer
        | DataType::BigInt
        | DataType::Serial
        | DataType::BigSerial => s
            .parse()
            .map(Value::Int)
            .unwrap_or_else(|_| Value::String(s.into())),
        DataType::Boolean => match s.as_str() {
            "true" | "t" | "1" => Value::Bool(true),
            "false" | "f" | "0" => Value::Bool(false),
            _ => bail!("Unrecognized boolean in existing parent key"),
        },
        DataType::Float | DataType::Double => {
            Value::Float(s.parse().context("Invalid floating-point parent key")?)
        }
        DataType::Binary => {
            ensure!(
                s.len().is_multiple_of(2) && s.bytes().all(|c| c.is_ascii_hexdigit()),
                "Invalid binary parent key"
            );
            Value::Bytes(
                (0..s.len())
                    .step_by(2)
                    .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
                    .collect::<Result<_, _>>()?,
            )
        }
        _ => Value::String(s.into()),
    })
}