Skip to main content

uqa_sql/plan/
visit.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read-only traversal of every scalar expression a plan owns: the counterpart of the plan rewrite for analyses that check a plan without changing it.
8
9use super::{
10    CommandPlan, CtePlan, CtePlanBody, QueryPlan, RelationalPlan, SourcePlan, UnifiedPlan,
11};
12use crate::ir::ScalarExpr;
13
14impl UnifiedPlan {
15    /// Visit every scalar expression this plan owns, each root once, including those of its CTEs, relational sources, scalar subqueries and command inputs. The nested nodes of a root are reached through [`ScalarExpr::visit`].
16    pub fn visit_scalar_expressions(&self, visit: &mut dyn FnMut(&ScalarExpr)) {
17        let Ok(()) = self.try_visit_scalar_expressions(&mut |expression| {
18            visit(expression);
19            Ok::<_, std::convert::Infallible>(())
20        });
21    }
22
23    /// Stop at the first callback error, without copying syntax or visiting later inputs.
24    pub fn try_visit_scalar_expressions<'a, E>(
25        &'a self,
26        visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<(), E>,
27    ) -> Result<(), E> {
28        match self {
29            Self::Query(query) => query.try_visit_scalar_expressions(visit)?,
30            Self::Command(command) => command.try_visit_scalar_expressions(visit)?,
31        }
32        Ok(())
33    }
34}
35
36impl<'a> super::PlanRef<'a> {
37    pub fn visit_scalar_expressions(self, visit: &mut dyn FnMut(&ScalarExpr)) {
38        let Ok(()) = self.try_visit_scalar_expressions(&mut |expression| {
39            visit(expression);
40            Ok::<_, std::convert::Infallible>(())
41        });
42    }
43
44    /// Stop at the first callback error, without copying syntax or visiting later inputs.
45    pub fn try_visit_scalar_expressions<E>(
46        self,
47        visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<(), E>,
48    ) -> Result<(), E> {
49        match self {
50            Self::Query(query) => query.try_visit_scalar_expressions(visit)?,
51            Self::Command(command) => command.try_visit_scalar_expressions(visit)?,
52        }
53        Ok(())
54    }
55}
56
57fn try_visit_ctes<'a, E>(
58    ctes: &'a [CtePlan],
59    visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<(), E>,
60) -> Result<(), E> {
61    for cte in ctes {
62        match &cte.body {
63            CtePlanBody::Query(query) => query.try_visit_scalar_expressions(visit)?,
64            CtePlanBody::Command(command) => command.try_visit_scalar_expressions(visit)?,
65        }
66        if let Some(cycle) = &cte.cycle {
67            visit(&cycle.mark_value)?;
68            visit(&cycle.mark_default)?;
69        }
70    }
71    Ok(())
72}
73
74impl QueryPlan {
75    /// Visit every scalar expression this query owns, each root once, including those of its CTEs, relational sources and scalar subqueries.
76    pub fn visit_scalar_expressions(&self, visit: &mut dyn FnMut(&ScalarExpr)) {
77        let Ok(()) = self.try_visit_scalar_expressions(&mut |expression| {
78            visit(expression);
79            Ok::<_, std::convert::Infallible>(())
80        });
81    }
82
83    /// Stop at the first callback error, without copying syntax or visiting later inputs.
84    pub fn try_visit_scalar_expressions<'a, E>(
85        &'a self,
86        visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<(), E>,
87    ) -> Result<(), E> {
88        try_visit_ctes(&self.ctes, visit)?;
89        match &self.root {
90            RelationalPlan::QueryBlock(block) => {
91                for rewrite in &block.deferred_outer_rewrites {
92                    rewrite.try_visit_scalar_expressions(visit)?;
93                }
94                if let Some(source) = &block.from {
95                    source.try_visit_scalar_expressions(visit)?;
96                }
97                for expression in block
98                    .r#where
99                    .iter()
100                    .chain(block.projections.iter().map(|projection| &projection.expr))
101                    .chain(&block.group_by)
102                    .chain(block.grouping_sets.iter().flatten())
103                    .chain(block.having.iter())
104                    .chain(block.order_by.iter().map(|order| &order.expr))
105                    .chain(block.limit.iter())
106                    .chain(block.offset.iter())
107                    .chain(&block.distinct_on)
108                {
109                    visit(expression)?;
110                }
111                for window in &block.windows {
112                    for expression in window.spec.expressions() {
113                        visit(expression)?;
114                    }
115                }
116                for subquery in &block.subqueries {
117                    subquery.try_visit_scalar_expressions(visit)?;
118                }
119            }
120            RelationalPlan::SetOp {
121                left,
122                right,
123                order_by,
124                limit,
125                offset,
126                subqueries,
127                ..
128            } => {
129                left.try_visit_scalar_expressions(visit)?;
130                right.try_visit_scalar_expressions(visit)?;
131                for expression in order_by
132                    .iter()
133                    .map(|order| &order.expr)
134                    .chain(limit.as_deref())
135                    .chain(offset.as_deref())
136                {
137                    visit(expression)?;
138                }
139                for subquery in subqueries {
140                    subquery.try_visit_scalar_expressions(visit)?;
141                }
142            }
143            RelationalPlan::Values { rows, subqueries } => {
144                for expression in rows.iter().flatten() {
145                    visit(expression)?;
146                }
147                for subquery in subqueries {
148                    subquery.try_visit_scalar_expressions(visit)?;
149                }
150            }
151        }
152        Ok(())
153    }
154}
155
156impl SourcePlan {
157    /// Visit every scalar expression this source owns, each root once: join conditions, `VALUES` rows, function arguments and the expressions of the query bodies nested in derived tables.
158    pub fn visit_scalar_expressions(&self, visit: &mut dyn FnMut(&ScalarExpr)) {
159        let Ok(()) = self.try_visit_scalar_expressions(&mut |expression| {
160            visit(expression);
161            Ok::<_, std::convert::Infallible>(())
162        });
163    }
164
165    /// Stop at the first callback error, without copying syntax or visiting later inputs.
166    pub fn try_visit_scalar_expressions<'a, E>(
167        &'a self,
168        visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<(), E>,
169    ) -> Result<(), E> {
170        match self {
171            crate::plan::SourcePlan::RetainedRows(_) => {}
172            Self::Table { .. } => {}
173            Self::Subquery { body, .. } => body.try_visit_scalar_expressions(visit)?,
174            Self::Join {
175                left, right, on, ..
176            } => {
177                left.try_visit_scalar_expressions(visit)?;
178                right.try_visit_scalar_expressions(visit)?;
179                if let Some(on) = on {
180                    visit(on)?;
181                }
182            }
183            Self::Values { rows, .. } => {
184                for expression in rows.iter().flatten() {
185                    visit(expression)?;
186                }
187            }
188            Self::Function { args, .. } => {
189                for argument in args {
190                    visit(argument)?;
191                }
192            }
193            Self::FunctionGroup { functions, .. } => {
194                for argument in functions.iter().flat_map(|function| &function.args) {
195                    visit(argument)?;
196                }
197            }
198        }
199        Ok(())
200    }
201}
202
203mod command;