Skip to main content

no_mistakes_postgres_sql/
annotation.rs

1use regex::Regex;
2use std::sync::OnceLock;
3
4/// True when executed SQL is missing a leading `/* name */` annotation.
5///
6/// `BEGIN` / `COMMIT` / `ROLLBACK` are exempt, including when they already
7/// carry a leading block comment. Matches the runtime-query
8/// contract: `/^\s*\/\*\s*\S[\s\S]*?\*\//`.
9pub fn sql_requires_query_annotation(sql: &str) -> bool {
10    !is_transaction_command(sql) && !has_leading_query_annotation(sql)
11}
12
13#[doc(hidden)]
14pub fn has_leading_query_annotation(sql: &str) -> bool {
15    annotation_re().is_match(sql)
16}
17
18/// Name from the same leading comment recognized by the annotation rule.
19pub fn leading_query_annotation(sql: &str) -> Option<&str> {
20    let comment = annotation_re().find(sql)?.as_str().trim();
21    Some(comment[2..comment.len() - 2].trim())
22}
23
24fn is_transaction_command(sql: &str) -> bool {
25    transaction_re().is_match(sql)
26}
27
28/// End of the fixed command keyword, so a prefix proof can require an
29/// observed word boundary instead of assuming its unknown suffix ends here.
30#[doc(hidden)]
31pub fn transaction_command_prefix_end(sql: &str) -> Option<usize> {
32    transaction_re().find(sql).map(|matched| matched.end())
33}
34
35fn annotation_re() -> &'static Regex {
36    static RE: OnceLock<Regex> = OnceLock::new();
37    RE.get_or_init(|| Regex::new(r"(?s)^\s*/\*\s*\S.*?\*/").expect("query annotation regex"))
38}
39
40fn transaction_re() -> &'static Regex {
41    static RE: OnceLock<Regex> = OnceLock::new();
42    RE.get_or_init(|| {
43        Regex::new(r"(?is)^\s*(?:/\*.*?\*/\s*)?(?:BEGIN|COMMIT|ROLLBACK)\b")
44            .expect("transaction command regex")
45    })
46}
47
48#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
49mod tests;