no-mistakes-postgres-engine 0.109.125

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use crate::catalog::count_owners::shape::{self, Increment};
use crate::catalog::{
    trigger_body_kinds::visit_body, CatalogFunction, CatalogTriggerWrite, TriggerEvent,
};
use no_mistakes_postgres_sql::dml::writes::names::assignment_base_column_keys;
use no_mistakes_postgres_sql::idents::object_name_identity;
use no_mistakes_postgres_sql::parse::parse_postgres_sql;
use sqlparser::ast::{
    Assignment, Expr, FromTable, MergeAction, MergeUpdateKind, OnConflictAction, OnInsert,
    Statement, TableFactor, TableInheritance, TableObject, Visitor,
};
use std::ops::ControlFlow;

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct WriteEffect {
    pub(super) write: CatalogTriggerWrite,
    pub(super) only: bool,
}

pub(super) struct Effects {
    pub(super) increment: Option<Increment>,
    pub(super) writes: Vec<WriteEffect>,
}

pub(super) fn effects(function: &CatalogFunction) -> Result<Effects, &'static str> {
    let body = function
        .body
        .as_deref()
        .ok_or("trigger function body is missing")?;
    let (statements, increment) = match function.language.as_deref() {
        Some("plpgsql") => {
            let statements =
                shape::plain_block(body).ok_or("trigger body is not a supported PL/pgSQL block")?;
            let increment = shape::increment(&statements);
            (statements, increment)
        }
        Some("sql") => (
            parse_postgres_sql(body).map_err(|_| "trigger function SQL could not be parsed")?,
            None,
        ),
        _ => return Err("trigger function language has no write analysis"),
    };
    let writes = visit_body(&statements, StaticWrites::default())?.writes;
    Ok(Effects { increment, writes })
}

#[derive(Default)]
struct StaticWrites {
    writes: Vec<WriteEffect>,
}

impl StaticWrites {
    fn push(&mut self, relation: String, event: TriggerEvent, columns: Vec<String>, only: bool) {
        self.writes.push(WriteEffect {
            write: CatalogTriggerWrite {
                relation,
                event,
                columns,
            },
            only,
        });
    }
}

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

    fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<Self::Break> {
        match statement {
            Statement::Insert(insert) => {
                let TableObject::TableName(name) = &insert.table else {
                    return ControlFlow::Break("INSERT target is not a named table");
                };
                let table = object_name_identity(name);
                self.push(table.clone(), TriggerEvent::Insert, Vec::new(), false);
                if let Some(OnInsert::OnConflict(conflict)) = &insert.on {
                    if let OnConflictAction::DoUpdate(update) = &conflict.action {
                        self.push(
                            table,
                            TriggerEvent::Update,
                            columns(&update.assignments),
                            false,
                        );
                    }
                }
            }
            Statement::Update(update) => {
                let Some((table, only)) = named_table(&update.table.relation) else {
                    return ControlFlow::Break("UPDATE target is not a named table");
                };
                self.push(
                    table,
                    TriggerEvent::Update,
                    columns(&update.assignments),
                    only,
                );
            }
            Statement::Merge(merge) => {
                let Some((table, only)) = named_table(&merge.table) else {
                    return ControlFlow::Break("MERGE target is not a named table");
                };
                for clause in &merge.clauses {
                    let (event, cols, clause_only) = match &clause.action {
                        MergeAction::Insert(_) => (TriggerEvent::Insert, Vec::new(), false),
                        MergeAction::Update(update) => {
                            let cols = match &update.kind {
                                MergeUpdateKind::Set(assignments) => columns(assignments),
                                MergeUpdateKind::Wildcard => Vec::new(),
                            };
                            (TriggerEvent::Update, cols, only)
                        }
                        MergeAction::Delete { .. } => (TriggerEvent::Delete, Vec::new(), only),
                        MergeAction::DoNothing { .. } => continue,
                    };
                    self.push(table.clone(), event, cols, clause_only);
                }
            }
            Statement::Delete(delete) => {
                let (FromTable::WithFromKeyword(from) | FromTable::WithoutKeyword(from)) =
                    &delete.from;
                for table in from {
                    let Some((relation, only)) = named_table(&table.relation) else {
                        return ControlFlow::Break("DELETE target is not a named table");
                    };
                    self.push(relation, TriggerEvent::Delete, Vec::new(), only);
                }
            }
            Statement::Query(_) | Statement::Return(_) => {}
            _ => return ControlFlow::Break("trigger statement effects are unknown"),
        }
        ControlFlow::Continue(())
    }

    fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<Self::Break> {
        match factor {
            TableFactor::Table { args: None, .. }
            | TableFactor::Derived { .. }
            | TableFactor::NestedJoin { .. }
            | TableFactor::UNNEST { .. } => ControlFlow::Continue(()),
            _ => ControlFlow::Break("trigger table function calls may have indirect effects"),
        }
    }

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
        if matches!(expr, Expr::Function(_)) {
            ControlFlow::Break("trigger function calls may have indirect effects")
        } else {
            ControlFlow::Continue(())
        }
    }
}

fn named_table(factor: &TableFactor) -> Option<(String, bool)> {
    let TableFactor::Table {
        name,
        args: None,
        inheritance,
        ..
    } = factor
    else {
        return None;
    };
    let only = matches!(inheritance, Some(TableInheritance::Only { .. }));
    Some((object_name_identity(name), only))
}

fn columns(assignments: &[Assignment]) -> Vec<String> {
    assignments
        .iter()
        .flat_map(|value| assignment_base_column_keys(&value.target))
        .collect()
}