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 output_columns(&self) -> Vec<String> {
249 crate::ast_transforms::get_output_column_names(&self.expression)
250 }
251
252 pub fn source_names(&self) -> HashSet<String> {
254 let mut names: HashSet<String> = self.sources.keys().cloned().collect();
255 names.extend(self.cte_sources.keys().cloned());
256 names
257 }
258
259 pub fn external_columns(&mut self) -> Vec<ColumnRef> {
261 if self.external_columns_cache.is_some() {
262 return self.external_columns_cache.clone().unwrap();
263 }
264
265 let source_names = self.source_names();
266 let columns = self.columns().to_vec();
267
268 let external: Vec<ColumnRef> = columns
269 .into_iter()
270 .filter(|col| {
271 match &col.table {
273 Some(table) => !source_names.contains(table),
274 None => false, }
276 })
277 .collect();
278
279 self.external_columns_cache = Some(external.clone());
280 external
281 }
282
283 pub fn local_columns(&mut self) -> Vec<ColumnRef> {
285 let external_set: HashSet<_> = self.external_columns().into_iter().collect();
286 let columns = self.columns().to_vec();
287
288 columns
289 .into_iter()
290 .filter(|col| !external_set.contains(col))
291 .collect()
292 }
293
294 pub fn unqualified_columns(&mut self) -> Vec<ColumnRef> {
296 self.columns()
297 .iter()
298 .filter(|c| c.table.is_none())
299 .cloned()
300 .collect()
301 }
302
303 pub fn source_columns(&mut self, source_name: &str) -> Vec<ColumnRef> {
305 self.columns()
306 .iter()
307 .filter(|col| col.table.as_deref() == Some(source_name))
308 .cloned()
309 .collect()
310 }
311
312 pub fn is_correlated_subquery(&mut self) -> bool {
318 self.can_be_correlated && !self.external_columns().is_empty()
319 }
320
321 pub fn is_subquery(&self) -> bool {
323 self.scope_type == ScopeType::Subquery
324 }
325
326 pub fn is_derived_table(&self) -> bool {
328 self.scope_type == ScopeType::DerivedTable
329 }
330
331 pub fn is_cte(&self) -> bool {
333 self.scope_type == ScopeType::Cte
334 }
335
336 pub fn is_root(&self) -> bool {
338 self.scope_type == ScopeType::Root
339 }
340
341 pub fn is_udtf(&self) -> bool {
343 self.scope_type == ScopeType::Udtf
344 }
345
346 pub fn is_union(&self) -> bool {
348 self.scope_type == ScopeType::SetOperation
349 }
350
351 pub fn traverse(&self) -> Vec<&Scope> {
353 let mut result = Vec::new();
354 self.traverse_impl(&mut result);
355 result
356 }
357
358 fn traverse_impl<'a>(&'a self, result: &mut Vec<&'a Scope>) {
359 for scope in &self.cte_scopes {
361 scope.traverse_impl(result);
362 }
363 for scope in &self.union_scopes {
364 scope.traverse_impl(result);
365 }
366 for scope in &self.table_scopes {
367 scope.traverse_impl(result);
368 }
369 for scope in &self.subquery_scopes {
370 scope.traverse_impl(result);
371 }
372 result.push(self);
374 }
375
376 pub fn ref_count(&self) -> HashMap<usize, usize> {
378 let mut counts: HashMap<usize, usize> = HashMap::new();
379
380 for scope in self.traverse() {
381 for (_, source_info) in scope.sources.iter() {
382 if source_info.is_scope {
383 let id = &source_info.expression as *const _ as usize;
384 *counts.entry(id).or_insert(0) += 1;
385 }
386 }
387 }
388
389 counts
390 }
391}
392
393fn collect_columns(expr: &Expression, columns: &mut Vec<ColumnRef>) {
395 match expr {
396 Expression::Column(col) => {
397 columns.push(ColumnRef {
398 table: col.table.as_ref().map(|t| t.name.clone()),
399 name: col.name.name.clone(),
400 });
401 }
402 Expression::Select(select) => {
403 for e in &select.expressions {
405 collect_columns(e, columns);
406 }
407 for join in &select.joins {
409 if let Some(on) = &join.on {
410 collect_columns(on, columns);
411 }
412 if let Some(match_condition) = &join.match_condition {
413 collect_columns(match_condition, columns);
414 }
415 }
416 if let Some(where_clause) = &select.where_clause {
418 collect_columns(&where_clause.this, columns);
419 }
420 if let Some(having) = &select.having {
422 collect_columns(&having.this, columns);
423 }
424 if let Some(order_by) = &select.order_by {
426 for ord in &order_by.expressions {
427 collect_columns(&ord.this, columns);
428 }
429 }
430 if let Some(group_by) = &select.group_by {
432 for e in &group_by.expressions {
433 collect_columns(e, columns);
434 }
435 }
436 }
439 Expression::And(bin)
441 | Expression::Or(bin)
442 | Expression::Add(bin)
443 | Expression::Sub(bin)
444 | Expression::Mul(bin)
445 | Expression::Div(bin)
446 | Expression::Mod(bin)
447 | Expression::Eq(bin)
448 | Expression::Neq(bin)
449 | Expression::Lt(bin)
450 | Expression::Lte(bin)
451 | Expression::Gt(bin)
452 | Expression::Gte(bin)
453 | Expression::BitwiseAnd(bin)
454 | Expression::BitwiseOr(bin)
455 | Expression::BitwiseXor(bin)
456 | Expression::Concat(bin) => {
457 collect_columns(&bin.left, columns);
458 collect_columns(&bin.right, columns);
459 }
460 Expression::Like(like) | Expression::ILike(like) => {
462 collect_columns(&like.left, columns);
463 collect_columns(&like.right, columns);
464 if let Some(escape) = &like.escape {
465 collect_columns(escape, columns);
466 }
467 }
468 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
470 collect_columns(&un.this, columns);
471 }
472 Expression::Function(func) => {
473 for arg in &func.args {
474 collect_columns(arg, columns);
475 }
476 }
477 Expression::AggregateFunction(agg) => {
478 for arg in &agg.args {
479 collect_columns(arg, columns);
480 }
481 }
482 Expression::WindowFunction(wf) => {
483 collect_columns(&wf.this, columns);
484 for e in &wf.over.partition_by {
485 collect_columns(e, columns);
486 }
487 for e in &wf.over.order_by {
488 collect_columns(&e.this, columns);
489 }
490 }
491 Expression::Alias(alias) => {
492 collect_columns(&alias.this, columns);
493 }
494 Expression::Case(case) => {
495 if let Some(operand) = &case.operand {
496 collect_columns(operand, columns);
497 }
498 for (when_expr, then_expr) in &case.whens {
499 collect_columns(when_expr, columns);
500 collect_columns(then_expr, columns);
501 }
502 if let Some(else_clause) = &case.else_ {
503 collect_columns(else_clause, columns);
504 }
505 }
506 Expression::Paren(paren) => {
507 collect_columns(&paren.this, columns);
508 }
509 Expression::Ordered(ord) => {
510 collect_columns(&ord.this, columns);
511 }
512 Expression::In(in_expr) => {
513 collect_columns(&in_expr.this, columns);
514 for e in &in_expr.expressions {
515 collect_columns(e, columns);
516 }
517 }
519 Expression::Between(between) => {
520 collect_columns(&between.this, columns);
521 collect_columns(&between.low, columns);
522 collect_columns(&between.high, columns);
523 }
524 Expression::IsNull(is_null) => {
525 collect_columns(&is_null.this, columns);
526 }
527 Expression::Cast(cast) => {
528 collect_columns(&cast.this, columns);
529 }
530 Expression::Extract(extract) => {
531 collect_columns(&extract.this, columns);
532 }
533 Expression::Exists(_) | Expression::Subquery(_) => {
534 }
536 _ => {
537 }
539 }
540}
541
542pub fn build_scope(expression: &Expression) -> Scope {
547 let mut root = Scope::new(expression.clone());
548 build_scope_impl(expression, &mut root);
549 root
550}
551
552fn build_scope_impl(expression: &Expression, current_scope: &mut Scope) {
553 match expression {
554 Expression::Select(select) => {
555 if let Some(with) = &select.with {
557 for cte in &with.ctes {
558 let cte_name = cte.alias.name.clone();
559 let mut cte_scope = current_scope
560 .branch(Expression::Cte(Box::new(cte.clone())), ScopeType::Cte);
561 build_scope_impl(&cte.this, &mut cte_scope);
562 current_scope.add_cte_source(cte_name, Expression::Cte(Box::new(cte.clone())));
563 current_scope.cte_scopes.push(cte_scope);
564 }
565 }
566
567 if let Some(from) = &select.from {
569 for table in &from.expressions {
570 add_table_to_scope(table, current_scope);
571 }
572 }
573
574 for join in &select.joins {
576 add_table_to_scope(&join.this, current_scope);
577 }
578
579 collect_subqueries(expression, current_scope);
581 }
582 Expression::Union(union) => {
583 let mut left_scope = current_scope.branch(union.left.clone(), ScopeType::SetOperation);
584 build_scope_impl(&union.left, &mut left_scope);
585
586 let mut right_scope =
587 current_scope.branch(union.right.clone(), ScopeType::SetOperation);
588 build_scope_impl(&union.right, &mut right_scope);
589
590 current_scope.union_scopes.push(left_scope);
591 current_scope.union_scopes.push(right_scope);
592 }
593 Expression::Intersect(intersect) => {
594 let mut left_scope =
595 current_scope.branch(intersect.left.clone(), ScopeType::SetOperation);
596 build_scope_impl(&intersect.left, &mut left_scope);
597
598 let mut right_scope =
599 current_scope.branch(intersect.right.clone(), ScopeType::SetOperation);
600 build_scope_impl(&intersect.right, &mut right_scope);
601
602 current_scope.union_scopes.push(left_scope);
603 current_scope.union_scopes.push(right_scope);
604 }
605 Expression::Except(except) => {
606 let mut left_scope = current_scope.branch(except.left.clone(), ScopeType::SetOperation);
607 build_scope_impl(&except.left, &mut left_scope);
608
609 let mut right_scope =
610 current_scope.branch(except.right.clone(), ScopeType::SetOperation);
611 build_scope_impl(&except.right, &mut right_scope);
612
613 current_scope.union_scopes.push(left_scope);
614 current_scope.union_scopes.push(right_scope);
615 }
616 _ => {}
617 }
618}
619
620fn add_table_to_scope(expr: &Expression, scope: &mut Scope) {
621 match expr {
622 Expression::Table(table) => {
623 let name = table
624 .alias
625 .as_ref()
626 .map(|a| a.name.clone())
627 .unwrap_or_else(|| table.name.name.clone());
628 let cte_source = if table.schema.is_none() && table.catalog.is_none() {
629 scope.cte_sources.get(&table.name.name).or_else(|| {
630 scope
631 .cte_sources
632 .iter()
633 .find(|(cte_name, _)| cte_name.eq_ignore_ascii_case(&table.name.name))
634 .map(|(_, source)| source)
635 })
636 } else {
637 None
638 };
639
640 if let Some(source) = cte_source {
641 scope.add_source(name, source.expression.clone(), true);
642 } else {
643 scope.add_source(name, expr.clone(), false);
644 }
645 }
646 Expression::Subquery(subquery) => {
647 let name = subquery
648 .alias
649 .as_ref()
650 .map(|a| a.name.clone())
651 .unwrap_or_default();
652
653 let mut derived_scope = scope.branch(subquery.this.clone(), ScopeType::DerivedTable);
654 build_scope_impl(&subquery.this, &mut derived_scope);
655
656 scope.add_source(name.clone(), expr.clone(), true);
657 scope.derived_table_scopes.push(derived_scope);
658 }
659 Expression::Paren(paren) => {
660 add_table_to_scope(&paren.this, scope);
661 }
662 _ => {}
663 }
664}
665
666fn collect_subqueries(expr: &Expression, parent_scope: &mut Scope) {
667 match expr {
668 Expression::Select(select) => {
669 if let Some(where_clause) = &select.where_clause {
671 collect_subqueries_in_expr(&where_clause.this, parent_scope);
672 }
673 for e in &select.expressions {
675 collect_subqueries_in_expr(e, parent_scope);
676 }
677 if let Some(having) = &select.having {
679 collect_subqueries_in_expr(&having.this, parent_scope);
680 }
681 }
682 _ => {}
683 }
684}
685
686fn collect_subqueries_in_expr(expr: &Expression, parent_scope: &mut Scope) {
687 match expr {
688 Expression::Subquery(subquery) if subquery.alias.is_none() => {
689 let mut sub_scope = parent_scope.branch(subquery.this.clone(), ScopeType::Subquery);
691 build_scope_impl(&subquery.this, &mut sub_scope);
692 parent_scope.subquery_scopes.push(sub_scope);
693 }
694 Expression::In(in_expr) => {
695 collect_subqueries_in_expr(&in_expr.this, parent_scope);
696 if let Some(query) = &in_expr.query {
697 let mut sub_scope = parent_scope.branch(query.clone(), ScopeType::Subquery);
698 build_scope_impl(query, &mut sub_scope);
699 parent_scope.subquery_scopes.push(sub_scope);
700 }
701 }
702 Expression::Exists(exists) => {
703 let mut sub_scope = parent_scope.branch(exists.this.clone(), ScopeType::Subquery);
704 build_scope_impl(&exists.this, &mut sub_scope);
705 parent_scope.subquery_scopes.push(sub_scope);
706 }
707 Expression::And(bin)
709 | Expression::Or(bin)
710 | Expression::Add(bin)
711 | Expression::Sub(bin)
712 | Expression::Mul(bin)
713 | Expression::Div(bin)
714 | Expression::Mod(bin)
715 | Expression::Eq(bin)
716 | Expression::Neq(bin)
717 | Expression::Lt(bin)
718 | Expression::Lte(bin)
719 | Expression::Gt(bin)
720 | Expression::Gte(bin)
721 | Expression::BitwiseAnd(bin)
722 | Expression::BitwiseOr(bin)
723 | Expression::BitwiseXor(bin)
724 | Expression::Concat(bin) => {
725 collect_subqueries_in_expr(&bin.left, parent_scope);
726 collect_subqueries_in_expr(&bin.right, parent_scope);
727 }
728 Expression::Like(like) | Expression::ILike(like) => {
730 collect_subqueries_in_expr(&like.left, parent_scope);
731 collect_subqueries_in_expr(&like.right, parent_scope);
732 if let Some(escape) = &like.escape {
733 collect_subqueries_in_expr(escape, parent_scope);
734 }
735 }
736 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
738 collect_subqueries_in_expr(&un.this, parent_scope);
739 }
740 Expression::Function(func) => {
741 for arg in &func.args {
742 collect_subqueries_in_expr(arg, parent_scope);
743 }
744 }
745 Expression::Case(case) => {
746 if let Some(operand) = &case.operand {
747 collect_subqueries_in_expr(operand, parent_scope);
748 }
749 for (when_expr, then_expr) in &case.whens {
750 collect_subqueries_in_expr(when_expr, parent_scope);
751 collect_subqueries_in_expr(then_expr, parent_scope);
752 }
753 if let Some(else_clause) = &case.else_ {
754 collect_subqueries_in_expr(else_clause, parent_scope);
755 }
756 }
757 Expression::Paren(paren) => {
758 collect_subqueries_in_expr(&paren.this, parent_scope);
759 }
760 Expression::Alias(alias) => {
761 collect_subqueries_in_expr(&alias.this, parent_scope);
762 }
763 _ => {}
764 }
765}
766
767pub fn walk_in_scope<'a>(
779 expression: &'a Expression,
780 bfs: bool,
781) -> impl Iterator<Item = &'a Expression> {
782 WalkInScopeIter::new(expression, bfs)
783}
784
785struct WalkInScopeIter<'a> {
787 queue: VecDeque<&'a Expression>,
788 bfs: bool,
789}
790
791impl<'a> WalkInScopeIter<'a> {
792 fn new(expression: &'a Expression, bfs: bool) -> Self {
793 let mut queue = VecDeque::new();
794 queue.push_back(expression);
795 Self { queue, bfs }
796 }
797
798 fn should_stop_at(&self, expr: &Expression, is_root: bool) -> bool {
799 if is_root {
800 return false;
801 }
802
803 if matches!(expr, Expression::Cte(_)) {
805 return true;
806 }
807
808 if let Expression::Subquery(subquery) = expr {
810 if subquery.alias.is_some() {
811 return true;
812 }
813 }
814
815 if matches!(
817 expr,
818 Expression::Select(_)
819 | Expression::Union(_)
820 | Expression::Intersect(_)
821 | Expression::Except(_)
822 ) {
823 return true;
824 }
825
826 false
827 }
828
829 fn get_children(&self, expr: &'a Expression) -> Vec<&'a Expression> {
830 let mut children = Vec::new();
831
832 match expr {
833 Expression::Select(select) => {
834 for e in &select.expressions {
836 children.push(e);
837 }
838 if let Some(from) = &select.from {
840 for table in &from.expressions {
841 if !self.should_stop_at(table, false) {
842 children.push(table);
843 }
844 }
845 }
846 for join in &select.joins {
848 if let Some(on) = &join.on {
849 children.push(on);
850 }
851 }
853 if let Some(where_clause) = &select.where_clause {
855 children.push(&where_clause.this);
856 }
857 if let Some(group_by) = &select.group_by {
859 for e in &group_by.expressions {
860 children.push(e);
861 }
862 }
863 if let Some(having) = &select.having {
865 children.push(&having.this);
866 }
867 if let Some(order_by) = &select.order_by {
869 for ord in &order_by.expressions {
870 children.push(&ord.this);
871 }
872 }
873 if let Some(limit) = &select.limit {
875 children.push(&limit.this);
876 }
877 if let Some(offset) = &select.offset {
879 children.push(&offset.this);
880 }
881 }
882 Expression::And(bin)
883 | Expression::Or(bin)
884 | Expression::Add(bin)
885 | Expression::Sub(bin)
886 | Expression::Mul(bin)
887 | Expression::Div(bin)
888 | Expression::Mod(bin)
889 | Expression::Eq(bin)
890 | Expression::Neq(bin)
891 | Expression::Lt(bin)
892 | Expression::Lte(bin)
893 | Expression::Gt(bin)
894 | Expression::Gte(bin)
895 | Expression::BitwiseAnd(bin)
896 | Expression::BitwiseOr(bin)
897 | Expression::BitwiseXor(bin)
898 | Expression::Concat(bin) => {
899 children.push(&bin.left);
900 children.push(&bin.right);
901 }
902 Expression::Like(like) | Expression::ILike(like) => {
903 children.push(&like.left);
904 children.push(&like.right);
905 if let Some(escape) = &like.escape {
906 children.push(escape);
907 }
908 }
909 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
910 children.push(&un.this);
911 }
912 Expression::Function(func) => {
913 for arg in &func.args {
914 children.push(arg);
915 }
916 }
917 Expression::AggregateFunction(agg) => {
918 for arg in &agg.args {
919 children.push(arg);
920 }
921 }
922 Expression::WindowFunction(wf) => {
923 children.push(&wf.this);
924 for e in &wf.over.partition_by {
925 children.push(e);
926 }
927 for e in &wf.over.order_by {
928 children.push(&e.this);
929 }
930 }
931 Expression::Alias(alias) => {
932 children.push(&alias.this);
933 }
934 Expression::Case(case) => {
935 if let Some(operand) = &case.operand {
936 children.push(operand);
937 }
938 for (when_expr, then_expr) in &case.whens {
939 children.push(when_expr);
940 children.push(then_expr);
941 }
942 if let Some(else_clause) = &case.else_ {
943 children.push(else_clause);
944 }
945 }
946 Expression::Paren(paren) => {
947 children.push(&paren.this);
948 }
949 Expression::Ordered(ord) => {
950 children.push(&ord.this);
951 }
952 Expression::In(in_expr) => {
953 children.push(&in_expr.this);
954 for e in &in_expr.expressions {
955 children.push(e);
956 }
957 }
959 Expression::Between(between) => {
960 children.push(&between.this);
961 children.push(&between.low);
962 children.push(&between.high);
963 }
964 Expression::IsNull(is_null) => {
965 children.push(&is_null.this);
966 }
967 Expression::Cast(cast) => {
968 children.push(&cast.this);
969 }
970 Expression::Extract(extract) => {
971 children.push(&extract.this);
972 }
973 Expression::Coalesce(coalesce) => {
974 for e in &coalesce.expressions {
975 children.push(e);
976 }
977 }
978 Expression::NullIf(nullif) => {
979 children.push(&nullif.this);
980 children.push(&nullif.expression);
981 }
982 Expression::Table(_table) => {
983 }
986 Expression::Column(_) | Expression::Literal(_) | Expression::Identifier(_) => {
987 }
989 Expression::Subquery(_) | Expression::Exists(_) => {}
991 _ => {
992 }
994 }
995
996 children
997 }
998}
999
1000impl<'a> Iterator for WalkInScopeIter<'a> {
1001 type Item = &'a Expression;
1002
1003 fn next(&mut self) -> Option<Self::Item> {
1004 let expr = if self.bfs {
1005 self.queue.pop_front()?
1006 } else {
1007 self.queue.pop_back()?
1008 };
1009
1010 let children = self.get_children(expr);
1012
1013 if self.bfs {
1014 for child in children {
1015 if !self.should_stop_at(child, false) {
1016 self.queue.push_back(child);
1017 }
1018 }
1019 } else {
1020 for child in children.into_iter().rev() {
1021 if !self.should_stop_at(child, false) {
1022 self.queue.push_back(child);
1023 }
1024 }
1025 }
1026
1027 Some(expr)
1028 }
1029}
1030
1031pub fn find_in_scope<'a, F>(
1043 expression: &'a Expression,
1044 predicate: F,
1045 bfs: bool,
1046) -> Option<&'a Expression>
1047where
1048 F: Fn(&Expression) -> bool,
1049{
1050 walk_in_scope(expression, bfs).find(|e| predicate(e))
1051}
1052
1053pub fn find_all_in_scope<'a, F>(
1065 expression: &'a Expression,
1066 predicate: F,
1067 bfs: bool,
1068) -> Vec<&'a Expression>
1069where
1070 F: Fn(&Expression) -> bool,
1071{
1072 walk_in_scope(expression, bfs)
1073 .filter(|e| predicate(e))
1074 .collect()
1075}
1076
1077pub fn traverse_scope(expression: &Expression) -> Vec<Scope> {
1087 match expression {
1088 Expression::Select(_)
1089 | Expression::Union(_)
1090 | Expression::Intersect(_)
1091 | Expression::Except(_) => {
1092 let root = build_scope(expression);
1093 root.traverse().into_iter().cloned().collect()
1094 }
1095 _ => Vec::new(),
1096 }
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101 use super::*;
1102 use crate::parser::Parser;
1103
1104 fn parse_and_build_scope(sql: &str) -> Scope {
1105 let ast = Parser::parse_sql(sql).expect("Failed to parse SQL");
1106 build_scope(&ast[0])
1107 }
1108
1109 #[test]
1110 fn test_simple_select_scope() {
1111 let mut scope = parse_and_build_scope("SELECT a, b FROM t");
1112
1113 assert!(scope.is_root());
1114 assert!(!scope.can_be_correlated);
1115 assert!(scope.sources.contains_key("t"));
1116
1117 let columns = scope.columns();
1118 assert_eq!(columns.len(), 2);
1119 }
1120
1121 #[test]
1122 fn test_derived_table_scope() {
1123 let mut scope = parse_and_build_scope("SELECT x.a FROM (SELECT a FROM t) AS x");
1124
1125 assert!(scope.sources.contains_key("x"));
1126 assert_eq!(scope.derived_table_scopes.len(), 1);
1127
1128 let derived = &mut scope.derived_table_scopes[0];
1129 assert!(derived.is_derived_table());
1130 assert!(derived.sources.contains_key("t"));
1131 }
1132
1133 #[test]
1134 fn test_non_correlated_subquery() {
1135 let mut scope = parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s)");
1136
1137 assert_eq!(scope.subquery_scopes.len(), 1);
1138
1139 let subquery = &mut scope.subquery_scopes[0];
1140 assert!(subquery.is_subquery());
1141 assert!(subquery.can_be_correlated);
1142
1143 assert!(subquery.sources.contains_key("s"));
1145 assert!(!subquery.is_correlated_subquery());
1146 }
1147
1148 #[test]
1149 fn test_correlated_subquery() {
1150 let mut scope =
1151 parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s WHERE s.x = t.y)");
1152
1153 assert_eq!(scope.subquery_scopes.len(), 1);
1154
1155 let subquery = &mut scope.subquery_scopes[0];
1156 assert!(subquery.is_subquery());
1157 assert!(subquery.can_be_correlated);
1158
1159 let external = subquery.external_columns();
1161 assert!(!external.is_empty());
1162 assert!(external.iter().any(|c| c.table.as_deref() == Some("t")));
1163 assert!(subquery.is_correlated_subquery());
1164 }
1165
1166 #[test]
1167 fn test_cte_scope() {
1168 let scope = parse_and_build_scope("WITH cte AS (SELECT a FROM t) SELECT * FROM cte");
1169
1170 assert_eq!(scope.cte_scopes.len(), 1);
1171 assert!(scope.cte_sources.contains_key("cte"));
1172
1173 let cte = &scope.cte_scopes[0];
1174 assert!(cte.is_cte());
1175 }
1176
1177 #[test]
1178 fn test_multiple_sources() {
1179 let scope = parse_and_build_scope("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
1180
1181 assert!(scope.sources.contains_key("t"));
1182 assert!(scope.sources.contains_key("s"));
1183 assert_eq!(scope.sources.len(), 2);
1184 }
1185
1186 #[test]
1187 fn test_aliased_table() {
1188 let scope = parse_and_build_scope("SELECT x.a FROM t AS x");
1189
1190 assert!(scope.sources.contains_key("x"));
1192 assert!(!scope.sources.contains_key("t"));
1193 }
1194
1195 #[test]
1196 fn test_local_columns() {
1197 let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1198
1199 let local = scope.local_columns();
1200 assert_eq!(local.len(), 5);
1203 assert!(local.iter().all(|c| c.table.is_some()));
1204 }
1205
1206 #[test]
1207 fn test_columns_include_join_on_clause_references() {
1208 let mut scope = parse_and_build_scope(
1209 "SELECT o.total FROM orders o JOIN customers c ON c.id = o.customer_id",
1210 );
1211
1212 let cols: Vec<String> = scope
1213 .columns()
1214 .iter()
1215 .map(|c| match &c.table {
1216 Some(t) => format!("{}.{}", t, c.name),
1217 None => c.name.clone(),
1218 })
1219 .collect();
1220
1221 assert!(cols.contains(&"o.total".to_string()));
1222 assert!(cols.contains(&"c.id".to_string()));
1223 assert!(cols.contains(&"o.customer_id".to_string()));
1224 }
1225
1226 #[test]
1227 fn test_unqualified_columns() {
1228 let mut scope = parse_and_build_scope("SELECT a, b, t.c FROM t");
1229
1230 let unqualified = scope.unqualified_columns();
1231 assert_eq!(unqualified.len(), 2);
1233 assert!(unqualified.iter().all(|c| c.table.is_none()));
1234 }
1235
1236 #[test]
1237 fn test_source_columns() {
1238 let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1239
1240 let t_cols = scope.source_columns("t");
1241 assert!(t_cols.len() >= 2);
1243 assert!(t_cols.iter().all(|c| c.table.as_deref() == Some("t")));
1244
1245 let s_cols = scope.source_columns("s");
1246 assert!(s_cols.len() >= 1);
1248 assert!(s_cols.iter().all(|c| c.table.as_deref() == Some("s")));
1249 }
1250
1251 #[test]
1252 fn test_rename_source() {
1253 let mut scope = parse_and_build_scope("SELECT a FROM t");
1254
1255 assert!(scope.sources.contains_key("t"));
1256 scope.rename_source("t", "new_name".to_string());
1257 assert!(!scope.sources.contains_key("t"));
1258 assert!(scope.sources.contains_key("new_name"));
1259 }
1260
1261 #[test]
1262 fn test_remove_source() {
1263 let mut scope = parse_and_build_scope("SELECT a FROM t");
1264
1265 assert!(scope.sources.contains_key("t"));
1266 scope.remove_source("t");
1267 assert!(!scope.sources.contains_key("t"));
1268 }
1269
1270 #[test]
1271 fn test_walk_in_scope() {
1272 let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1273 let expr = &ast[0];
1274
1275 let walked: Vec<_> = walk_in_scope(expr, true).collect();
1277 assert!(!walked.is_empty());
1278
1279 assert!(walked.iter().any(|e| matches!(e, Expression::Select(_))));
1281 assert!(walked.iter().any(|e| matches!(e, Expression::Column(_))));
1283 }
1284
1285 #[test]
1286 fn test_find_in_scope() {
1287 let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1288 let expr = &ast[0];
1289
1290 let found = find_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1292 assert!(found.is_some());
1293 assert!(matches!(found.unwrap(), Expression::Column(_)));
1294 }
1295
1296 #[test]
1297 fn test_find_all_in_scope() {
1298 let ast = Parser::parse_sql("SELECT a, b, c FROM t").expect("Failed to parse");
1299 let expr = &ast[0];
1300
1301 let found = find_all_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1303 assert_eq!(found.len(), 3);
1304 }
1305
1306 #[test]
1307 fn test_traverse_scope() {
1308 let ast =
1309 Parser::parse_sql("SELECT a FROM (SELECT b FROM t) AS x").expect("Failed to parse");
1310 let expr = &ast[0];
1311
1312 let scopes = traverse_scope(expr);
1313 assert!(!scopes.is_empty());
1316 assert!(scopes.iter().any(|s| s.is_root()));
1318 }
1319
1320 #[test]
1321 fn test_branch_with_options() {
1322 let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1323 let scope = build_scope(&ast[0]);
1324
1325 let child = scope.branch_with_options(
1326 ast[0].clone(),
1327 ScopeType::Subquery, None,
1329 None,
1330 Some(vec!["col1".to_string(), "col2".to_string()]),
1331 );
1332
1333 assert_eq!(child.outer_columns, vec!["col1", "col2"]);
1334 assert!(child.can_be_correlated); }
1336
1337 #[test]
1338 fn test_is_udtf() {
1339 let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1340 let scope = Scope::new(ast[0].clone());
1341 assert!(!scope.is_udtf());
1342
1343 let root = build_scope(&ast[0]);
1344 let udtf_scope = root.branch(ast[0].clone(), ScopeType::Udtf);
1345 assert!(udtf_scope.is_udtf());
1346 }
1347
1348 #[test]
1349 fn test_is_union() {
1350 let scope = parse_and_build_scope("SELECT a FROM t UNION SELECT b FROM s");
1351
1352 assert!(scope.is_root());
1353 assert_eq!(scope.union_scopes.len(), 2);
1354 assert!(scope.union_scopes[0].is_union());
1356 assert!(scope.union_scopes[1].is_union());
1357 }
1358
1359 #[test]
1360 fn test_union_output_columns() {
1361 let scope = parse_and_build_scope(
1362 "SELECT id, name FROM customers UNION ALL SELECT id, name FROM employees",
1363 );
1364 assert_eq!(scope.output_columns(), vec!["id", "name"]);
1365 }
1366
1367 #[test]
1368 fn test_clear_cache() {
1369 let mut scope = parse_and_build_scope("SELECT t.a FROM t");
1370
1371 let _ = scope.columns();
1373 assert!(scope.columns_cache.is_some());
1374
1375 scope.clear_cache();
1377 assert!(scope.columns_cache.is_none());
1378 assert!(scope.external_columns_cache.is_none());
1379 }
1380
1381 #[test]
1382 fn test_scope_traverse() {
1383 let scope = parse_and_build_scope(
1384 "WITH cte AS (SELECT a FROM t) SELECT * FROM cte WHERE EXISTS (SELECT b FROM s)",
1385 );
1386
1387 let traversed = scope.traverse();
1388 assert!(traversed.len() >= 3);
1390 }
1391}