seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
//! Storage-type fallback for columns without a semantic classification.

use rand::Rng;

use crate::generate::value::Value;
use crate::schema::types::{Column, DataType, ParsedCheck};

#[derive(Debug, Clone)]
pub enum NumericFallback {
    Integer { min: i64, max: i64 },
    Decimal { max_units: i64, scale: i32 },
    Real { single_precision: bool },
}

impl NumericFallback {
    pub fn for_column(col: &Column) -> Option<Self> {
        use DataType::*;
        let (min, max) = match col.data_type {
            SmallInt if col.raw_type.eq_ignore_ascii_case("tinyint") => {
                (i8::MIN.into(), i8::MAX.into())
            }
            SmallInt => (i16::MIN.into(), i16::MAX.into()),
            Integer | Serial => (i32::MIN.into(), i32::MAX.into()),
            BigInt | BigSerial => (i64::MIN, i64::MAX),
            Float | Double => {
                return Some(Self::Real {
                    single_precision: col.data_type == Float,
                })
            }
            Numeric | Money => {
                // Four fractional digits normally suffice. For e.g. NUMERIC(2,6)
                // retain the leading fractional zeroes and both significant digits.
                let precision = col.numeric_precision.unwrap_or(15) as i32;
                let declared_scale = col.numeric_scale.unwrap_or(2) as i32;
                let whole_digits = precision - declared_scale;
                let scale = declared_scale.min(4 + (-whole_digits).max(0));
                let digits = (whole_digits + scale).clamp(0, 15) as u32;
                return Some(Self::Decimal {
                    max_units: 10_i64.pow(digits) - 1,
                    scale,
                });
            }
            _ => return None,
        };
        Some(Self::Integer { min, max })
    }

    pub fn sample(&self, rng: &mut impl Rng, checks: &[ParsedCheck]) -> Option<Value> {
        let (mut low, mut high) = (f64::NEG_INFINITY, f64::INFINITY);
        for check in checks {
            match check {
                ParsedCheck::GreaterThanOrEqual { value, .. } => low = low.max(*value),
                ParsedCheck::GreaterThan { value, .. } => low = low.max(value.next_up()),
                ParsedCheck::LessThanOrEqual { value, .. } => high = high.min(*value),
                ParsedCheck::LessThan { value, .. } => high = high.min(value.next_down()),
                ParsedCheck::Between {
                    low: a, high: b, ..
                } => {
                    low = low.max(*a);
                    high = high.min(*b);
                }
                _ => {}
            }
        }
        match *self {
            Self::Integer { min, max } => {
                let (a, b) = window(low.ceil().max(min as f64), high.floor().min(max as f64))?;
                Some(Value::Int(rng.random_range((a as i64)..=(b as i64))))
            }
            Self::Decimal { max_units, scale } => {
                let factor = 10_f64.powi(scale);
                if !factor.is_finite() || factor == 0.0 {
                    return (low <= 0.0 && high >= 0.0).then_some(Value::Float(0.0));
                }
                let mut a = ((low * factor).ceil() as i64).max(-max_units);
                let mut b = ((high * factor).floor() as i64).min(max_units);
                // Multiplication can round a strict endpoint onto an integer tick.
                if (a as f64) / factor < low {
                    a = a.saturating_add(1);
                }
                if (b as f64) / factor > high {
                    b = b.saturating_sub(1);
                }
                let (a, b) = window(a as f64, b as f64)?;
                Some(Value::Float(
                    rng.random_range((a as i64)..=(b as i64)) as f64 / factor,
                ))
            }
            Self::Real { single_precision } => {
                let (a, b) = window(low, high)?;
                if single_precision {
                    let mut start = a as f32;
                    let mut end = b as f32;
                    if f64::from(start) < a {
                        start = start.next_up();
                    }
                    if f64::from(end) > b {
                        end = end.next_down();
                    }
                    if !start.is_finite() || !end.is_finite() || start > end {
                        return None;
                    }
                    Some(Value::Float(f64::from(rng.random_range(start..=end))))
                } else {
                    Some(Value::Float(rng.random_range(a..=b)))
                }
            }
        }
    }
}

/// Prefer modest nonnegative values. When a CHECK requires another interval,
/// sample near its closest endpoint without widening the legal range.
fn window(low: f64, high: f64) -> Option<(f64, f64)> {
    if low > high {
        return None;
    }
    let start = 0.0_f64.clamp(low, high);
    if high < 0.0 {
        Some(((high - 10_000.0).max(low), high))
    } else {
        Some((start, (start + 10_000.0).min(high)))
    }
}