Skip to main content

no_mistakes_postgres_engine/catalog/
findings.rs

1mod allow;
2pub use allow::canonical_key;
3mod table_key;
4use anyhow::{bail, Result};
5use no_mistakes_rule_kernel::finding::RuleFinding;
6use serde::Deserialize;
7use std::collections::BTreeSet;
8use std::fmt;
9use std::str::FromStr;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum CatalogObjectRef {
13    Table(String),
14    Column { table: String, column: String },
15    Index { table: String, index: String },
16    Trigger { table: String, trigger: String },
17    Constraint { table: String, name: String },
18    Function(String),
19    Enum(String),
20    View(String),
21    MaterializedView(String),
22}
23
24impl fmt::Display for CatalogObjectRef {
25    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::Table(name) => write!(formatter, "table:{name}"),
28            Self::Column { table, column } => write!(formatter, "column:{table}.{column}"),
29            Self::Index { table, index } => write!(formatter, "index:{table}.{index}"),
30            Self::Trigger { table, trigger } => write!(formatter, "trigger:{table}.{trigger}"),
31            Self::Constraint { table, name } => write!(formatter, "constraint:{table}.{name}"),
32            Self::Function(key) => write!(formatter, "function:{key}"),
33            Self::Enum(name) => write!(formatter, "enum:{name}"),
34            Self::View(name) => write!(formatter, "view:{name}"),
35            Self::MaterializedView(name) => write!(formatter, "materialized-view:{name}"),
36        }
37    }
38}
39
40impl FromStr for CatalogObjectRef {
41    type Err = ();
42
43    fn from_str(raw: &str) -> Result<Self, ()> {
44        if let Some(rest) = raw.strip_prefix("materialized-view:") {
45            return Ok(Self::MaterializedView(non_empty(rest)?));
46        }
47        let (prefix, rest) = raw.split_once(':').ok_or(())?;
48        let object = match prefix {
49            "table" => Self::Table(non_empty(rest)?),
50            "column" => {
51                let (table, column) = pair(rest)?;
52                Self::Column { table, column }
53            }
54            "index" => {
55                let (table, index) = pair(rest)?;
56                Self::Index { table, index }
57            }
58            "trigger" => {
59                let (table, trigger) = pair(rest)?;
60                Self::Trigger { table, trigger }
61            }
62            "constraint" => {
63                let (table, name) = pair(rest)?;
64                Self::Constraint { table, name }
65            }
66            "function" => Self::Function(non_empty(rest)?),
67            "enum" => Self::Enum(non_empty(rest)?),
68            "view" => Self::View(non_empty(rest)?),
69            _ => return Err(()),
70        };
71        Ok(object)
72    }
73}
74
75fn non_empty(raw: &str) -> Result<String, ()> {
76    (!raw.trim().is_empty()).then(|| raw.to_string()).ok_or(())
77}
78
79fn pair(raw: &str) -> Result<(String, String), ()> {
80    let (left, right) = raw.rsplit_once('.').ok_or(())?;
81    Ok((non_empty(left)?, non_empty(right)?))
82}
83
84pub fn catalog_finding(
85    rule_id: &str,
86    catalog_path: &str,
87    object: &CatalogObjectRef,
88    text: &str,
89) -> RuleFinding {
90    let path = slash_normalize(catalog_path);
91    let object = object.to_string();
92    RuleFinding {
93        causes: Vec::new(),
94        uncovered_lines: Vec::new(),
95        rule: rule_id.to_string(),
96        file: path.clone(),
97        line: 1,
98        message: format!("{path}: {object}: {text}"),
99        import: None,
100        target: Some(object),
101    }
102}
103
104pub fn require_catalog_path(rule_id: &str, path: &str) -> Result<()> {
105    if path.trim().is_empty() {
106        bail!("{rule_id} option schemaCatalogPath: required");
107    }
108    Ok(())
109}
110
111#[derive(Debug, Clone, Deserialize)]
112#[serde(rename_all = "camelCase")]
113pub struct AllowEntry {
114    pub object: String,
115    pub reason: String,
116}
117
118#[derive(Debug, Clone)]
119pub struct AllowList {
120    rule_id: String,
121    entries: Vec<AllowEntry>,
122    keys: Vec<String>,
123    ambiguous_columns: Vec<bool>,
124}
125
126impl AllowList {
127    pub fn contains(&self, object: &str) -> bool {
128        self.matching_entries([object]).any(|matched| matched)
129    }
130
131    pub fn matching_entries<'a, const N: usize>(
132        &'a self,
133        objects: [&'a str; N],
134    ) -> impl Iterator<Item = bool> + 'a {
135        let targets = objects.map(canonical_key);
136        self.keys
137            .iter()
138            .zip(&self.ambiguous_columns)
139            .map(move |(key, ambiguous)| !ambiguous && targets.contains(key))
140    }
141
142    pub fn entry_keys(&self) -> impl Iterator<Item = (usize, &str)> + '_ {
143        self.keys.iter().map(String::as_str).enumerate()
144    }
145
146    pub fn entry_objects(&self) -> impl Iterator<Item = (usize, &str)> + '_ {
147        self.entries
148            .iter()
149            .enumerate()
150            .map(|(index, entry)| (index, entry.object.as_str()))
151    }
152
153    pub fn compile(rule_id: &str, entries: Vec<AllowEntry>) -> Result<Self> {
154        let mut seen = BTreeSet::new();
155        let mut keys = Vec::with_capacity(entries.len());
156        for entry in &entries {
157            if entry.reason.trim().is_empty() {
158                bail!(
159                    "{rule_id} option allow: entry {} needs a reason",
160                    entry.object
161                );
162            }
163            let valid = entry.object.strip_prefix("column:").map_or_else(
164                || entry.object.parse::<CatalogObjectRef>().is_ok(),
165                Self::valid_column_selector,
166            );
167            if !valid {
168                bail!(
169                    "{rule_id} option allow: invalid object ref {}",
170                    entry.object
171                );
172            }
173            let key = canonical_key(&entry.object);
174            if !seen.insert(table_key::duplicate_key(&entry.object, &key)) {
175                bail!("{rule_id} option allow: duplicate entry {}", entry.object);
176            }
177            keys.push(key);
178        }
179        Ok(Self {
180            ambiguous_columns: vec![false; entries.len()],
181            keys,
182            rule_id: rule_id.to_string(),
183            entries,
184        })
185    }
186}
187
188fn slash_normalize(path: &str) -> String {
189    path.replace('\\', "/")
190}