1use crate::expressions::Expression;
9use serde::{Deserialize, Serialize};
10use std::collections::{HashMap, HashSet, VecDeque};
11#[cfg(feature = "bindings")]
12use ts_rs::TS;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "bindings", derive(TS))]
17#[cfg_attr(feature = "bindings", ts(export))]
18pub enum ScopeType {
19 Root,
21 Subquery,
23 DerivedTable,
25 Cte,
27 SetOperation,
29 Udtf,
31}
32
33#[derive(Debug, Clone)]
35pub struct SourceInfo {
36 pub expression: Expression,
38 pub is_scope: bool,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct ColumnRef {
45 pub table: Option<String>,
47 pub name: String,
49}
50
51#[derive(Debug, Clone)]
56pub struct Scope {
57 pub expression: Expression,
59
60 pub scope_type: ScopeType,
62
63 pub sources: HashMap<String, SourceInfo>,
65
66 pub lateral_sources: HashMap<String, SourceInfo>,
68
69 pub cte_sources: HashMap<String, SourceInfo>,
71
72 pub outer_columns: Vec<String>,
75
76 pub can_be_correlated: bool,
79
80 pub subquery_scopes: Vec<Scope>,
82
83 pub derived_table_scopes: Vec<Scope>,
85
86 pub cte_scopes: Vec<Scope>,
88
89 pub udtf_scopes: Vec<Scope>,
91
92 pub table_scopes: Vec<Scope>,
94
95 pub union_scopes: Vec<Scope>,
97
98 columns_cache: Option<Vec<ColumnRef>>,
100
101 external_columns_cache: Option<Vec<ColumnRef>>,
103}
104
105impl Scope {
106 pub fn new(expression: Expression) -> Self {
108 Self {
109 expression,
110 scope_type: ScopeType::Root,
111 sources: HashMap::new(),
112 lateral_sources: HashMap::new(),
113 cte_sources: HashMap::new(),
114 outer_columns: Vec::new(),
115 can_be_correlated: false,
116 subquery_scopes: Vec::new(),
117 derived_table_scopes: Vec::new(),
118 cte_scopes: Vec::new(),
119 udtf_scopes: Vec::new(),
120 table_scopes: Vec::new(),
121 union_scopes: Vec::new(),
122 columns_cache: None,
123 external_columns_cache: None,
124 }
125 }
126
127 pub fn branch(&self, expression: Expression, scope_type: ScopeType) -> Self {
129 self.branch_with_options(expression, scope_type, None, None, None)
130 }
131
132 pub fn branch_with_options(
134 &self,
135 expression: Expression,
136 scope_type: ScopeType,
137 sources: Option<HashMap<String, SourceInfo>>,
138 lateral_sources: Option<HashMap<String, SourceInfo>>,
139 outer_columns: Option<Vec<String>>,
140 ) -> Self {
141 let can_be_correlated = self.can_be_correlated
142 || scope_type == ScopeType::Subquery
143 || scope_type == ScopeType::Udtf;
144
145 Self {
146 expression,
147 scope_type,
148 sources: sources.unwrap_or_default(),
149 lateral_sources: lateral_sources.unwrap_or_default(),
150 cte_sources: self.cte_sources.clone(),
151 outer_columns: outer_columns.unwrap_or_default(),
152 can_be_correlated,
153 subquery_scopes: Vec::new(),
154 derived_table_scopes: Vec::new(),
155 cte_scopes: Vec::new(),
156 udtf_scopes: Vec::new(),
157 table_scopes: Vec::new(),
158 union_scopes: Vec::new(),
159 columns_cache: None,
160 external_columns_cache: None,
161 }
162 }
163
164 pub fn clear_cache(&mut self) {
166 self.columns_cache = None;
167 self.external_columns_cache = None;
168 }
169
170 pub fn add_source(&mut self, name: String, expression: Expression, is_scope: bool) {
172 self.sources.insert(
173 name,
174 SourceInfo {
175 expression,
176 is_scope,
177 },
178 );
179 self.clear_cache();
180 }
181
182 pub fn add_lateral_source(&mut self, name: String, expression: Expression, is_scope: bool) {
184 self.lateral_sources.insert(
185 name.clone(),
186 SourceInfo {
187 expression: expression.clone(),
188 is_scope,
189 },
190 );
191 self.sources.insert(
192 name,
193 SourceInfo {
194 expression,
195 is_scope,
196 },
197 );
198 self.clear_cache();
199 }
200
201 pub fn add_cte_source(&mut self, name: String, expression: Expression) {
203 self.cte_sources.insert(
204 name.clone(),
205 SourceInfo {
206 expression: expression.clone(),
207 is_scope: true,
208 },
209 );
210 self.sources.insert(
211 name,
212 SourceInfo {
213 expression,
214 is_scope: true,
215 },
216 );
217 self.clear_cache();
218 }
219
220 pub fn rename_source(&mut self, old_name: &str, new_name: String) {
222 if let Some(source) = self.sources.remove(old_name) {
223 self.sources.insert(new_name, source);
224 }
225 self.clear_cache();
226 }
227
228 pub fn remove_source(&mut self, name: &str) {
230 self.sources.remove(name);
231 self.clear_cache();
232 }
233
234 pub fn columns(&mut self) -> &[ColumnRef] {
236 if self.columns_cache.is_none() {
237 let mut columns = Vec::new();
238 collect_columns(&self.expression, &mut columns);
239 self.columns_cache = Some(columns);
240 }
241 self.columns_cache.as_ref().unwrap()
242 }
243
244 pub fn source_names(&self) -> HashSet<String> {
246 let mut names: HashSet<String> = self.sources.keys().cloned().collect();
247 names.extend(self.cte_sources.keys().cloned());
248 names
249 }
250
251 pub fn external_columns(&mut self) -> Vec<ColumnRef> {
253 if self.external_columns_cache.is_some() {
254 return self.external_columns_cache.clone().unwrap();
255 }
256
257 let source_names = self.source_names();
258 let columns = self.columns().to_vec();
259
260 let external: Vec<ColumnRef> = columns
261 .into_iter()
262 .filter(|col| {
263 match &col.table {
265 Some(table) => !source_names.contains(table),
266 None => false, }
268 })
269 .collect();
270
271 self.external_columns_cache = Some(external.clone());
272 external
273 }
274
275 pub fn local_columns(&mut self) -> Vec<ColumnRef> {
277 let external_set: HashSet<_> = self.external_columns().into_iter().collect();
278 let columns = self.columns().to_vec();
279
280 columns
281 .into_iter()
282 .filter(|col| !external_set.contains(col))
283 .collect()
284 }
285
286 pub fn unqualified_columns(&mut self) -> Vec<ColumnRef> {
288 self.columns()
289 .iter()
290 .filter(|c| c.table.is_none())
291 .cloned()
292 .collect()
293 }
294
295 pub fn source_columns(&mut self, source_name: &str) -> Vec<ColumnRef> {
297 self.columns()
298 .iter()
299 .filter(|col| col.table.as_deref() == Some(source_name))
300 .cloned()
301 .collect()
302 }
303
304 pub fn is_correlated_subquery(&mut self) -> bool {
310 self.can_be_correlated && !self.external_columns().is_empty()
311 }
312
313 pub fn is_subquery(&self) -> bool {
315 self.scope_type == ScopeType::Subquery
316 }
317
318 pub fn is_derived_table(&self) -> bool {
320 self.scope_type == ScopeType::DerivedTable
321 }
322
323 pub fn is_cte(&self) -> bool {
325 self.scope_type == ScopeType::Cte
326 }
327
328 pub fn is_root(&self) -> bool {
330 self.scope_type == ScopeType::Root
331 }
332
333 pub fn is_udtf(&self) -> bool {
335 self.scope_type == ScopeType::Udtf
336 }
337
338 pub fn is_union(&self) -> bool {
340 self.scope_type == ScopeType::SetOperation
341 }
342
343 pub fn traverse(&self) -> Vec<&Scope> {
345 let mut result = Vec::new();
346 self.traverse_impl(&mut result);
347 result
348 }
349
350 fn traverse_impl<'a>(&'a self, result: &mut Vec<&'a Scope>) {
351 for scope in &self.cte_scopes {
353 scope.traverse_impl(result);
354 }
355 for scope in &self.union_scopes {
356 scope.traverse_impl(result);
357 }
358 for scope in &self.table_scopes {
359 scope.traverse_impl(result);
360 }
361 for scope in &self.subquery_scopes {
362 scope.traverse_impl(result);
363 }
364 result.push(self);
366 }
367
368 pub fn ref_count(&self) -> HashMap<usize, usize> {
370 let mut counts: HashMap<usize, usize> = HashMap::new();
371
372 for scope in self.traverse() {
373 for (_, source_info) in scope.sources.iter() {
374 if source_info.is_scope {
375 let id = &source_info.expression as *const _ as usize;
376 *counts.entry(id).or_insert(0) += 1;
377 }
378 }
379 }
380
381 counts
382 }
383}
384
385fn collect_columns(expr: &Expression, columns: &mut Vec<ColumnRef>) {
387 match expr {
388 Expression::Column(col) => {
389 columns.push(ColumnRef {
390 table: col.table.as_ref().map(|t| t.name.clone()),
391 name: col.name.name.clone(),
392 });
393 }
394 Expression::Select(select) => {
395 for e in &select.expressions {
397 collect_columns(e, columns);
398 }
399 for join in &select.joins {
401 if let Some(on) = &join.on {
402 collect_columns(on, columns);
403 }
404 if let Some(match_condition) = &join.match_condition {
405 collect_columns(match_condition, columns);
406 }
407 }
408 if let Some(where_clause) = &select.where_clause {
410 collect_columns(&where_clause.this, columns);
411 }
412 if let Some(having) = &select.having {
414 collect_columns(&having.this, columns);
415 }
416 if let Some(order_by) = &select.order_by {
418 for ord in &order_by.expressions {
419 collect_columns(&ord.this, columns);
420 }
421 }
422 if let Some(group_by) = &select.group_by {
424 for e in &group_by.expressions {
425 collect_columns(e, columns);
426 }
427 }
428 }
431 Expression::And(bin)
433 | Expression::Or(bin)
434 | Expression::Add(bin)
435 | Expression::Sub(bin)
436 | Expression::Mul(bin)
437 | Expression::Div(bin)
438 | Expression::Mod(bin)
439 | Expression::Eq(bin)
440 | Expression::Neq(bin)
441 | Expression::Lt(bin)
442 | Expression::Lte(bin)
443 | Expression::Gt(bin)
444 | Expression::Gte(bin)
445 | Expression::BitwiseAnd(bin)
446 | Expression::BitwiseOr(bin)
447 | Expression::BitwiseXor(bin)
448 | Expression::Concat(bin) => {
449 collect_columns(&bin.left, columns);
450 collect_columns(&bin.right, columns);
451 }
452 Expression::Like(like) | Expression::ILike(like) => {
454 collect_columns(&like.left, columns);
455 collect_columns(&like.right, columns);
456 if let Some(escape) = &like.escape {
457 collect_columns(escape, columns);
458 }
459 }
460 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
462 collect_columns(&un.this, columns);
463 }
464 Expression::Function(func) => {
465 for arg in &func.args {
466 collect_columns(arg, columns);
467 }
468 }
469 Expression::AggregateFunction(agg) => {
470 for arg in &agg.args {
471 collect_columns(arg, columns);
472 }
473 }
474 Expression::WindowFunction(wf) => {
475 collect_columns(&wf.this, columns);
476 for e in &wf.over.partition_by {
477 collect_columns(e, columns);
478 }
479 for e in &wf.over.order_by {
480 collect_columns(&e.this, columns);
481 }
482 }
483 Expression::Alias(alias) => {
484 collect_columns(&alias.this, columns);
485 }
486 Expression::Case(case) => {
487 if let Some(operand) = &case.operand {
488 collect_columns(operand, columns);
489 }
490 for (when_expr, then_expr) in &case.whens {
491 collect_columns(when_expr, columns);
492 collect_columns(then_expr, columns);
493 }
494 if let Some(else_clause) = &case.else_ {
495 collect_columns(else_clause, columns);
496 }
497 }
498 Expression::Paren(paren) => {
499 collect_columns(&paren.this, columns);
500 }
501 Expression::Ordered(ord) => {
502 collect_columns(&ord.this, columns);
503 }
504 Expression::In(in_expr) => {
505 collect_columns(&in_expr.this, columns);
506 for e in &in_expr.expressions {
507 collect_columns(e, columns);
508 }
509 }
511 Expression::Between(between) => {
512 collect_columns(&between.this, columns);
513 collect_columns(&between.low, columns);
514 collect_columns(&between.high, columns);
515 }
516 Expression::IsNull(is_null) => {
517 collect_columns(&is_null.this, columns);
518 }
519 Expression::Cast(cast) => {
520 collect_columns(&cast.this, columns);
521 }
522 Expression::Extract(extract) => {
523 collect_columns(&extract.this, columns);
524 }
525 Expression::Exists(_) | Expression::Subquery(_) => {
526 }
528 _ => {
529 }
531 }
532}
533
534pub fn build_scope(expression: &Expression) -> Scope {
539 let mut root = Scope::new(expression.clone());
540 build_scope_impl(expression, &mut root);
541 root
542}
543
544fn build_scope_impl(expression: &Expression, current_scope: &mut Scope) {
545 match expression {
546 Expression::Select(select) => {
547 if let Some(with) = &select.with {
549 for cte in &with.ctes {
550 let cte_name = cte.alias.name.clone();
551 let mut cte_scope = current_scope
552 .branch(Expression::Cte(Box::new(cte.clone())), ScopeType::Cte);
553 build_scope_impl(&cte.this, &mut cte_scope);
554 current_scope.add_cte_source(cte_name, Expression::Cte(Box::new(cte.clone())));
555 current_scope.cte_scopes.push(cte_scope);
556 }
557 }
558
559 if let Some(from) = &select.from {
561 for table in &from.expressions {
562 add_table_to_scope(table, current_scope);
563 }
564 }
565
566 for join in &select.joins {
568 add_table_to_scope(&join.this, current_scope);
569 }
570
571 collect_subqueries(expression, current_scope);
573 }
574 Expression::Union(union) => {
575 let mut left_scope = current_scope.branch(union.left.clone(), ScopeType::SetOperation);
576 build_scope_impl(&union.left, &mut left_scope);
577
578 let mut right_scope =
579 current_scope.branch(union.right.clone(), ScopeType::SetOperation);
580 build_scope_impl(&union.right, &mut right_scope);
581
582 current_scope.union_scopes.push(left_scope);
583 current_scope.union_scopes.push(right_scope);
584 }
585 Expression::Intersect(intersect) => {
586 let mut left_scope =
587 current_scope.branch(intersect.left.clone(), ScopeType::SetOperation);
588 build_scope_impl(&intersect.left, &mut left_scope);
589
590 let mut right_scope =
591 current_scope.branch(intersect.right.clone(), ScopeType::SetOperation);
592 build_scope_impl(&intersect.right, &mut right_scope);
593
594 current_scope.union_scopes.push(left_scope);
595 current_scope.union_scopes.push(right_scope);
596 }
597 Expression::Except(except) => {
598 let mut left_scope = current_scope.branch(except.left.clone(), ScopeType::SetOperation);
599 build_scope_impl(&except.left, &mut left_scope);
600
601 let mut right_scope =
602 current_scope.branch(except.right.clone(), ScopeType::SetOperation);
603 build_scope_impl(&except.right, &mut right_scope);
604
605 current_scope.union_scopes.push(left_scope);
606 current_scope.union_scopes.push(right_scope);
607 }
608 _ => {}
609 }
610}
611
612fn add_table_to_scope(expr: &Expression, scope: &mut Scope) {
613 match expr {
614 Expression::Table(table) => {
615 let name = table
616 .alias
617 .as_ref()
618 .map(|a| a.name.clone())
619 .unwrap_or_else(|| table.name.name.clone());
620 scope.add_source(name, expr.clone(), false);
621 }
622 Expression::Subquery(subquery) => {
623 let name = subquery
624 .alias
625 .as_ref()
626 .map(|a| a.name.clone())
627 .unwrap_or_default();
628
629 let mut derived_scope = scope.branch(subquery.this.clone(), ScopeType::DerivedTable);
630 build_scope_impl(&subquery.this, &mut derived_scope);
631
632 scope.add_source(name.clone(), expr.clone(), true);
633 scope.derived_table_scopes.push(derived_scope);
634 }
635 Expression::Paren(paren) => {
636 add_table_to_scope(&paren.this, scope);
637 }
638 _ => {}
639 }
640}
641
642fn collect_subqueries(expr: &Expression, parent_scope: &mut Scope) {
643 match expr {
644 Expression::Select(select) => {
645 if let Some(where_clause) = &select.where_clause {
647 collect_subqueries_in_expr(&where_clause.this, parent_scope);
648 }
649 for e in &select.expressions {
651 collect_subqueries_in_expr(e, parent_scope);
652 }
653 if let Some(having) = &select.having {
655 collect_subqueries_in_expr(&having.this, parent_scope);
656 }
657 }
658 _ => {}
659 }
660}
661
662fn collect_subqueries_in_expr(expr: &Expression, parent_scope: &mut Scope) {
663 match expr {
664 Expression::Subquery(subquery) if subquery.alias.is_none() => {
665 let mut sub_scope = parent_scope.branch(subquery.this.clone(), ScopeType::Subquery);
667 build_scope_impl(&subquery.this, &mut sub_scope);
668 parent_scope.subquery_scopes.push(sub_scope);
669 }
670 Expression::In(in_expr) => {
671 collect_subqueries_in_expr(&in_expr.this, parent_scope);
672 if let Some(query) = &in_expr.query {
673 let mut sub_scope = parent_scope.branch(query.clone(), ScopeType::Subquery);
674 build_scope_impl(query, &mut sub_scope);
675 parent_scope.subquery_scopes.push(sub_scope);
676 }
677 }
678 Expression::Exists(exists) => {
679 let mut sub_scope = parent_scope.branch(exists.this.clone(), ScopeType::Subquery);
680 build_scope_impl(&exists.this, &mut sub_scope);
681 parent_scope.subquery_scopes.push(sub_scope);
682 }
683 Expression::And(bin)
685 | Expression::Or(bin)
686 | Expression::Add(bin)
687 | Expression::Sub(bin)
688 | Expression::Mul(bin)
689 | Expression::Div(bin)
690 | Expression::Mod(bin)
691 | Expression::Eq(bin)
692 | Expression::Neq(bin)
693 | Expression::Lt(bin)
694 | Expression::Lte(bin)
695 | Expression::Gt(bin)
696 | Expression::Gte(bin)
697 | Expression::BitwiseAnd(bin)
698 | Expression::BitwiseOr(bin)
699 | Expression::BitwiseXor(bin)
700 | Expression::Concat(bin) => {
701 collect_subqueries_in_expr(&bin.left, parent_scope);
702 collect_subqueries_in_expr(&bin.right, parent_scope);
703 }
704 Expression::Like(like) | Expression::ILike(like) => {
706 collect_subqueries_in_expr(&like.left, parent_scope);
707 collect_subqueries_in_expr(&like.right, parent_scope);
708 if let Some(escape) = &like.escape {
709 collect_subqueries_in_expr(escape, parent_scope);
710 }
711 }
712 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
714 collect_subqueries_in_expr(&un.this, parent_scope);
715 }
716 Expression::Function(func) => {
717 for arg in &func.args {
718 collect_subqueries_in_expr(arg, parent_scope);
719 }
720 }
721 Expression::Case(case) => {
722 if let Some(operand) = &case.operand {
723 collect_subqueries_in_expr(operand, parent_scope);
724 }
725 for (when_expr, then_expr) in &case.whens {
726 collect_subqueries_in_expr(when_expr, parent_scope);
727 collect_subqueries_in_expr(then_expr, parent_scope);
728 }
729 if let Some(else_clause) = &case.else_ {
730 collect_subqueries_in_expr(else_clause, parent_scope);
731 }
732 }
733 Expression::Paren(paren) => {
734 collect_subqueries_in_expr(&paren.this, parent_scope);
735 }
736 Expression::Alias(alias) => {
737 collect_subqueries_in_expr(&alias.this, parent_scope);
738 }
739 _ => {}
740 }
741}
742
743pub fn walk_in_scope<'a>(
755 expression: &'a Expression,
756 bfs: bool,
757) -> impl Iterator<Item = &'a Expression> {
758 WalkInScopeIter::new(expression, bfs)
759}
760
761struct WalkInScopeIter<'a> {
763 queue: VecDeque<&'a Expression>,
764 bfs: bool,
765}
766
767impl<'a> WalkInScopeIter<'a> {
768 fn new(expression: &'a Expression, bfs: bool) -> Self {
769 let mut queue = VecDeque::new();
770 queue.push_back(expression);
771 Self { queue, bfs }
772 }
773
774 fn should_stop_at(&self, expr: &Expression, is_root: bool) -> bool {
775 if is_root {
776 return false;
777 }
778
779 if matches!(expr, Expression::Cte(_)) {
781 return true;
782 }
783
784 if let Expression::Subquery(subquery) = expr {
786 if subquery.alias.is_some() {
787 return true;
788 }
789 }
790
791 if matches!(
793 expr,
794 Expression::Select(_)
795 | Expression::Union(_)
796 | Expression::Intersect(_)
797 | Expression::Except(_)
798 ) {
799 return true;
800 }
801
802 false
803 }
804
805 fn get_children(&self, expr: &'a Expression) -> Vec<&'a Expression> {
806 let mut children = Vec::new();
807
808 match expr {
809 Expression::Select(select) => {
810 for e in &select.expressions {
812 children.push(e);
813 }
814 if let Some(from) = &select.from {
816 for table in &from.expressions {
817 if !self.should_stop_at(table, false) {
818 children.push(table);
819 }
820 }
821 }
822 for join in &select.joins {
824 if let Some(on) = &join.on {
825 children.push(on);
826 }
827 }
829 if let Some(where_clause) = &select.where_clause {
831 children.push(&where_clause.this);
832 }
833 if let Some(group_by) = &select.group_by {
835 for e in &group_by.expressions {
836 children.push(e);
837 }
838 }
839 if let Some(having) = &select.having {
841 children.push(&having.this);
842 }
843 if let Some(order_by) = &select.order_by {
845 for ord in &order_by.expressions {
846 children.push(&ord.this);
847 }
848 }
849 if let Some(limit) = &select.limit {
851 children.push(&limit.this);
852 }
853 if let Some(offset) = &select.offset {
855 children.push(&offset.this);
856 }
857 }
858 Expression::And(bin)
859 | Expression::Or(bin)
860 | Expression::Add(bin)
861 | Expression::Sub(bin)
862 | Expression::Mul(bin)
863 | Expression::Div(bin)
864 | Expression::Mod(bin)
865 | Expression::Eq(bin)
866 | Expression::Neq(bin)
867 | Expression::Lt(bin)
868 | Expression::Lte(bin)
869 | Expression::Gt(bin)
870 | Expression::Gte(bin)
871 | Expression::BitwiseAnd(bin)
872 | Expression::BitwiseOr(bin)
873 | Expression::BitwiseXor(bin)
874 | Expression::Concat(bin) => {
875 children.push(&bin.left);
876 children.push(&bin.right);
877 }
878 Expression::Like(like) | Expression::ILike(like) => {
879 children.push(&like.left);
880 children.push(&like.right);
881 if let Some(escape) = &like.escape {
882 children.push(escape);
883 }
884 }
885 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
886 children.push(&un.this);
887 }
888 Expression::Function(func) => {
889 for arg in &func.args {
890 children.push(arg);
891 }
892 }
893 Expression::AggregateFunction(agg) => {
894 for arg in &agg.args {
895 children.push(arg);
896 }
897 }
898 Expression::WindowFunction(wf) => {
899 children.push(&wf.this);
900 for e in &wf.over.partition_by {
901 children.push(e);
902 }
903 for e in &wf.over.order_by {
904 children.push(&e.this);
905 }
906 }
907 Expression::Alias(alias) => {
908 children.push(&alias.this);
909 }
910 Expression::Case(case) => {
911 if let Some(operand) = &case.operand {
912 children.push(operand);
913 }
914 for (when_expr, then_expr) in &case.whens {
915 children.push(when_expr);
916 children.push(then_expr);
917 }
918 if let Some(else_clause) = &case.else_ {
919 children.push(else_clause);
920 }
921 }
922 Expression::Paren(paren) => {
923 children.push(&paren.this);
924 }
925 Expression::Ordered(ord) => {
926 children.push(&ord.this);
927 }
928 Expression::In(in_expr) => {
929 children.push(&in_expr.this);
930 for e in &in_expr.expressions {
931 children.push(e);
932 }
933 }
935 Expression::Between(between) => {
936 children.push(&between.this);
937 children.push(&between.low);
938 children.push(&between.high);
939 }
940 Expression::IsNull(is_null) => {
941 children.push(&is_null.this);
942 }
943 Expression::Cast(cast) => {
944 children.push(&cast.this);
945 }
946 Expression::Extract(extract) => {
947 children.push(&extract.this);
948 }
949 Expression::Coalesce(coalesce) => {
950 for e in &coalesce.expressions {
951 children.push(e);
952 }
953 }
954 Expression::NullIf(nullif) => {
955 children.push(&nullif.this);
956 children.push(&nullif.expression);
957 }
958 Expression::Table(_table) => {
959 }
962 Expression::Column(_) | Expression::Literal(_) | Expression::Identifier(_) => {
963 }
965 Expression::Subquery(_) | Expression::Exists(_) => {}
967 _ => {
968 }
970 }
971
972 children
973 }
974}
975
976impl<'a> Iterator for WalkInScopeIter<'a> {
977 type Item = &'a Expression;
978
979 fn next(&mut self) -> Option<Self::Item> {
980 let expr = if self.bfs {
981 self.queue.pop_front()?
982 } else {
983 self.queue.pop_back()?
984 };
985
986 let children = self.get_children(expr);
988
989 if self.bfs {
990 for child in children {
991 if !self.should_stop_at(child, false) {
992 self.queue.push_back(child);
993 }
994 }
995 } else {
996 for child in children.into_iter().rev() {
997 if !self.should_stop_at(child, false) {
998 self.queue.push_back(child);
999 }
1000 }
1001 }
1002
1003 Some(expr)
1004 }
1005}
1006
1007pub fn find_in_scope<'a, F>(
1019 expression: &'a Expression,
1020 predicate: F,
1021 bfs: bool,
1022) -> Option<&'a Expression>
1023where
1024 F: Fn(&Expression) -> bool,
1025{
1026 walk_in_scope(expression, bfs).find(|e| predicate(e))
1027}
1028
1029pub fn find_all_in_scope<'a, F>(
1041 expression: &'a Expression,
1042 predicate: F,
1043 bfs: bool,
1044) -> Vec<&'a Expression>
1045where
1046 F: Fn(&Expression) -> bool,
1047{
1048 walk_in_scope(expression, bfs)
1049 .filter(|e| predicate(e))
1050 .collect()
1051}
1052
1053pub fn traverse_scope(expression: &Expression) -> Vec<Scope> {
1063 match expression {
1064 Expression::Select(_)
1065 | Expression::Union(_)
1066 | Expression::Intersect(_)
1067 | Expression::Except(_) => {
1068 let root = build_scope(expression);
1069 root.traverse().into_iter().cloned().collect()
1070 }
1071 _ => Vec::new(),
1072 }
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077 use super::*;
1078 use crate::parser::Parser;
1079
1080 fn parse_and_build_scope(sql: &str) -> Scope {
1081 let ast = Parser::parse_sql(sql).expect("Failed to parse SQL");
1082 build_scope(&ast[0])
1083 }
1084
1085 #[test]
1086 fn test_simple_select_scope() {
1087 let mut scope = parse_and_build_scope("SELECT a, b FROM t");
1088
1089 assert!(scope.is_root());
1090 assert!(!scope.can_be_correlated);
1091 assert!(scope.sources.contains_key("t"));
1092
1093 let columns = scope.columns();
1094 assert_eq!(columns.len(), 2);
1095 }
1096
1097 #[test]
1098 fn test_derived_table_scope() {
1099 let mut scope = parse_and_build_scope("SELECT x.a FROM (SELECT a FROM t) AS x");
1100
1101 assert!(scope.sources.contains_key("x"));
1102 assert_eq!(scope.derived_table_scopes.len(), 1);
1103
1104 let derived = &mut scope.derived_table_scopes[0];
1105 assert!(derived.is_derived_table());
1106 assert!(derived.sources.contains_key("t"));
1107 }
1108
1109 #[test]
1110 fn test_non_correlated_subquery() {
1111 let mut scope = parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s)");
1112
1113 assert_eq!(scope.subquery_scopes.len(), 1);
1114
1115 let subquery = &mut scope.subquery_scopes[0];
1116 assert!(subquery.is_subquery());
1117 assert!(subquery.can_be_correlated);
1118
1119 assert!(subquery.sources.contains_key("s"));
1121 assert!(!subquery.is_correlated_subquery());
1122 }
1123
1124 #[test]
1125 fn test_correlated_subquery() {
1126 let mut scope =
1127 parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s WHERE s.x = t.y)");
1128
1129 assert_eq!(scope.subquery_scopes.len(), 1);
1130
1131 let subquery = &mut scope.subquery_scopes[0];
1132 assert!(subquery.is_subquery());
1133 assert!(subquery.can_be_correlated);
1134
1135 let external = subquery.external_columns();
1137 assert!(!external.is_empty());
1138 assert!(external.iter().any(|c| c.table.as_deref() == Some("t")));
1139 assert!(subquery.is_correlated_subquery());
1140 }
1141
1142 #[test]
1143 fn test_cte_scope() {
1144 let scope = parse_and_build_scope("WITH cte AS (SELECT a FROM t) SELECT * FROM cte");
1145
1146 assert_eq!(scope.cte_scopes.len(), 1);
1147 assert!(scope.cte_sources.contains_key("cte"));
1148
1149 let cte = &scope.cte_scopes[0];
1150 assert!(cte.is_cte());
1151 }
1152
1153 #[test]
1154 fn test_multiple_sources() {
1155 let scope = parse_and_build_scope("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
1156
1157 assert!(scope.sources.contains_key("t"));
1158 assert!(scope.sources.contains_key("s"));
1159 assert_eq!(scope.sources.len(), 2);
1160 }
1161
1162 #[test]
1163 fn test_aliased_table() {
1164 let scope = parse_and_build_scope("SELECT x.a FROM t AS x");
1165
1166 assert!(scope.sources.contains_key("x"));
1168 assert!(!scope.sources.contains_key("t"));
1169 }
1170
1171 #[test]
1172 fn test_local_columns() {
1173 let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1174
1175 let local = scope.local_columns();
1176 assert_eq!(local.len(), 5);
1179 assert!(local.iter().all(|c| c.table.is_some()));
1180 }
1181
1182 #[test]
1183 fn test_columns_include_join_on_clause_references() {
1184 let mut scope = parse_and_build_scope(
1185 "SELECT o.total FROM orders o JOIN customers c ON c.id = o.customer_id",
1186 );
1187
1188 let cols: Vec<String> = scope
1189 .columns()
1190 .iter()
1191 .map(|c| match &c.table {
1192 Some(t) => format!("{}.{}", t, c.name),
1193 None => c.name.clone(),
1194 })
1195 .collect();
1196
1197 assert!(cols.contains(&"o.total".to_string()));
1198 assert!(cols.contains(&"c.id".to_string()));
1199 assert!(cols.contains(&"o.customer_id".to_string()));
1200 }
1201
1202 #[test]
1203 fn test_unqualified_columns() {
1204 let mut scope = parse_and_build_scope("SELECT a, b, t.c FROM t");
1205
1206 let unqualified = scope.unqualified_columns();
1207 assert_eq!(unqualified.len(), 2);
1209 assert!(unqualified.iter().all(|c| c.table.is_none()));
1210 }
1211
1212 #[test]
1213 fn test_source_columns() {
1214 let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1215
1216 let t_cols = scope.source_columns("t");
1217 assert!(t_cols.len() >= 2);
1219 assert!(t_cols.iter().all(|c| c.table.as_deref() == Some("t")));
1220
1221 let s_cols = scope.source_columns("s");
1222 assert!(s_cols.len() >= 1);
1224 assert!(s_cols.iter().all(|c| c.table.as_deref() == Some("s")));
1225 }
1226
1227 #[test]
1228 fn test_rename_source() {
1229 let mut scope = parse_and_build_scope("SELECT a FROM t");
1230
1231 assert!(scope.sources.contains_key("t"));
1232 scope.rename_source("t", "new_name".to_string());
1233 assert!(!scope.sources.contains_key("t"));
1234 assert!(scope.sources.contains_key("new_name"));
1235 }
1236
1237 #[test]
1238 fn test_remove_source() {
1239 let mut scope = parse_and_build_scope("SELECT a FROM t");
1240
1241 assert!(scope.sources.contains_key("t"));
1242 scope.remove_source("t");
1243 assert!(!scope.sources.contains_key("t"));
1244 }
1245
1246 #[test]
1247 fn test_walk_in_scope() {
1248 let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1249 let expr = &ast[0];
1250
1251 let walked: Vec<_> = walk_in_scope(expr, true).collect();
1253 assert!(!walked.is_empty());
1254
1255 assert!(walked.iter().any(|e| matches!(e, Expression::Select(_))));
1257 assert!(walked.iter().any(|e| matches!(e, Expression::Column(_))));
1259 }
1260
1261 #[test]
1262 fn test_find_in_scope() {
1263 let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1264 let expr = &ast[0];
1265
1266 let found = find_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1268 assert!(found.is_some());
1269 assert!(matches!(found.unwrap(), Expression::Column(_)));
1270 }
1271
1272 #[test]
1273 fn test_find_all_in_scope() {
1274 let ast = Parser::parse_sql("SELECT a, b, c FROM t").expect("Failed to parse");
1275 let expr = &ast[0];
1276
1277 let found = find_all_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1279 assert_eq!(found.len(), 3);
1280 }
1281
1282 #[test]
1283 fn test_traverse_scope() {
1284 let ast =
1285 Parser::parse_sql("SELECT a FROM (SELECT b FROM t) AS x").expect("Failed to parse");
1286 let expr = &ast[0];
1287
1288 let scopes = traverse_scope(expr);
1289 assert!(!scopes.is_empty());
1292 assert!(scopes.iter().any(|s| s.is_root()));
1294 }
1295
1296 #[test]
1297 fn test_branch_with_options() {
1298 let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1299 let scope = build_scope(&ast[0]);
1300
1301 let child = scope.branch_with_options(
1302 ast[0].clone(),
1303 ScopeType::Subquery, None,
1305 None,
1306 Some(vec!["col1".to_string(), "col2".to_string()]),
1307 );
1308
1309 assert_eq!(child.outer_columns, vec!["col1", "col2"]);
1310 assert!(child.can_be_correlated); }
1312
1313 #[test]
1314 fn test_is_udtf() {
1315 let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1316 let scope = Scope::new(ast[0].clone());
1317 assert!(!scope.is_udtf());
1318
1319 let root = build_scope(&ast[0]);
1320 let udtf_scope = root.branch(ast[0].clone(), ScopeType::Udtf);
1321 assert!(udtf_scope.is_udtf());
1322 }
1323
1324 #[test]
1325 fn test_is_union() {
1326 let scope = parse_and_build_scope("SELECT a FROM t UNION SELECT b FROM s");
1327
1328 assert!(scope.is_root());
1329 assert_eq!(scope.union_scopes.len(), 2);
1330 assert!(scope.union_scopes[0].is_union());
1332 assert!(scope.union_scopes[1].is_union());
1333 }
1334
1335 #[test]
1336 fn test_clear_cache() {
1337 let mut scope = parse_and_build_scope("SELECT t.a FROM t");
1338
1339 let _ = scope.columns();
1341 assert!(scope.columns_cache.is_some());
1342
1343 scope.clear_cache();
1345 assert!(scope.columns_cache.is_none());
1346 assert!(scope.external_columns_cache.is_none());
1347 }
1348
1349 #[test]
1350 fn test_scope_traverse() {
1351 let scope = parse_and_build_scope(
1352 "WITH cte AS (SELECT a FROM t) SELECT * FROM cte WHERE EXISTS (SELECT b FROM s)",
1353 );
1354
1355 let traversed = scope.traverse();
1356 assert!(traversed.len() >= 3);
1358 }
1359}