no-mistakes-postgres-engine 0.109.130

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::names::{normalize_table_name, split_name};
use super::trigger_functions::TriggerFunctions;
use super::trigger_writes::Writes;
use super::{CatalogFunction, SchemaCatalog};
use no_mistakes_postgres_sql::erased_visit_capture::VisitCaptured;
use no_mistakes_postgres_sql::parse;
use sqlparser::ast::{Query, Statement, Visitor};
use std::{collections::BTreeMap, ops::ControlFlow};

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CatalogTriggerBodyKind {
    pub function: String,
    pub row_lock: bool,
    pub cross_table_write: bool,
}

impl SchemaCatalog {
    pub fn trigger_body_kinds(&self) -> anyhow::Result<&[CatalogTriggerBodyKind]> {
        self.projections()
            .trigger_body_kinds
            .get_or_init(|| {
                let bindings = TriggerFunctions::new(self);
                let mut parsed = BTreeMap::new();
                let mut kinds = BTreeMap::new();
                for table in self.logical_tables() {
                    for trigger in &table.triggers {
                        let Some(function) = bindings.resolve(table, trigger) else {
                            continue;
                        };
                        let activity = parsed
                            .entry(&function.key)
                            .or_insert_with(|| activity(function));
                        let activity = with_function(activity, &function.key)?;
                        let kind =
                            kinds
                                .entry(&function.key)
                                .or_insert_with(|| CatalogTriggerBodyKind {
                                    function: function.key.clone(),
                                    ..Default::default()
                                });
                        kind.row_lock |= activity.row_lock;
                        kind.cross_table_write |=
                            activity.writes.0.iter().any(|write| {
                                writes_other_table(self, &table.name, &write.relation)
                            });
                    }
                }
                Ok(kinds.into_values().collect())
            })
            .as_ref()
            .map(Vec::as_slice)
            .map_err(|reason| anyhow::anyhow!("{reason}"))
    }
}

fn writes_other_table(catalog: &SchemaCatalog, table: &str, relation: &str) -> bool {
    if catalog.declared_schema().is_none() && split_name(relation).0.is_some() {
        return normalize_table_name(relation) != normalize_table_name(table);
    }
    catalog
        .relation(relation)
        .map_or(relation != table, |target| target.name != table)
}

fn activity(function: &CatalogFunction) -> Result<Activity, &'static str> {
    let Some(body) = &function.body else {
        return Ok(Activity::default());
    };
    let statements = match function.language.as_deref() {
        Some("sql") => parse::parse_postgres_sql(body).unwrap_or_default(),
        Some("plpgsql") => parse::parse_postgres_body_with_function_sources(body)
            .into_iter()
            .map(|item| item.statement)
            .collect(),
        _ => Vec::new(),
    };
    visit_body(&statements, Activity::default())
}

pub(super) fn visit_body<T: Visitor<Break = &'static str>>(
    statements: &[Statement],
    mut visitor: T,
) -> Result<T, &'static str> {
    for statement in statements {
        if matches!(statement, Statement::Prepare { .. }) {
            continue;
        }
        if let ControlFlow::Break(reason) = statement.visit_captured(&mut visitor) {
            return Err(reason);
        }
    }
    Ok(visitor)
}

pub(super) fn with_function<'a, T>(
    analysis: &'a Result<T, &'static str>,
    function: &str,
) -> Result<&'a T, String> {
    analysis
        .as_ref()
        .map_err(|reason| format!("trigger function {function}: {reason}"))
}

#[derive(Default)]
struct Activity {
    row_lock: bool,
    writes: Writes,
}

impl Visitor for Activity {
    type Break = &'static str;

    fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<Self::Break> {
        self.writes.pre_visit_statement(statement)
    }

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<Self::Break> {
        self.row_lock |= !query.locks.is_empty();
        ControlFlow::Continue(())
    }
}

#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
#[test]
fn trigger_activity_excludes_prepared_payloads() {
    let sql = include_str!("../../../../fixtures/postgres/catalog/trigger-prepare.sql");
    let statements = parse::parse_postgres_sql(sql).unwrap();
    let activity = visit_body(&statements, Activity::default()).ok().unwrap();

    assert!(!activity.row_lock);
    assert_eq!(activity.writes.0.len(), 1);
    assert_eq!(activity.writes.0[0].relation, "jobs");
}