Skip to main content

no_mistakes_postgres_engine/
catalog.rs

1use anyhow::{Context, Result};
2use no_mistakes_ts_analysis::source_access::SourceAccess;
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6mod arbiter;
7mod bounded;
8mod build;
9mod count_owners;
10mod discriminant;
11mod enums;
12mod expressions;
13mod fallback;
14mod findings;
15mod function;
16mod function_body;
17mod function_cardinality;
18mod function_clauses;
19mod function_comment;
20mod function_escape;
21mod function_outputs;
22mod function_quote;
23mod load;
24mod locations;
25#[cfg(test)]
26mod logical_scope_tests;
27mod model;
28mod names;
29mod nesting;
30mod partition;
31mod paths;
32mod projection_cache;
33mod relation_identity;
34mod resolve;
35mod row_security;
36mod scalar_functions;
37mod search_path;
38mod snapshot;
39mod table_scope;
40mod test_json;
41#[cfg(test)]
42mod tests;
43mod trigger;
44mod trigger_body_kinds;
45mod trigger_functions;
46mod trigger_writes;
47mod view_definition;
48mod view_relation;
49
50use arbiter::ArbiterTable;
51pub use arbiter::{CanonicalIndex, CanonicalOrderKey, ResolvedArbiter};
52pub use bounded::{canonical_bound_expr, BoundedUniqueIndex};
53pub use count_owners::{CatalogCountOwnerAnalysis, CatalogCountOwners};
54pub use expressions::{
55    expression_matches, normalize_expression, order_prefix_matches, parse_postgres_expression,
56};
57pub use findings::{
58    canonical_key, catalog_finding, require_catalog_path, AllowEntry, AllowList, CatalogObjectRef,
59};
60pub use model::{
61    CatalogCheck, CatalogColumn, CatalogCoverage, CatalogEnum, CatalogForeignKey, CatalogFunction,
62    CatalogIndexInfo, CatalogIndexKey, CatalogTable, CatalogTrigger, CatalogUnique, CatalogView,
63    GeneratedKind, PartitionKey, PartitionKeyElement, PartitionStrategy, RelationKind,
64    TriggerEvent, TriggerTiming,
65};
66pub use names::{decoded_parts, normalize_identifier};
67use paths::catalog_path;
68pub use paths::normalize_catalog_path;
69pub use row_security::{CatalogRowSecurity, PolicyCommand};
70use snapshot::Snapshot;
71pub use trigger_body_kinds::CatalogTriggerBodyKind;
72pub use trigger_writes::{CatalogTriggerWrite, CatalogTriggerWrites};
73
74#[derive(Debug, Clone, Default)]
75pub struct SchemaCatalog {
76    coverage: CatalogCoverage,
77    schema: Option<String>,
78    search_path_evidence: BTreeMap<String, Option<BTreeSet<String>>>,
79    current_database: Option<String>,
80    tables: BTreeMap<String, ArbiterTable>,
81    model_tables: BTreeMap<String, CatalogTable>,
82    row_security: BTreeMap<String, CatalogRowSecurity>,
83    descendant_presence: BTreeMap<String, bool>,
84    relation_fallback: std::sync::OnceLock<fallback::RelationFallback>,
85    functions: BTreeMap<String, CatalogFunction>,
86    trigger_function_identities: BTreeMap<String, BTreeMap<String, String>>,
87    projections:
88        std::sync::Arc<std::sync::OnceLock<std::sync::Arc<projection_cache::ProjectionCache>>>,
89    enums: BTreeMap<String, CatalogEnum>,
90    views: BTreeMap<String, CatalogView>,
91    view_fallback: std::sync::OnceLock<fallback::RelationFallback>,
92    locations: locations::CatalogLocations,
93}
94
95impl SchemaCatalog {
96    pub fn coverage(&self) -> CatalogCoverage {
97        self.coverage
98    }
99
100    /// Exact connected database name, when explicitly supplied by the catalog producer.
101    pub fn current_database(&self) -> Option<&str> {
102        self.current_database.as_deref()
103    }
104
105    /// Schema named by the catalog snapshot, when the producer set one.
106    pub fn declared_schema(&self) -> Option<&str> {
107        self.schema.as_deref()
108    }
109
110    pub fn load(root: &Path, raw_path: &str, sources: &dyn SourceAccess) -> Result<Self> {
111        let path = catalog_path(root, raw_path)?;
112        let source = sources.read_path(&path).map_err(|error| {
113            anyhow::anyhow!(
114                "failed to read schemaCatalogPath {}: {error}",
115                path.display()
116            )
117        })?;
118        let parsed = jsonc_parser::parse_to_ast(
119            &source,
120            &jsonc_parser::CollectOptions::default(),
121            &load::jsonc_parse_options(),
122        )
123        .with_context(|| format!("schemaCatalogPath {} is not valid JSONC", path.display()))?;
124        let locations = parsed
125            .value
126            .as_ref()
127            .map(|value| locations::catalog_locations(value, &source))
128            .unwrap_or_default();
129        let value = parsed
130            .value
131            .ok_or_else(|| anyhow::anyhow!("schemaCatalogPath {} is empty", path.display()))?;
132        let snapshot = load::parse_snapshot(&path.display().to_string(), value.into())?;
133        let mut catalog = Self::from_snapshot(&path.display().to_string(), snapshot)?;
134        catalog.locations = locations;
135        Ok(catalog)
136    }
137
138    fn from_snapshot(path: &str, snapshot: Snapshot) -> Result<Self> {
139        build::from_snapshot(path, snapshot)
140    }
141
142    pub fn tables(&self) -> impl Iterator<Item = &CatalogTable> {
143        self.model_tables.values()
144    }
145
146    /// Tables are indexed by normalized name, so a quoted key such as `"Order Items"` is found
147    /// by its quoted or unquoted spelling, the way it round-trips from the generator.
148    pub fn table(&self, name: &str) -> Option<&CatalogTable> {
149        self.model_tables.get(&names::normalize_table_name(name))
150    }
151
152    /// The table a SQL name refers to: its exact key, or the one table whose bare name it is.
153    /// A name that spells a schema reaches a bare-keyed table only when it is this catalog's
154    /// schema; `audit.accounts` is not the `accounts` of the catalog for `public`.
155    pub fn relation(&self, name: &str) -> Option<&CatalogTable> {
156        let normalized = names::normalize_table_name(name);
157        if let Some(table) = self.model_tables.get(&normalized) {
158            return Some(table);
159        }
160        // Names are split quote-aware: `public."audit.log"` has a schema and one bare name.
161        let (qualifier, bare) = names::split_name(name);
162        if let (Some(qualifier), Some(own)) = (&qualifier, &self.schema) {
163            if qualifier != own {
164                return None;
165            }
166        }
167        // Qualification only falls back to a bare catalog key; unqualified names require
168        // exactly one candidate across all schemas. The indexes retain that distinction.
169        let fallback = self
170            .relation_fallback
171            .get_or_init(|| fallback::build(&self.model_tables));
172        let key = if qualifier.is_some() {
173            fallback.bare_keys.get(&bare)?
174        } else {
175            fallback.unique.get(&bare)?.as_ref()?
176        };
177        self.model_tables.get(key)
178    }
179
180    pub fn functions(&self) -> impl Iterator<Item = &CatalogFunction> {
181        self.functions.values()
182    }
183
184    pub fn enums(&self) -> impl Iterator<Item = &CatalogEnum> {
185        self.enums.values()
186    }
187
188    pub fn views(&self) -> impl Iterator<Item = &CatalogView> {
189        self.views.values()
190    }
191}