1use 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
11pub trait Visitor {
17 fn visit_expression(&mut self, expression: Expression) -> Result<Expression> {
21 Ok(expression)
22 }
23
24 fn visit_table_reference(&mut self, reference: Table) -> Result<Table> {
28 Ok(reference)
29 }
30
31 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#[derive(Debug, Clone, Copy, Default)]
87pub struct Walker;
88
89impl Walker {
90 pub const fn new() -> Self {
94 Walker
95 }
96
97 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#[derive(Debug, Clone, PartialEq, Eq)]
261pub struct ColumnValidator {
262 allowed: Vec<String>,
263 allow_star: bool,
264}
265
266impl ColumnValidator {
267 pub fn new(allowed: Vec<String>, allow_star: bool) -> Self {
271 ColumnValidator { allowed, allow_star }
272 }
273}
274
275impl Visitor for ColumnValidator {
276 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#[derive(Debug, Clone, PartialEq)]
300pub struct FilterInjector {
301 condition: Expression,
302}
303
304impl FilterInjector {
305 pub fn new(condition: impl Into<Expression>) -> Self {
309 FilterInjector { condition: condition.into() }
310 }
311}
312
313impl Visitor for FilterInjector {
314 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#[derive(Debug, Clone, PartialEq, Eq)]
332pub struct TableRenamer {
333 renames: HashMap<String, String>,
334}
335
336impl TableRenamer {
337 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 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 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}