Skip to main content

no_mistakes_postgres_sql/
function_calls.rs

1//! Syntactic calls shared by SQL policies; names and locations retain SQL identity.
2use super::idents::ident_key;
3use sqlparser::ast::{
4    Expr, ObjectName, OrderBy, Query, Select, Spanned, Statement, TableFactor, Visit, Visitor,
5};
6use std::ops::ControlFlow;
7
8mod clause;
9mod clauses;
10pub use clause::SqlFunctionClause;
11
12/// One function expression, excluding column and alias identifiers.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct SqlFunctionCallFact {
15    pub name_parts: Vec<String>,
16    pub line: usize,
17    pub column: usize,
18    /// None for calls outside the supported clauses, including FROM and GROUP BY.
19    pub clause: Option<SqlFunctionClause>,
20}
21
22pub(super) fn collect(statement: &Statement, out: &mut Vec<SqlFunctionCallFact>) {
23    collect_projected(statement, out, false);
24}
25
26/// Project calls from statements that actually execute, while retaining the
27/// syntactic collector for callers that inspect the original SQL expression.
28pub(super) fn collect_executed(statement: &Statement, out: &mut Vec<SqlFunctionCallFact>) {
29    let mut executed = Vec::new();
30    super::statements::walk_executed(statement, &mut executed);
31    for statement in executed {
32        collect(statement, out);
33    }
34}
35
36pub(super) fn collect_projected(
37    statement: &Statement,
38    out: &mut Vec<SqlFunctionCallFact>,
39    synthetic_select: bool,
40) {
41    let _ = statement.visit(&mut Calls {
42        out,
43        roots: clauses::Roots::default(),
44        current: None,
45        contexts: Vec::new(),
46        synthetic_select,
47    });
48}
49
50/// Visit an expression owned by parser recovery using its actual clause.
51pub(super) fn collect_expression(
52    expression: &Expr,
53    out: &mut Vec<SqlFunctionCallFact>,
54    clause: Option<SqlFunctionClause>,
55) {
56    let _ = expression.visit(&mut Calls {
57        out,
58        roots: clauses::Roots::default(),
59        current: clause,
60        contexts: Vec::new(),
61        synthetic_select: false,
62    });
63}
64
65struct Calls<'a> {
66    out: &'a mut Vec<SqlFunctionCallFact>,
67    roots: clauses::Roots,
68    current: Option<SqlFunctionClause>,
69    contexts: Vec<Option<SqlFunctionClause>>,
70    synthetic_select: bool,
71}
72
73impl Calls<'_> {
74    fn enter(&mut self, clause: Option<SqlFunctionClause>) {
75        self.contexts.push(self.current);
76        self.current = clause;
77    }
78
79    fn leave(&mut self) {
80        self.current = self.contexts.pop().expect("balanced SQL visitor context");
81    }
82}
83
84impl Visitor for Calls<'_> {
85    type Break = ();
86
87    fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<()> {
88        self.enter(None);
89        self.roots.statement(statement);
90        ControlFlow::Continue(())
91    }
92
93    fn post_visit_statement(&mut self, _statement: &Statement) -> ControlFlow<()> {
94        self.leave();
95        ControlFlow::Continue(())
96    }
97
98    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
99        // A subquery owns its clauses even when it occurs inside an outer expression.
100        self.enter(None);
101        self.roots.query(query);
102        ControlFlow::Continue(())
103    }
104
105    fn post_visit_query(&mut self, _query: &Query) -> ControlFlow<()> {
106        self.leave();
107        ControlFlow::Continue(())
108    }
109
110    fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
111        self.roots.select(select, !self.synthetic_select);
112        self.synthetic_select = false;
113        ControlFlow::Continue(())
114    }
115
116    fn pre_visit_order_by(&mut self, ordering: &OrderBy) -> ControlFlow<()> {
117        self.roots.order_by(ordering);
118        ControlFlow::Continue(())
119    }
120
121    fn pre_visit_expr(&mut self, expression: &Expr) -> ControlFlow<()> {
122        self.enter(self.roots.clause(expression).unwrap_or(self.current));
123        if let Expr::Function(function) = expression {
124            self.roots.function(function);
125            record(&function.name, self.current, self.out);
126        }
127        ControlFlow::Continue(())
128    }
129
130    fn post_visit_expr(&mut self, _expression: &Expr) -> ControlFlow<()> {
131        self.leave();
132        ControlFlow::Continue(())
133    }
134
135    fn pre_visit_table_factor(&mut self, table: &TableFactor) -> ControlFlow<()> {
136        match table {
137            TableFactor::Table {
138                name,
139                args: Some(_),
140                ..
141            }
142            | TableFactor::Function { name, .. } => record(name, self.current, self.out),
143            _ => {}
144        }
145        ControlFlow::Continue(())
146    }
147}
148
149fn record(
150    name: &ObjectName,
151    clause: Option<SqlFunctionClause>,
152    out: &mut Vec<SqlFunctionCallFact>,
153) {
154    let parts: Option<Vec<_>> = name
155        .0
156        .iter()
157        .map(|part| part.as_ident().map(ident_key))
158        .collect();
159    if let Some(name_parts) = parts {
160        let start = name.span().start;
161        out.push(SqlFunctionCallFact {
162            name_parts,
163            line: start.line.max(1) as usize,
164            column: start.column.max(1) as usize,
165            clause,
166        });
167    }
168}
169
170#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
171mod tests;
172
173#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
174mod clause_tests;
175
176#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
177mod join_tests;
178
179#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
180mod variant_tests;
181
182#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
183mod mutation_tests;
184
185#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
186mod execution_tests;