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        rule: rule_id.to_string(),
95        file: path.clone(),
96        line: 1,
97        message: format!("{path}: {object}: {text}"),
98        import: None,
99        target: Some(object),
100    }
101}
102
103pub fn require_catalog_path(rule_id: &str, path: &str) -> Result<()> {
104    if path.trim().is_empty() {
105        bail!("{rule_id} option schemaCatalogPath: required");
106    }
107    Ok(())
108}
109
110#[derive(Debug, Clone, Deserialize)]
111#[serde(rename_all = "camelCase")]
112pub struct AllowEntry {
113    pub object: String,
114    pub reason: String,
115}
116
117#[derive(Debug, Clone)]
118pub struct AllowList {
119    rule_id: String,
120    entries: Vec<AllowEntry>,
121    keys: Vec<String>,
122    ambiguous_columns: Vec<bool>,
123}
124
125impl AllowList {
126    pub fn contains(&self, object: &str) -> bool {
127        self.matching_entries([object]).any(|matched| matched)
128    }
129
130    pub fn matching_entries<'a, const N: usize>(
131        &'a self,
132        objects: [&'a str; N],
133    ) -> impl Iterator<Item = bool> + 'a {
134        let targets = objects.map(canonical_key);
135        self.keys
136            .iter()
137            .zip(&self.ambiguous_columns)
138            .map(move |(key, ambiguous)| !ambiguous && targets.contains(key))
139    }
140
141    pub fn entry_keys(&self) -> impl Iterator<Item = (usize, &str)> + '_ {
142        self.keys.iter().map(String::as_str).enumerate()
143    }
144
145    pub fn entry_objects(&self) -> impl Iterator<Item = (usize, &str)> + '_ {
146        self.entries
147            .iter()
148            .enumerate()
149            .map(|(index, entry)| (index, entry.object.as_str()))
150    }
151
152    pub fn compile(rule_id: &str, entries: Vec<AllowEntry>) -> Result<Self> {
153        let mut seen = BTreeSet::new();
154        let mut keys = Vec::with_capacity(entries.len());
155        for entry in &entries {
156            if entry.reason.trim().is_empty() {
157                bail!(
158                    "{rule_id} option allow: entry {} needs a reason",
159                    entry.object
160                );
161            }
162            let valid = entry.object.strip_prefix("column:").map_or_else(
163                || entry.object.parse::<CatalogObjectRef>().is_ok(),
164                Self::valid_column_selector,
165            );
166            if !valid {
167                bail!(
168                    "{rule_id} option allow: invalid object ref {}",
169                    entry.object
170                );
171            }
172            let key = canonical_key(&entry.object);
173            if !seen.insert(table_key::duplicate_key(&entry.object, &key)) {
174                bail!("{rule_id} option allow: duplicate entry {}", entry.object);
175            }
176            keys.push(key);
177        }
178        Ok(Self {
179            ambiguous_columns: vec![false; entries.len()],
180            keys,
181            rule_id: rule_id.to_string(),
182            entries,
183        })
184    }
185}
186
187fn slash_normalize(path: &str) -> String {
188    path.replace('\\', "/")
189}