Skip to main content

no_mistakes_postgres_engine/catalog/
trigger_body_kinds.rs

1use super::names::{normalize_table_name, split_name};
2use super::trigger_functions::TriggerFunctions;
3use super::trigger_writes::Writes;
4use super::{CatalogFunction, SchemaCatalog};
5use no_mistakes_postgres_sql::erased_visit_capture::VisitCaptured;
6use no_mistakes_postgres_sql::parse;
7use sqlparser::ast::{Query, Statement, Visitor};
8use std::{collections::BTreeMap, ops::ControlFlow};
9
10#[derive(Clone, Debug, Default, PartialEq, Eq)]
11pub struct CatalogTriggerBodyKind {
12    pub function: String,
13    pub row_lock: bool,
14    pub cross_table_write: bool,
15}
16
17impl SchemaCatalog {
18    pub fn trigger_body_kinds(&self) -> anyhow::Result<&[CatalogTriggerBodyKind]> {
19        self.projections()
20            .trigger_body_kinds
21            .get_or_init(|| {
22                let bindings = TriggerFunctions::new(self);
23                let mut parsed = BTreeMap::new();
24                let mut kinds = BTreeMap::new();
25                for table in self.logical_tables() {
26                    for trigger in &table.triggers {
27                        let Some(function) = bindings.resolve(table, trigger) else {
28                            continue;
29                        };
30                        let activity = parsed
31                            .entry(&function.key)
32                            .or_insert_with(|| activity(function));
33                        let activity = with_function(activity, &function.key)?;
34                        let kind =
35                            kinds
36                                .entry(&function.key)
37                                .or_insert_with(|| CatalogTriggerBodyKind {
38                                    function: function.key.clone(),
39                                    ..Default::default()
40                                });
41                        kind.row_lock |= activity.row_lock;
42                        kind.cross_table_write |=
43                            activity.writes.0.iter().any(|write| {
44                                writes_other_table(self, &table.name, &write.relation)
45                            });
46                    }
47                }
48                Ok(kinds.into_values().collect())
49            })
50            .as_ref()
51            .map(Vec::as_slice)
52            .map_err(|reason| anyhow::anyhow!("{reason}"))
53    }
54}
55
56fn writes_other_table(catalog: &SchemaCatalog, table: &str, relation: &str) -> bool {
57    if catalog.declared_schema().is_none() && split_name(relation).0.is_some() {
58        return normalize_table_name(relation) != normalize_table_name(table);
59    }
60    catalog
61        .relation(relation)
62        .map_or(relation != table, |target| target.name != table)
63}
64
65fn activity(function: &CatalogFunction) -> Result<Activity, &'static str> {
66    let Some(body) = &function.body else {
67        return Ok(Activity::default());
68    };
69    let statements = match function.language.as_deref() {
70        Some("sql") => parse::parse_postgres_sql(body).unwrap_or_default(),
71        Some("plpgsql") => parse::parse_postgres_body_with_function_sources(body)
72            .into_iter()
73            .map(|item| item.statement)
74            .collect(),
75        _ => Vec::new(),
76    };
77    visit_body(&statements, Activity::default())
78}
79
80pub(super) fn visit_body<T: Visitor<Break = &'static str>>(
81    statements: &[Statement],
82    mut visitor: T,
83) -> Result<T, &'static str> {
84    for statement in statements {
85        if matches!(statement, Statement::Prepare { .. }) {
86            continue;
87        }
88        if let ControlFlow::Break(reason) = statement.visit_captured(&mut visitor) {
89            return Err(reason);
90        }
91    }
92    Ok(visitor)
93}
94
95pub(super) fn with_function<'a, T>(
96    analysis: &'a Result<T, &'static str>,
97    function: &str,
98) -> Result<&'a T, String> {
99    analysis
100        .as_ref()
101        .map_err(|reason| format!("trigger function {function}: {reason}"))
102}
103
104#[derive(Default)]
105struct Activity {
106    row_lock: bool,
107    writes: Writes,
108}
109
110impl Visitor for Activity {
111    type Break = &'static str;
112
113    fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<Self::Break> {
114        self.writes.pre_visit_statement(statement)
115    }
116
117    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<Self::Break> {
118        self.row_lock |= !query.locks.is_empty();
119        ControlFlow::Continue(())
120    }
121}
122
123#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
124#[test]
125fn trigger_activity_excludes_prepared_payloads() {
126    let sql = include_str!("../../../../fixtures/postgres/catalog/trigger-prepare.sql");
127    let statements = parse::parse_postgres_sql(sql).unwrap();
128    let activity = visit_body(&statements, Activity::default()).ok().unwrap();
129
130    assert!(!activity.row_lock);
131    assert_eq!(activity.writes.0.len(), 1);
132    assert_eq!(activity.writes.0[0].relation, "jobs");
133}