no-mistakes-postgres-engine 0.109.130

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::{slash_normalize, table_key, AllowList, CatalogObjectRef, RuleFinding};

impl AllowList {
    pub fn valid_column_selector(selector: &str) -> bool {
        table_key::column_splits(selector).next().is_some()
    }

    pub fn has_column_selectors(&self) -> bool {
        self.entries
            .iter()
            .any(|entry| entry.object.starts_with("column:"))
    }

    pub fn column_selector_is_ambiguous(&self, index: usize) -> bool {
        self.ambiguous_columns[index]
    }

    pub fn bind_catalog_columns(self, catalog: &crate::catalog::SchemaCatalog) -> Self {
        self.bind_column_candidates(catalog.tables().flat_map(|table| {
            table
                .columns
                .iter()
                .map(|column| (table.name.as_str(), column.name.as_str()))
        }))
    }

    pub fn bind_column_candidates<'a>(
        mut self,
        candidates: impl IntoIterator<Item = (&'a str, &'a str)>,
    ) -> Self {
        if self.has_column_selectors() {
            self.ambiguous_columns = table_key::ambiguous_columns(
                self.entries.iter().map(|entry| entry.object.as_str()),
                candidates,
            );
        }
        self
    }

    pub fn apply(self, catalog_path: &str, findings: Vec<RuleFinding>) -> Vec<RuleFinding> {
        self.apply_with(
            catalog_path,
            findings,
            |finding| finding,
            |finding| finding,
            &[],
        )
    }

    pub fn apply_with<T>(
        self,
        catalog_path: &str,
        mut findings: Vec<T>,
        finding: impl Fn(&T) -> &RuleFinding,
        wrap: impl Fn(RuleFinding) -> T,
        consumed: &[usize],
    ) -> Vec<T> {
        let mut used = vec![false; self.entries.len()];
        for &index in consumed {
            used[index] = true;
        }
        findings.retain(|finding_value| {
            let Some(target) = finding(finding_value).target.as_deref() else {
                return true;
            };
            !mark_used(&mut used, self.matching_entries([target]))
        });
        findings.extend(self.unused_findings(catalog_path, &used).map(wrap));
        findings
    }

    pub fn matching_objects<'a, const N: usize>(
        &'a self,
        objects: [&'a CatalogObjectRef; N],
    ) -> impl Iterator<Item = bool> + 'a {
        let targets = objects.map(|object| {
            (!matches!(object, CatalogObjectRef::Column { .. }))
                .then(|| canonical_key(&object.to_string()))
        });
        self.entries
            .iter()
            .zip(self.keys.iter().zip(&self.ambiguous_columns))
            .map(move |(entry, (key, ambiguous))| {
                !ambiguous
                    && objects
                        .iter()
                        .zip(&targets)
                        .any(|(object, target)| match object {
                            CatalogObjectRef::Column { table, column } => {
                                table_key::matches_column(&entry.object, table, column)
                            }
                            _ => target.as_ref() == Some(key),
                        })
            })
    }

    pub fn apply_objects(
        self,
        catalog_path: &str,
        findings: Vec<(CatalogObjectRef, RuleFinding)>,
    ) -> Vec<RuleFinding> {
        let mut used = vec![false; self.entries.len()];
        let mut findings: Vec<_> = findings
            .into_iter()
            .filter_map(|(object, finding)| {
                (!mark_used(&mut used, self.matching_objects([&object]))).then_some(finding)
            })
            .collect();
        findings.extend(self.unused_findings(catalog_path, &used));
        findings
    }

    fn unused_findings<'a>(
        &'a self,
        catalog_path: &str,
        used: &'a [bool],
    ) -> impl Iterator<Item = RuleFinding> + 'a {
        let path = slash_normalize(catalog_path);
        self.entries
            .iter()
            .zip(used)
            .filter(|(_, used)| !**used)
            .map(move |(entry, _)| RuleFinding {
                causes: Vec::new(),
                rule: self.rule_id.clone(),
                file: path.clone(),
                line: 1,
                message: format!(
                    "{path}: stale {} allow entry: {}",
                    self.rule_id, entry.object
                ),
                import: None,
                target: Some(entry.object.clone()),
            })
    }
}

fn mark_used(used: &mut [bool], matches: impl Iterator<Item = bool>) -> bool {
    let mut matched = false;
    for (used, entry_matches) in used.iter_mut().zip(matches) {
        if entry_matches {
            *used = true;
            matched = true;
        }
    }
    matched
}

pub fn canonical_key(object: &str) -> String {
    use super::super::names::normalize_table_name as table_key;
    let Ok(parsed) = object.parse::<CatalogObjectRef>() else {
        return object.to_string();
    };
    match parsed {
        CatalogObjectRef::Table(table) => CatalogObjectRef::Table(table_key(&table)),
        CatalogObjectRef::Column { table, column } => CatalogObjectRef::Column {
            table: table_key(&table),
            column,
        },
        CatalogObjectRef::Index { table, index } => CatalogObjectRef::Index {
            table: table_key(&table),
            index,
        },
        CatalogObjectRef::Trigger { table, trigger } => CatalogObjectRef::Trigger {
            table: table_key(&table),
            trigger,
        },
        CatalogObjectRef::Constraint { table, name } => CatalogObjectRef::Constraint {
            table: table_key(&table),
            name,
        },
        other => other,
    }
    .to_string()
}