no-mistakes-postgres-engine 0.109.128

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use anyhow::{Context, Result};
use no_mistakes_ts_analysis::source_access::SourceAccess;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

mod arbiter;
mod bounded;
mod build;
mod count_owners;
mod discriminant;
mod enums;
mod expressions;
mod fallback;
mod findings;
mod function;
mod function_body;
mod function_cardinality;
mod function_clauses;
mod function_comment;
mod function_escape;
mod function_outputs;
mod function_quote;
mod load;
mod locations;
#[cfg(test)]
mod logical_scope_tests;
mod model;
mod names;
mod nesting;
mod partition;
mod paths;
mod projection_cache;
mod relation_identity;
mod resolve;
mod scalar_functions;
mod search_path;
mod snapshot;
mod table_scope;
mod test_json;
#[cfg(test)]
mod tests;
mod trigger;
mod trigger_body_kinds;
mod trigger_functions;
mod trigger_writes;
pub use trigger_body_kinds::CatalogTriggerBodyKind;
pub use trigger_writes::{CatalogTriggerWrite, CatalogTriggerWrites};
mod view_definition;
mod view_relation;

use arbiter::ArbiterTable;
pub use arbiter::{CanonicalIndex, CanonicalOrderKey, ResolvedArbiter};
pub use bounded::canonical_bound_expr;
pub use bounded::BoundedUniqueIndex;
pub use count_owners::{CatalogCountOwnerAnalysis, CatalogCountOwners};
pub use expressions::{
    expression_matches, normalize_expression, order_prefix_matches, parse_postgres_expression,
};
pub use findings::{
    canonical_key, catalog_finding, require_catalog_path, AllowEntry, AllowList, CatalogObjectRef,
};
pub use model::{
    CatalogCheck, CatalogColumn, CatalogCoverage, CatalogEnum, CatalogForeignKey, CatalogFunction,
    CatalogIndexInfo, CatalogIndexKey, CatalogTable, CatalogTrigger, CatalogUnique, CatalogView,
    GeneratedKind, PartitionKey, PartitionKeyElement, PartitionStrategy, RelationKind,
    TriggerEvent, TriggerTiming,
};
use paths::catalog_path;
pub use paths::normalize_catalog_path;
use snapshot::Snapshot;

#[derive(Debug, Clone, Default)]
pub struct SchemaCatalog {
    coverage: CatalogCoverage,
    schema: Option<String>,
    search_path_evidence: BTreeMap<String, Option<BTreeSet<String>>>,
    current_database: Option<String>,
    tables: BTreeMap<String, ArbiterTable>,
    model_tables: BTreeMap<String, CatalogTable>,
    descendant_presence: BTreeMap<String, bool>,
    relation_fallback: std::sync::OnceLock<fallback::RelationFallback>,
    functions: BTreeMap<String, CatalogFunction>,
    trigger_function_identities: BTreeMap<String, BTreeMap<String, String>>,
    projections:
        std::sync::Arc<std::sync::OnceLock<std::sync::Arc<projection_cache::ProjectionCache>>>,
    enums: BTreeMap<String, CatalogEnum>,
    views: BTreeMap<String, CatalogView>,
    view_fallback: std::sync::OnceLock<fallback::RelationFallback>,
    locations: locations::CatalogLocations,
}

impl SchemaCatalog {
    pub fn coverage(&self) -> CatalogCoverage {
        self.coverage
    }

    /// Exact connected database name, when explicitly supplied by the catalog producer.
    pub fn current_database(&self) -> Option<&str> {
        self.current_database.as_deref()
    }

    /// Schema named by the catalog snapshot, when the producer set one.
    pub fn declared_schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    pub fn load(root: &Path, raw_path: &str, sources: &dyn SourceAccess) -> Result<Self> {
        let path = catalog_path(root, raw_path)?;
        let source = sources.read_path(&path).map_err(|error| {
            anyhow::anyhow!(
                "failed to read schemaCatalogPath {}: {error}",
                path.display()
            )
        })?;
        let parsed = jsonc_parser::parse_to_ast(
            &source,
            &jsonc_parser::CollectOptions::default(),
            &load::jsonc_parse_options(),
        )
        .with_context(|| format!("schemaCatalogPath {} is not valid JSONC", path.display()))?;
        let locations = parsed
            .value
            .as_ref()
            .map(|value| locations::catalog_locations(value, &source))
            .unwrap_or_default();
        let value = parsed
            .value
            .ok_or_else(|| anyhow::anyhow!("schemaCatalogPath {} is empty", path.display()))?;
        let snapshot = load::parse_snapshot(&path.display().to_string(), value.into())?;
        let mut catalog = Self::from_snapshot(&path.display().to_string(), snapshot)?;
        catalog.locations = locations;
        Ok(catalog)
    }

    fn from_snapshot(path: &str, snapshot: Snapshot) -> Result<Self> {
        build::from_snapshot(path, snapshot)
    }

    pub fn tables(&self) -> impl Iterator<Item = &CatalogTable> {
        self.model_tables.values()
    }

    pub fn table_line(&self, table: &str) -> usize {
        self.locations.tables.get(table).copied().unwrap_or(1)
    }

    pub fn column_line(&self, table: &str, column: &str) -> usize {
        self.locations
            .columns
            .get(&(table.to_string(), column.to_string()))
            .copied()
            .unwrap_or(1)
    }

    /// Tables are indexed by normalized name, so a quoted key such as `"Order Items"` is found
    /// by its quoted or unquoted spelling, the way it round-trips from the generator.
    pub fn table(&self, name: &str) -> Option<&CatalogTable> {
        self.model_tables.get(&names::normalize_table_name(name))
    }

    /// The table a SQL name refers to: its exact key, or the one table whose bare name it is.
    /// A name that spells a schema reaches a bare-keyed table only when it is this catalog's
    /// schema; `audit.accounts` is not the `accounts` of the catalog for `public`.
    pub fn relation(&self, name: &str) -> Option<&CatalogTable> {
        let normalized = names::normalize_table_name(name);
        if let Some(table) = self.model_tables.get(&normalized) {
            return Some(table);
        }
        // Names are split quote-aware: `public."audit.log"` has a schema and one bare name.
        let (qualifier, bare) = names::split_name(name);
        if let (Some(qualifier), Some(own)) = (&qualifier, &self.schema) {
            if qualifier != own {
                return None;
            }
        }
        // Qualification only falls back to a bare catalog key; unqualified names require
        // exactly one candidate across all schemas. The indexes retain that distinction.
        let fallback = self
            .relation_fallback
            .get_or_init(|| fallback::build(&self.model_tables));
        let key = if qualifier.is_some() {
            fallback.bare_keys.get(&bare)?
        } else {
            fallback.unique.get(&bare)?.as_ref()?
        };
        self.model_tables.get(key)
    }

    pub fn functions(&self) -> impl Iterator<Item = &CatalogFunction> {
        self.functions.values()
    }

    pub fn enums(&self) -> impl Iterator<Item = &CatalogEnum> {
        self.enums.values()
    }

    pub fn views(&self) -> impl Iterator<Item = &CatalogView> {
        self.views.values()
    }
}

pub use names::{decoded_parts, normalize_identifier};