no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use regex::Regex;
use std::sync::OnceLock;

/// True when executed SQL is missing a leading `/* name */` annotation.
///
/// `BEGIN` / `COMMIT` / `ROLLBACK` are exempt, including when they already
/// carry a leading block comment. Matches the runtime-query
/// contract: `/^\s*\/\*\s*\S[\s\S]*?\*\//`.
pub fn sql_requires_query_annotation(sql: &str) -> bool {
    !is_transaction_command(sql) && !has_leading_query_annotation(sql)
}

#[doc(hidden)]
pub fn has_leading_query_annotation(sql: &str) -> bool {
    annotation_re().is_match(sql)
}

/// Name from the same leading comment recognized by the annotation rule.
pub fn leading_query_annotation(sql: &str) -> Option<&str> {
    let comment = annotation_re().find(sql)?.as_str().trim();
    Some(comment[2..comment.len() - 2].trim())
}

fn is_transaction_command(sql: &str) -> bool {
    transaction_re().is_match(sql)
}

/// End of the fixed command keyword, so a prefix proof can require an
/// observed word boundary instead of assuming its unknown suffix ends here.
#[doc(hidden)]
pub fn transaction_command_prefix_end(sql: &str) -> Option<usize> {
    transaction_re().find(sql).map(|matched| matched.end())
}

fn annotation_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"(?s)^\s*/\*\s*\S.*?\*/").expect("query annotation regex"))
}

fn transaction_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"(?is)^\s*(?:/\*.*?\*/\s*)?(?:BEGIN|COMMIT|ROLLBACK)\b")
            .expect("transaction command regex")
    })
}

#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
mod tests;