sql-values 0.8.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
Documentation
//! `text ~ pattern` answered as PostgreSQL 18 answers it without flags, for every generated
//! pattern the subset `PgRegex` takes, each of which PostgreSQL compiles, and every character's
//! membership of every character class.

#[path = "support/answers.rs"]
#[expect(
    dead_code,
    reason = "every case is a match, so no refusal goes through `Answer::of`"
)]
mod answers;
#[path = "support/containers.rs"]
mod containers;
#[path = "support/exit_slot.rs"]
mod exit_slot;
#[path = "support/postgres.rs"]
mod postgres;

use answers::{Answer, compare, quoted};
use diesel::{RunQueryDsl, dsl::sql, sql_types::Text};
use sql_values::postgres::PgRegex;

static PG18: postgres::Slot = exit_slot::ExitSlot::new();

const PG18_TAG: &str = "18.6";

const CLASSES: [&str; 14] = [
    "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph", "lower", "print", "punct",
    "space", "upper", "word", "xdigit",
];

/// A xorshift generator, so every run draws the same patterns and texts.
struct Draws(u64);

impl Draws {
    fn below(&mut self, bound: usize) -> usize {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        usize::try_from(self.0 % u64::try_from(bound).expect("a small bound"))
            .expect("below a usize bound")
    }

    fn pick<'item>(&mut self, items: &[&'item str]) -> &'item str {
        items[self.below(items.len())]
    }

    /// An alternation of up to three branches, its groups nested `depth` more levels at most.
    fn alternation(&mut self, depth: usize) -> String {
        let branches = 1 + self.below(3);
        (0..branches)
            .map(|_| self.branch(depth))
            .collect::<Vec<_>>()
            .join("|")
    }

    fn branch(&mut self, depth: usize) -> String {
        (0..self.below(5))
            .map(|_| {
                let atom = self.atom(depth);
                let quantifier = self.pick(&[
                    "", "", "", "*", "+", "?", "{2}", "{1,}", "{0,2}", "*?", "+?", "{1,3}?",
                ]);
                atom + quantifier
            })
            .collect()
    }

    fn atom(&mut self, depth: usize) -> String {
        match self.below(if depth == 0 { 4 } else { 5 }) {
            0 => self
                .pick(&["a", "b", "-", "é", "\n", ".", "^", "$"])
                .to_owned(),
            1 => self
                .pick(&[r"\.", r"\*", r"\-", r"\$", "a", "b"])
                .to_owned(),
            2 => self
                .pick(&[
                    "[ab]",
                    "[^a]",
                    "[a-c]",
                    "[-a]",
                    "[a-]",
                    "[^-é]",
                    "[^\n]",
                    "[a^]",
                    "[[:space:]]",
                    "[^[:alpha:]]",
                    "[[:digit:]a-c]",
                    "[[:punct:][:upper:]]",
                    "[^[:space:]/?#]",
                    "[[:word:]-]",
                    "[[]",
                    "[[:lower:]é]",
                ])
                .to_owned(),
            3 => self.pick(&["a", "b", "ab", "ba"]).to_owned(),
            _ => {
                let open = self.pick(&["(", "(?:"]);
                format!("{open}{})", self.alternation(depth - 1))
            }
        }
    }

    /// Characters of the pattern syntax in any order, mostly outside the subset.
    fn soup(&mut self) -> String {
        (0..1 + self.below(8))
            .map(|_| {
                self.pick(&[
                    "a",
                    "b",
                    ".",
                    "^",
                    "$",
                    "(",
                    ")",
                    "|",
                    "*",
                    "+",
                    "?",
                    "{",
                    "}",
                    "[",
                    "]",
                    "-",
                    "\\",
                    ":",
                    ",",
                    "0",
                    "1",
                    "2",
                    "=",
                    "!",
                    "<",
                    "#",
                    "é",
                    "[:alpha:]",
                    "[:space:]",
                    "[.",
                    "[=",
                ])
            })
            .collect()
    }

    fn text(&mut self) -> String {
        (0..self.below(6))
            .map(|_| {
                self.pick(&[
                    "a", "b", "c", "-", ".", "é", "\n", "$", "*", " ", "\u{2000}", "\u{a0}", "A",
                    "1", "_", "\t", "?", "[", "Σ",
                ])
            })
            .collect()
    }
}

/// The query PostgreSQL answers `text ~ pattern` with, and the crate's answer to it.
fn case(regex: &PgRegex, pattern: &str, text: &str) -> (String, Answer) {
    (
        format!("SELECT ({} ~ {})::text", quoted(text), quoted(pattern)),
        Answer::Value(regex.is_match(text).to_string()),
    )
}

/// `cases` extended with `pattern` matched against `texts` drawn texts, when the subset takes it.
fn push_cases(
    cases: &mut Vec<(String, Answer)>,
    draws: &mut Draws,
    pattern: &str,
    texts: usize,
) -> bool {
    let Ok(regex) = PgRegex::new(pattern) else {
        return false;
    };
    for _ in 0..texts {
        let text = draws.text();
        cases.push(case(&regex, pattern, &text));
    }
    true
}

