Skip to main content

utopia_query/ast/
walker.rs

1//! [`Walker`] and [`Visitor`]: rewriting a tree, and the visitors the
2//! library ships.
3
4use std::collections::HashMap;
5
6use super::node::{
7    Binary, Column, Expression, InList, JoinClause, OrderByItem, Select, Star, Table, TableSource, WindowSpecification,
8};
9use crate::error::{Error, Result};
10
11/// Inspects or rewrites the nodes a [`Walker`] visits: each method gets a
12/// node (its children already walked) and returns it, or its replacement.
13/// The defaults keep every node.
14///
15/// PHP: the `Utopia\Query\AST\Visitor` interface.
16pub trait Visitor {
17    /// Visits an expression.
18    ///
19    /// PHP: `Visitor::visitExpression()`.
20    fn visit_expression(&mut self, expression: Expression) -> Result<Expression> {
21        Ok(expression)
22    }
23
24    /// Visits a table reference (of a `FROM` or a join).
25    ///
26    /// PHP: `Visitor::visitTableReference()`.
27    fn visit_table_reference(&mut self, reference: Table) -> Result<Table> {
28        Ok(reference)
29    }
30
31    /// Visits a statement, after everything in it (subqueries included).
32    ///
33    /// PHP: `Visitor::visitSelect()`.
34    fn visit_select(&mut self, select: Select) -> Result<Select> {
35        Ok(select)
36    }
37}
38
39impl<V: Visitor + ?Sized> Visitor for &mut V {
40    fn visit_expression(&mut self, expression: Expression) -> Result<Expression> {
41        (**self).visit_expression(expression)
42    }
43
44    fn visit_table_reference(&mut self, reference: Table) -> Result<Table> {
45        (**self).visit_table_reference(reference)
46    }
47
48    fn visit_select(&mut self, select: Select) -> Result<Select> {
49        (**self).visit_select(select)
50    }
51}
52
53/// Applies a [`Visitor`] to every node of a statement, bottom-up: the
54/// children of a node first, then the node. Statements nested in
55/// subqueries, `IN`, `EXISTS`, derived tables and CTEs are walked the same
56/// way, and each gets [`Visitor::visit_select`].
57///
58/// Order within a statement: columns, `FROM`, joins (table, then
59/// condition), `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`, `LIMIT`,
60/// `OFFSET`, CTEs, `WINDOW` definitions.
61///
62/// PHP: `Utopia\Query\AST\Walker`.
63///
64/// ```
65/// use std::collections::HashMap;
66/// use utopia_query::ast::{Parser, Serializer, TableRenamer, Walker};
67///
68/// let select = Parser::new().parse_sql("SELECT u.id FROM users u WHERE u.active = 1")?;
69/// let mut renamer = TableRenamer::new(HashMap::from([("users".to_owned(), "accounts".to_owned())]));
70/// let select = Walker::new().walk(select, &mut renamer)?;
71/// assert_eq!(Serializer::new().serialize(&select)?, "SELECT `u`.`id` FROM `accounts` AS `u` WHERE `u`.`active` = 1");
72/// # Ok::<(), utopia_query::Error>(())
73/// ```
74///
75/// ```php
76/// use Utopia\Query\AST\Parser;
77/// use Utopia\Query\AST\Serializer;
78/// use Utopia\Query\AST\Visitor\TableRenamer;
79/// use Utopia\Query\AST\Walker;
80/// use Utopia\Query\Tokenizer\Tokenizer;
81///
82/// $select = (new Parser())->parse(Tokenizer::filter((new Tokenizer())->tokenize('SELECT u.id FROM users u WHERE u.active = 1')));
83/// $select = (new Walker())->walk($select, new TableRenamer(['users' => 'accounts']));
84/// echo (new Serializer())->serialize($select), "\n"; // SELECT `u`.`id` FROM `accounts` AS `u` WHERE `u`.`active` = 1
85/// ```
86#[derive(Debug, Clone, Copy, Default)]
87pub struct Walker;
88
89impl Walker {
90    /// A walker.
91    ///
92    /// PHP: `new Walker()`.
93    pub const fn new() -> Self {
94        Walker
95    }
96
97    /// `statement` with `visitor` applied to every node; fails with the
98    /// first error a visitor returns.
99    ///
100    /// PHP: `Walker::walk()`.
101    pub fn walk<V: Visitor + ?Sized>(&self, statement: Select, visitor: &mut V) -> Result<Select> {
102        let statement = self.statement(statement, visitor)?;
103        visitor.visit_select(statement)
104    }
105
106    fn statement<V: Visitor + ?Sized>(&self, s: Select, v: &mut V) -> Result<Select> {
107        let columns = self.expressions(s.columns, v)?;
108        let from = match s.from {
109            Some(source) => Some(self.source(source, v)?),
110            None => None,
111        };
112        let joins = s
113            .joins
114            .into_iter()
115            .map(|join| {
116                let table = self.source(join.table, v)?;
117                let condition = self.optional(join.condition, v)?;
118                Ok(JoinClause { kind: join.kind, table, condition })
119            })
120            .collect::<Result<_>>()?;
121        let where_clause = self.optional(s.where_clause, v)?;
122        let group_by = self.expressions(s.group_by, v)?;
123        let having = self.optional(s.having, v)?;
124        let order_by = self.order_by(s.order_by, v)?;
125        let limit = self.optional(s.limit, v)?;
126        let offset = self.optional(s.offset, v)?;
127        let mut ctes = s.ctes;
128        for cte in &mut ctes {
129            cte.query = self.walk(std::mem::take(&mut cte.query), v)?;
130        }
131        let mut windows = s.windows;
132        for window in &mut windows {
133            window.specification = self.specification(std::mem::take(&mut window.specification), v)?;
134        }
135        Ok(Select {
136            columns,
137            from,
138            joins,
139            where_clause,
140            group_by,
141            having,
142            order_by,
143            limit,
144            offset,
145            distinct: s.distinct,
146            ctes,
147            windows,
148        })
149    }
150
151    fn source<V: Visitor + ?Sized>(&self, source: TableSource, v: &mut V) -> Result<TableSource> {
152        Ok(match source {
153            TableSource::Table(t) => TableSource::Table(v.visit_table_reference(t)?),
154            TableSource::Subquery(mut s) => {
155                *s.query = self.walk(std::mem::take(&mut *s.query), v)?;
156                TableSource::Subquery(s)
157            }
158        })
159    }
160
161    fn optional<V: Visitor + ?Sized>(&self, e: Option<Expression>, v: &mut V) -> Result<Option<Expression>> {
162        e.map(|e| self.expression(e, v)).transpose()
163    }
164
165    fn boxed<V: Visitor + ?Sized>(&self, e: &mut Box<Expression>, v: &mut V) -> Result<()> {
166        let inner = std::mem::replace(&mut **e, Expression::Star(Star::default()));
167        **e = self.expression(inner, v)?;
168        Ok(())
169    }
170
171    fn expressions<V: Visitor + ?Sized>(&self, items: Vec<Expression>, v: &mut V) -> Result<Vec<Expression>> {
172        items.into_iter().map(|e| self.expression(e, v)).collect()
173    }
174
175    fn order_by<V: Visitor + ?Sized>(&self, items: Vec<OrderByItem>, v: &mut V) -> Result<Vec<OrderByItem>> {
176        items
177            .into_iter()
178            .map(|item| {
179                Ok(OrderByItem {
180                    expression: self.expression(item.expression, v)?,
181                    direction: item.direction,
182                    nulls: item.nulls,
183                })
184            })
185            .collect()
186    }
187
188    fn specification<V: Visitor + ?Sized>(&self, s: WindowSpecification, v: &mut V) -> Result<WindowSpecification> {
189        Ok(WindowSpecification {
190            partition_by: self.expressions(s.partition_by, v)?,
191            order_by: self.order_by(s.order_by, v)?,
192            ..s
193        })
194    }
195
196    fn expression<V: Visitor + ?Sized>(&self, mut expression: Expression, v: &mut V) -> Result<Expression> {
197        match &mut expression {
198            Expression::Binary(b) => {
199                self.boxed(&mut b.left, v)?;
200                self.boxed(&mut b.right, v)?;
201                if let Some(escape) = &mut b.escape {
202                    self.boxed(escape, v)?;
203                }
204            }
205            Expression::Unary(u) => self.boxed(&mut u.operand, v)?,
206            Expression::Func(f) => {
207                f.arguments = self.expressions(std::mem::take(&mut f.arguments), v)?;
208                if let Some(filter) = &mut f.filter {
209                    self.boxed(filter, v)?;
210                }
211            }
212            Expression::Aliased(a) => self.boxed(&mut a.expression, v)?,
213            Expression::In(i) => {
214                self.boxed(&mut i.expression, v)?;
215                match &mut i.list {
216                    InList::Subquery(query) => **query = self.walk(std::mem::take(&mut **query), v)?,
217                    InList::Values(items) => *items = self.expressions(std::mem::take(items), v)?,
218                }
219            }
220            Expression::Between(b) => {
221                self.boxed(&mut b.expression, v)?;
222                self.boxed(&mut b.low, v)?;
223                self.boxed(&mut b.high, v)?;
224            }
225            Expression::Exists(e) => *e.subquery = self.walk(std::mem::take(&mut *e.subquery), v)?,
226            Expression::Conditional(c) => {
227                if let Some(operand) = &mut c.operand {
228                    self.boxed(operand, v)?;
229                }
230                for when in &mut c.whens {
231                    self.boxed(&mut when.condition, v)?;
232                    self.boxed(&mut when.result, v)?;
233                }
234                if let Some(else_result) = &mut c.else_result {
235                    self.boxed(else_result, v)?;
236                }
237            }
238            Expression::Cast(c) => self.boxed(&mut c.expression, v)?,
239            Expression::Subquery(s) => *s.query = self.walk(std::mem::take(&mut *s.query), v)?,
240            Expression::Window(w) => {
241                self.boxed(&mut w.function, v)?;
242                if let Some(specification) = w.specification.take() {
243                    w.specification = Some(Box::new(self.specification(*specification, v)?));
244                }
245            }
246            Expression::CaseWhen(_)
247            | Expression::Literal(_)
248            | Expression::Placeholder(_)
249            | Expression::Raw(_)
250            | Expression::Column(_)
251            | Expression::Star(_) => {}
252        }
253        v.visit_expression(expression)
254    }
255}
256
257/// Rejects columns outside an allow-list, and `*` unless allowed.
258///
259/// PHP: `Utopia\Query\AST\Visitor\ColumnValidator`.
260#[derive(Debug, Clone, PartialEq, Eq)]
261pub struct ColumnValidator {
262    allowed: Vec<String>,
263    allow_star: bool,
264}
265
266impl ColumnValidator {
267    /// A validator allowing `allowed` columns (by name), and `*` when `allow_star`.
268    ///
269    /// PHP: `new ColumnValidator($allowedColumns, $allowStar)`.
270    pub fn new(allowed: Vec<String>, allow_star: bool) -> Self {
271        ColumnValidator { allowed, allow_star }
272    }
273}
274
275impl Visitor for ColumnValidator {
276    /// Fails with [`Error::Query`] on a column not allowed, or on `*` (any
277    /// `*`, qualified or not) unless allowed.
278    ///
279    /// PHP: `ColumnValidator::visitExpression()`.
280    fn visit_expression(&mut self, expression: Expression) -> Result<Expression> {
281        match &expression {
282            Expression::Column(c) if !self.allowed.contains(&c.name) => {
283                Err(Error::query(format!("Column '{}' is not in the allowed list", c.name)))
284            }
285            Expression::Star(_) if !self.allow_star => Err(Error::query(
286                "Wildcard (*) selection is not allowed; list explicit columns or construct ColumnValidator with allowStar: true",
287            )),
288            _ => Ok(expression),
289        }
290    }
291}
292
293/// Adds a condition to the `WHERE` of statements (`AND`-ed with an existing one).
294///
295/// Walked, it applies to every statement, subqueries included; to change
296/// only the outer one, call [`Visitor::visit_select`] on it directly.
297///
298/// PHP: `Utopia\Query\AST\Visitor\FilterInjector`.
299#[derive(Debug, Clone, PartialEq)]
300pub struct FilterInjector {
301    condition: Expression,
302}
303
304impl FilterInjector {
305    /// An injector of `condition`.
306    ///
307    /// PHP: `new FilterInjector($condition)`.
308    pub fn new(condition: impl Into<Expression>) -> Self {
309        FilterInjector { condition: condition.into() }
310    }
311}
312
313impl Visitor for FilterInjector {
314    /// `select` with the condition in its `WHERE`.
315    ///
316    /// PHP: `FilterInjector::visitSelect()`.
317    fn visit_select(&mut self, mut select: Select) -> Result<Select> {
318        let condition = self.condition.clone();
319        select.where_clause = Some(match select.where_clause.take() {
320            None => condition,
321            Some(existing) => Binary::new(existing, "AND", condition).into(),
322        });
323        Ok(select)
324    }
325}
326
327/// Renames tables: table references (name and alias) and the table
328/// qualifier of columns and `table.*`.
329///
330/// PHP: `Utopia\Query\AST\Visitor\TableRenamer`.
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub struct TableRenamer {
333    renames: HashMap<String, String>,
334}
335
336impl TableRenamer {
337    /// A renamer of each old name to its new name.
338    ///
339    /// PHP: `new TableRenamer($renames)`.
340    pub fn new(renames: HashMap<String, String>) -> Self {
341        TableRenamer { renames }
342    }
343
344    fn renamed(&self, name: &Option<String>) -> Option<&String> {
345        name.as_ref().and_then(|n| self.renames.get(n))
346    }
347}
348
349impl Visitor for TableRenamer {
350    /// A column or `*` with its table qualifier renamed.
351    ///
352    /// PHP: `TableRenamer::visitExpression()`.
353    fn visit_expression(&mut self, expression: Expression) -> Result<Expression> {
354        Ok(match expression {
355            Expression::Column(c) => match self.renamed(&c.table) {
356                Some(table) => Column { name: c.name, table: Some(table.clone()), schema: c.schema }.into(),
357                None => Expression::Column(c),
358            },
359            Expression::Star(s) => match self.renamed(&s.table) {
360                Some(table) => Star { table: Some(table.clone()), schema: s.schema }.into(),
361                None => Expression::Star(s),
362            },
363            other => other,
364        })
365    }
366
367    /// The table with its name and alias renamed.
368    ///
369    /// PHP: `TableRenamer::visitTableReference()`.
370    fn visit_table_reference(&mut self, reference: Table) -> Result<Table> {
371        let name = self.renames.get(&reference.name).cloned();
372        let alias = self.renamed(&reference.alias).cloned();
373        if name.is_none() && alias.is_none() {
374            return Ok(reference);
375        }
376        Ok(Table { name: name.unwrap_or(reference.name), alias: alias.or(reference.alias), schema: reference.schema })
377    }
378}