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