/// The pattern `shape` makes of the largest count up to 255 the subset takes.
fn largest_taken(shape: impl Fn(usize) -> String) -> String {
    (0..=255)
        .rev()
        .map(shape)
        .find(|pattern| PgRegex::new(pattern).is_ok())
        .expect("the subset takes a count of 0")
}

/// The code points from U+0001 on where `member` starts or stops holding.
fn flips(member: impl Fn(char) -> bool) -> Vec<u32> {
    let mut previous = false;
    ('\u{1}'..=char::MAX)
        .filter(|&character| {
            let flipped = member(character) != previous;
            previous ^= flipped;
            flipped
        })
        .map(u32::from)
        .collect()
}

#[test]
fn matches_as_postgresql_does() {
    let mut draws = Draws(0x5eed_1e55_0f0d_d1ce);
    let mut cases = Vec::new();
    for pattern in [
        "^[a-z_][a-z0-9_]*:(read|insert|update|delete)(,[a-z_][a-z0-9_]*:(read|insert|update|delete))*$",
        "(a{255}){37}",
        "a{0,255}?b",
        &format!("{}a{}", "(".repeat(64), ")".repeat(64)),
        "^https://[^[:space:]/?#]+$",
    ] {
        assert!(
            push_cases(&mut cases, &mut draws, pattern, 6),
            "{pattern:?}"
        );
    }
    let low: String = ('\u{100}'..'\u{2f4}').collect();
    let high: String = ('\u{4e00}'..'\u{4e32}').collect();
    let few_high: String = ('\u{4e00}'..'\u{4e05}').collect();
    let every: String = CLASSES.iter().map(|name| format!("[[:{name}:]]")).collect();
    let every_negated: String = CLASSES
        .iter()
        .map(|name| format!("[^[:{name}:]]"))
        .collect();
    for pattern in [
        largest_taken(|count| format!("{low}([^a]{{255}}){{{count}}}")),
        largest_taken(|count| format!("({every}){{{count}}}")),
        largest_taken(|count| format!("({every_negated}){{{count}}}")),
        largest_taken(|count| format!("(([[:alpha:]]){{255}}){{{count}}}")),
        largest_taken(|count| format!("{high}([^[:alpha:][:space:]]{{255}}){{{count}}}")),
        largest_taken(|count| format!("({few_high}{every}){{{count}}}")),
    ] {
        assert!(
            push_cases(&mut cases, &mut draws, &pattern, 2),
            "{pattern:?}"
        );
    }
    let grammar_taken = (0..600)
        .filter(|_| {
            let pattern = draws.alternation(2);
            push_cases(&mut cases, &mut draws, &pattern, 6)
        })
        .count();
    let soup_taken = (0..4000)
        .filter(|_| {
            let pattern = draws.soup();
            push_cases(&mut cases, &mut draws, &pattern, 3)
        })
        .count();
    assert!(
        grammar_taken > 300 && soup_taken > 300,
        "the subset took {grammar_taken} grammar and {soup_taken} soup patterns",
    );
    compare(&mut answers::connect(&PG18, PG18_TAG), cases);
}

/// Every character's membership of every class, as PostgreSQL answers `chr(code) ~ '[[:name:]]'`.
#[test]
fn classes_hold_what_postgresql_holds() {
    let mut conn = postgres::connect(&PG18, PG18_TAG);
    for name in CLASSES {
        let class = format!("[[:{name}:]]");
        let regex = PgRegex::new(&class).unwrap_or_else(|error| panic!("{class}: {error}"));
        let crate_flips = flips(|character| regex.is_match(character.encode_utf8(&mut [0; 4])));
        // Raw SQL, since `generate_series` and a window function have no DSL form.
        let listed: String = diesel::select(sql::<Text>(&format!(
            "(WITH members AS (
                 SELECT code, chr(code) ~ '{class}' AS member
                 FROM generate_series(1, 1114111) AS code
                 WHERE code NOT BETWEEN 55296 AND 57343
             )
             SELECT coalesce(string_agg(code::text, ',' ORDER BY code), '')
             FROM (
                 SELECT code, member, lag(member, 1, false) OVER (ORDER BY code) AS previous
                 FROM members
             ) AS flips
             WHERE member <> previous)"
        )))
        .get_result(&mut conn)
        .unwrap_or_else(|error| panic!("{class}: {error}"));
        let postgres_flips: Vec<u32> = listed
            .split(',')
            .filter(|code| !code.is_empty())
            .map(|code| code.parse().expect("a code point"))
            .collect();
        let first_difference = crate_flips
            .iter()
            .zip(&postgres_flips)
            .find(|(ours, theirs)| ours != theirs);
        assert!(
            first_difference.is_none() && crate_flips.len() == postgres_flips.len(),
            "{class} flips at {first_difference:?} (crate, PostgreSQL), {} and {} flips",
            crate_flips.len(),
            postgres_flips.len(),
        );
    }
}