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, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum SourceKind {
37 Root,
39 Table,
41 DerivedTable,
43 Cte,
45 Virtual,
47 Unknown,
49}
50
51impl Default for SourceKind {
52 fn default() -> Self {
53 Self::Unknown
54 }
55}
56
57#[derive(Debug, Clone)]
59pub struct SourceInfo {
60 pub expression: Expression,
62 pub is_scope: bool,
64 pub kind: SourceKind,
66 pub alias: Option<String>,
68 pub lineage_name: Option<String>,
70}
71
72impl SourceInfo {
73 pub fn new(expression: Expression, is_scope: bool, kind: SourceKind) -> Self {
74 Self {
75 expression,
76 is_scope,
77 kind,
78 alias: None,
79 lineage_name: None,
80 }
81 }
82
83 pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
84 self.alias = Some(alias.into());
85 self
86 }
87
88 pub fn with_lineage_name(mut self, lineage_name: impl Into<String>) -> Self {
89 self.lineage_name = Some(lineage_name.into());
90 self
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Hash)]
96pub struct ColumnRef {
97 pub table: Option<String>,
99 pub name: String,
101}
102
103#[derive(Debug, Clone)]
108pub struct Scope {
109 pub expression: Expression,
111
112 pub scope_type: ScopeType,
114
115 pub sources: HashMap<String, SourceInfo>,
117
118 pub lateral_sources: HashMap<String, SourceInfo>,
120
121 pub cte_sources: HashMap<String, SourceInfo>,
123
124 pub outer_columns: Vec<String>,
127
128 pub can_be_correlated: bool,
131
132 pub subquery_scopes: Vec<Scope>,
134
135 pub derived_table_scopes: Vec<Scope>,
137
138 pub cte_scopes: Vec<Scope>,
140
141 pub udtf_scopes: Vec<Scope>,
143
144 pub table_scopes: Vec<Scope>,
146
147 pub union_scopes: Vec<Scope>,
149
150 columns_cache: Option<Vec<ColumnRef>>,
152
153 external_columns_cache: Option<Vec<ColumnRef>>,
155}
156
157impl Scope {
158 pub fn new(expression: Expression) -> Self {
160 Self {
161 expression,
162 scope_type: ScopeType::Root,
163 sources: HashMap::new(),
164 lateral_sources: HashMap::new(),
165 cte_sources: HashMap::new(),
166 outer_columns: Vec::new(),
167 can_be_correlated: false,
168 subquery_scopes: Vec::new(),
169 derived_table_scopes: Vec::new(),
170 cte_scopes: Vec::new(),
171 udtf_scopes: Vec::new(),
172 table_scopes: Vec::new(),
173 union_scopes: Vec::new(),
174 columns_cache: None,
175 external_columns_cache: None,
176 }
177 }
178
179 pub fn branch(&self, expression: Expression, scope_type: ScopeType) -> Self {
181 self.branch_with_options(expression, scope_type, None, None, None)
182 }
183
184 pub fn branch_with_options(
186 &self,
187 expression: Expression,
188 scope_type: ScopeType,
189 sources: Option<HashMap<String, SourceInfo>>,
190 lateral_sources: Option<HashMap<String, SourceInfo>>,
191 outer_columns: Option<Vec<String>>,
192 ) -> Self {
193 let can_be_correlated = self.can_be_correlated
194 || scope_type == ScopeType::Subquery
195 || scope_type == ScopeType::Udtf;
196
197 Self {
198 expression,
199 scope_type,
200 sources: sources.unwrap_or_default(),
201 lateral_sources: lateral_sources.unwrap_or_default(),
202 cte_sources: self.cte_sources.clone(),
203 outer_columns: outer_columns.unwrap_or_default(),
204 can_be_correlated,
205 subquery_scopes: Vec::new(),
206 derived_table_scopes: Vec::new(),
207 cte_scopes: Vec::new(),
208 udtf_scopes: Vec::new(),
209 table_scopes: Vec::new(),
210 union_scopes: Vec::new(),
211 columns_cache: None,
212 external_columns_cache: None,
213 }
214 }
215
216 pub fn clear_cache(&mut self) {
218 self.columns_cache = None;
219 self.external_columns_cache = None;
220 }
221
222 pub fn add_source(&mut self, name: String, expression: Expression, is_scope: bool) {
224 let kind = if is_scope {
225 SourceKind::DerivedTable
226 } else {
227 SourceKind::Table
228 };
229 self.add_source_info(name, SourceInfo::new(expression, is_scope, kind));
230 }
231
232 pub fn add_source_info(&mut self, name: String, info: SourceInfo) {
234 self.sources.insert(name, info);
235 self.clear_cache();
236 }
237
238 pub fn add_virtual_source(&mut self, alias: String, expression: Expression) {
240 let lineage_name = self.next_virtual_source_name();
241 let info = SourceInfo::new(expression, false, SourceKind::Virtual)
242 .with_alias(alias.clone())
243 .with_lineage_name(lineage_name);
244 self.add_source_info(alias, info);
245 }
246
247 fn next_virtual_source_name(&self) -> String {
248 let count = self
249 .sources
250 .values()
251 .filter(|source| source.kind == SourceKind::Virtual)
252 .count();
253 format!("_{}", count)
254 }
255
256 pub fn add_lateral_source(&mut self, name: String, expression: Expression, is_scope: bool) {
258 let kind = if is_scope {
259 SourceKind::DerivedTable
260 } else {
261 SourceKind::Table
262 };
263 let info = SourceInfo::new(expression.clone(), is_scope, kind);
264 self.sources.insert(name.clone(), info.clone());
265 self.lateral_sources.insert(name, info);
266 self.clear_cache();
267 }
268
269 pub fn add_cte_source(&mut self, name: String, expression: Expression) {
271 let info = SourceInfo::new(expression, true, SourceKind::Cte);
272 self.cte_sources.insert(name.clone(), info.clone());
273 self.sources.insert(name, info);
274 self.clear_cache();
275 }
276
277 pub fn rename_source(&mut self, old_name: &str, new_name: String) {
279 if let Some(source) = self.sources.remove(old_name) {
280 self.sources.insert(new_name, source);
281 }
282 self.clear_cache();
283 }
284
285 pub fn remove_source(&mut self, name: &str) {
287 self.sources.remove(name);
288 self.clear_cache();
289 }
290
291 pub fn columns(&mut self) -> &[ColumnRef] {
293 if self.columns_cache.is_none() {
294 let mut columns = Vec::new();
295 collect_columns(&self.expression, &mut columns);
296 self.columns_cache = Some(columns);
297 }
298 self.columns_cache.as_ref().unwrap()
299 }
300
301 pub fn output_columns(&self) -> Vec<String> {
306 crate::ast_transforms::get_output_column_names(&self.expression)
307 }
308
309 pub fn source_names(&self) -> HashSet<String> {
311 let mut names: HashSet<String> = self.sources.keys().cloned().collect();
312 names.extend(self.cte_sources.keys().cloned());
313 names
314 }
315
316 pub fn external_columns(&mut self) -> Vec<ColumnRef> {
318 if self.external_columns_cache.is_some() {
319 return self.external_columns_cache.clone().unwrap();
320 }
321
322 let source_names = self.source_names();
323 let columns = self.columns().to_vec();
324
325 let external: Vec<ColumnRef> = columns
326 .into_iter()
327 .filter(|col| {
328 match &col.table {
330 Some(table) => !source_names.contains(table),
331 None => false, }
333 })
334 .collect();
335
336 self.external_columns_cache = Some(external.clone());
337 external
338 }
339
340 pub fn local_columns(&mut self) -> Vec<ColumnRef> {
342 let external_set: HashSet<_> = self.external_columns().into_iter().collect();
343 let columns = self.columns().to_vec();
344
345 columns
346 .into_iter()
347 .filter(|col| !external_set.contains(col))
348 .collect()
349 }
350
351 pub fn unqualified_columns(&mut self) -> Vec<ColumnRef> {
353 self.columns()
354 .iter()
355 .filter(|c| c.table.is_none())
356 .cloned()
357 .collect()
358 }
359
360 pub fn source_columns(&mut self, source_name: &str) -> Vec<ColumnRef> {
362 self.columns()
363 .iter()
364 .filter(|col| col.table.as_deref() == Some(source_name))
365 .cloned()
366 .collect()
367 }
368
369 pub fn is_correlated_subquery(&mut self) -> bool {
375 self.can_be_correlated && !self.external_columns().is_empty()
376 }
377
378 pub fn is_subquery(&self) -> bool {
380 self.scope_type == ScopeType::Subquery
381 }
382
383 pub fn is_derived_table(&self) -> bool {
385 self.scope_type == ScopeType::DerivedTable
386 }
387
388 pub fn is_cte(&self) -> bool {
390 self.scope_type == ScopeType::Cte
391 }
392
393 pub fn is_root(&self) -> bool {
395 self.scope_type == ScopeType::Root
396 }
397
398 pub fn is_udtf(&self) -> bool {
400 self.scope_type == ScopeType::Udtf
401 }
402
403 pub fn is_union(&self) -> bool {
405 self.scope_type == ScopeType::SetOperation
406 }
407
408 pub fn traverse(&self) -> Vec<&Scope> {
410 let mut result = Vec::new();
411 self.traverse_impl(&mut result);
412 result
413 }
414
415 fn traverse_impl<'a>(&'a self, result: &mut Vec<&'a Scope>) {
416 for scope in &self.cte_scopes {
418 scope.traverse_impl(result);
419 }
420 for scope in &self.union_scopes {
421 scope.traverse_impl(result);
422 }
423 for scope in &self.table_scopes {
424 scope.traverse_impl(result);
425 }
426 for scope in &self.subquery_scopes {
427 scope.traverse_impl(result);
428 }
429 result.push(self);
431 }
432
433 pub fn ref_count(&self) -> HashMap<usize, usize> {
435 let mut counts: HashMap<usize, usize> = HashMap::new();
436
437 for scope in self.traverse() {
438 for (_, source_info) in scope.sources.iter() {
439 if source_info.is_scope {
440 let id = &source_info.expression as *const _ as usize;
441 *counts.entry(id).or_insert(0) += 1;
442 }
443 }
444 }
445
446 counts
447 }
448}
449
450fn collect_columns(expr: &Expression, columns: &mut Vec<ColumnRef>) {
452 match expr {
453 Expression::Column(col) => {
454 columns.push(ColumnRef {
455 table: col.table.as_ref().map(|t| t.name.clone()),
456 name: col.name.name.clone(),
457 });
458 }
459 Expression::Select(select) => {
460 for e in &select.expressions {
462 collect_columns(e, columns);
463 }
464 for join in &select.joins {
466 if let Some(on) = &join.on {
467 collect_columns(on, columns);
468 }
469 if let Some(match_condition) = &join.match_condition {
470 collect_columns(match_condition, columns);
471 }
472 }
473 if let Some(where_clause) = &select.where_clause {
475 collect_columns(&where_clause.this, columns);
476 }
477 if let Some(having) = &select.having {
479 collect_columns(&having.this, columns);
480 }
481 if let Some(order_by) = &select.order_by {
483 for ord in &order_by.expressions {
484 collect_columns(&ord.this, columns);
485 }
486 }
487 if let Some(group_by) = &select.group_by {
489 for e in &group_by.expressions {
490 collect_columns(e, columns);
491 }
492 }
493 }
496 Expression::And(bin)
498 | Expression::Or(bin)
499 | Expression::Add(bin)
500 | Expression::Sub(bin)
501 | Expression::Mul(bin)
502 | Expression::Div(bin)
503 | Expression::Mod(bin)
504 | Expression::Eq(bin)
505 | Expression::Neq(bin)
506 | Expression::Lt(bin)
507 | Expression::Lte(bin)
508 | Expression::Gt(bin)
509 | Expression::Gte(bin)
510 | Expression::BitwiseAnd(bin)
511 | Expression::BitwiseOr(bin)
512 | Expression::BitwiseXor(bin)
513 | Expression::Concat(bin) => {
514 collect_columns(&bin.left, columns);
515 collect_columns(&bin.right, columns);
516 }
517 Expression::Like(like) | Expression::ILike(like) => {
519 collect_columns(&like.left, columns);
520 collect_columns(&like.right, columns);
521 if let Some(escape) = &like.escape {
522 collect_columns(escape, columns);
523 }
524 }
525 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
527 collect_columns(&un.this, columns);
528 }
529 Expression::Function(func) => {
530 for arg in &func.args {
531 collect_columns(arg, columns);
532 }
533 }
534 Expression::AggregateFunction(agg) => {
535 for arg in &agg.args {
536 collect_columns(arg, columns);
537 }
538 }
539 Expression::WindowFunction(wf) => {
540 collect_columns(&wf.this, columns);
541 for e in &wf.over.partition_by {
542 collect_columns(e, columns);
543 }
544 for e in &wf.over.order_by {
545 collect_columns(&e.this, columns);
546 }
547 }
548 Expression::Alias(alias) => {
549 collect_columns(&alias.this, columns);
550 }
551 Expression::Case(case) => {
552 if let Some(operand) = &case.operand {
553 collect_columns(operand, columns);
554 }
555 for (when_expr, then_expr) in &case.whens {
556 collect_columns(when_expr, columns);
557 collect_columns(then_expr, columns);
558 }
559 if let Some(else_clause) = &case.else_ {
560 collect_columns(else_clause, columns);
561 }
562 }
563 Expression::Paren(paren) => {
564 collect_columns(&paren.this, columns);
565 }
566 Expression::Ordered(ord) => {
567 collect_columns(&ord.this, columns);
568 }
569 Expression::In(in_expr) => {
570 collect_columns(&in_expr.this, columns);
571 for e in &in_expr.expressions {
572 collect_columns(e, columns);
573 }
574 }
576 Expression::Between(between) => {
577 collect_columns(&between.this, columns);
578 collect_columns(&between.low, columns);
579 collect_columns(&between.high, columns);
580 }
581 Expression::IsNull(is_null) => {
582 collect_columns(&is_null.this, columns);
583 }
584 Expression::Cast(cast) => {
585 collect_columns(&cast.this, columns);
586 }
587 Expression::Extract(extract) => {
588 collect_columns(&extract.this, columns);
589 }
590 Expression::Exists(_) | Expression::Subquery(_) => {
591 }
593 Expression::Prepare(prepare) => {
594 collect_columns(&prepare.statement, columns);
595 }
596 _ => {
597 }
599 }
600}
601
602pub fn build_scope(expression: &Expression) -> Scope {
607 let mut root = Scope::new(expression.clone());
608 build_scope_impl(expression, &mut root);
609 root
610}
611
612fn build_scope_impl(expression: &Expression, current_scope: &mut Scope) {
613 match expression {
614 Expression::Prepare(prepare) => {
615 build_scope_impl(&prepare.statement, current_scope);
616 }
617 Expression::Select(select) => {
618 if let Some(with) = &select.with {
620 for cte in &with.ctes {
621 let cte_name = cte.alias.name.clone();
622 let mut cte_scope = current_scope
623 .branch(Expression::Cte(Box::new(cte.clone())), ScopeType::Cte);
624 build_scope_impl(&cte.this, &mut cte_scope);
625 current_scope.add_cte_source(cte_name, Expression::Cte(Box::new(cte.clone())));
626 current_scope.cte_scopes.push(cte_scope);
627 }
628 }
629
630 if let Some(from) = &select.from {
632 for table in &from.expressions {
633 add_table_to_scope(table, current_scope);
634 }
635 }
636
637 for join in &select.joins {
639 add_table_to_scope(&join.this, current_scope);
640 }
641
642 collect_subqueries(expression, current_scope);
644 }
645 Expression::Union(union) => {
646 let mut left_scope = current_scope.branch(union.left.clone(), ScopeType::SetOperation);
647 build_scope_impl(&union.left, &mut left_scope);
648
649 let mut right_scope =
650 current_scope.branch(union.right.clone(), ScopeType::SetOperation);
651 build_scope_impl(&union.right, &mut right_scope);
652
653 current_scope.union_scopes.push(left_scope);
654 current_scope.union_scopes.push(right_scope);
655 }
656 Expression::Intersect(intersect) => {
657 let mut left_scope =
658 current_scope.branch(intersect.left.clone(), ScopeType::SetOperation);
659 build_scope_impl(&intersect.left, &mut left_scope);
660
661 let mut right_scope =
662 current_scope.branch(intersect.right.clone(), ScopeType::SetOperation);
663 build_scope_impl(&intersect.right, &mut right_scope);
664
665 current_scope.union_scopes.push(left_scope);
666 current_scope.union_scopes.push(right_scope);
667 }
668 Expression::Except(except) => {
669 let mut left_scope = current_scope.branch(except.left.clone(), ScopeType::SetOperation);
670 build_scope_impl(&except.left, &mut left_scope);
671
672 let mut right_scope =
673 current_scope.branch(except.right.clone(), ScopeType::SetOperation);
674 build_scope_impl(&except.right, &mut right_scope);
675
676 current_scope.union_scopes.push(left_scope);
677 current_scope.union_scopes.push(right_scope);
678 }
679 Expression::CreateTable(create) => {
680 if let Some(with) = &create.with_cte {
683 for cte in &with.ctes {
684 let cte_name = cte.alias.name.clone();
685 let mut cte_scope = current_scope
686 .branch(Expression::Cte(Box::new(cte.clone())), ScopeType::Cte);
687 build_scope_impl(&cte.this, &mut cte_scope);
688 current_scope.add_cte_source(cte_name, Expression::Cte(Box::new(cte.clone())));
689 current_scope.cte_scopes.push(cte_scope);
690 }
691 }
692 if let Some(as_select) = &create.as_select {
694 build_scope_impl(as_select, current_scope);
695 }
696 }
697 _ => {}
698 }
699}
700
701fn add_table_to_scope(expr: &Expression, scope: &mut Scope) {
702 match expr {
703 Expression::Table(table) => {
704 let name = table
705 .alias
706 .as_ref()
707 .map(|a| a.name.clone())
708 .unwrap_or_else(|| table.name.name.clone());
709 let cte_source = if table.schema.is_none() && table.catalog.is_none() {
710 scope.cte_sources.get(&table.name.name).or_else(|| {
711 scope
712 .cte_sources
713 .iter()
714 .find(|(cte_name, _)| cte_name.eq_ignore_ascii_case(&table.name.name))
715 .map(|(_, source)| source)
716 })
717 } else {
718 None
719 };
720
721 if let Some(source) = cte_source {
722 scope.add_source_info(name, source.clone());
723 } else {
724 scope.add_source(name, expr.clone(), false);
725 }
726 }
727 Expression::Subquery(subquery) => {
728 let name = subquery
729 .alias
730 .as_ref()
731 .map(|a| a.name.clone())
732 .unwrap_or_default();
733
734 let mut derived_scope = scope.branch(subquery.this.clone(), ScopeType::DerivedTable);
735 build_scope_impl(&subquery.this, &mut derived_scope);
736
737 scope.add_source(name.clone(), expr.clone(), true);
738 scope.derived_table_scopes.push(derived_scope);
739 }
740 Expression::Unnest(unnest) => {
741 if let Some(alias) = &unnest.alias {
742 scope.add_virtual_source(alias.name.clone(), expr.clone());
743 }
744 }
745 Expression::Alias(alias) if matches!(&alias.this, Expression::Unnest(_)) => {
746 scope.add_virtual_source(alias.alias.name.clone(), expr.clone());
747 }
748 Expression::Paren(paren) => {
749 add_table_to_scope(&paren.this, scope);
750 }
751 _ => {}
752 }
753}
754
755fn collect_subqueries(expr: &Expression, parent_scope: &mut Scope) {
756 match expr {
757 Expression::Select(select) => {
758 if let Some(where_clause) = &select.where_clause {
760 collect_subqueries_in_expr(&where_clause.this, parent_scope);
761 }
762 for e in &select.expressions {
764 collect_subqueries_in_expr(e, parent_scope);
765 }
766 if let Some(having) = &select.having {
768 collect_subqueries_in_expr(&having.this, parent_scope);
769 }
770 }
771 _ => {}
772 }
773}
774
775fn collect_subqueries_in_expr(expr: &Expression, parent_scope: &mut Scope) {
776 match expr {
777 Expression::Subquery(subquery) if subquery.alias.is_none() => {
778 let mut sub_scope = parent_scope.branch(subquery.this.clone(), ScopeType::Subquery);
780 build_scope_impl(&subquery.this, &mut sub_scope);
781 parent_scope.subquery_scopes.push(sub_scope);
782 }
783 Expression::In(in_expr) => {
784 collect_subqueries_in_expr(&in_expr.this, parent_scope);
785 if let Some(query) = &in_expr.query {
786 let mut sub_scope = parent_scope.branch(query.clone(), ScopeType::Subquery);
787 build_scope_impl(query, &mut sub_scope);
788 parent_scope.subquery_scopes.push(sub_scope);
789 }
790 }
791 Expression::Exists(exists) => {
792 let mut sub_scope = parent_scope.branch(exists.this.clone(), ScopeType::Subquery);
793 build_scope_impl(&exists.this, &mut sub_scope);
794 parent_scope.subquery_scopes.push(sub_scope);
795 }
796 Expression::And(bin)
798 | Expression::Or(bin)
799 | Expression::Add(bin)
800 | Expression::Sub(bin)
801 | Expression::Mul(bin)
802 | Expression::Div(bin)
803 | Expression::Mod(bin)
804 | Expression::Eq(bin)
805 | Expression::Neq(bin)
806 | Expression::Lt(bin)
807 | Expression::Lte(bin)
808 | Expression::Gt(bin)
809 | Expression::Gte(bin)
810 | Expression::BitwiseAnd(bin)
811 | Expression::BitwiseOr(bin)
812 | Expression::BitwiseXor(bin)
813 | Expression::Concat(bin) => {
814 collect_subqueries_in_expr(&bin.left, parent_scope);
815 collect_subqueries_in_expr(&bin.right, parent_scope);
816 }
817 Expression::Like(like) | Expression::ILike(like) => {
819 collect_subqueries_in_expr(&like.left, parent_scope);
820 collect_subqueries_in_expr(&like.right, parent_scope);
821 if let Some(escape) = &like.escape {
822 collect_subqueries_in_expr(escape, parent_scope);
823 }
824 }
825 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
827 collect_subqueries_in_expr(&un.this, parent_scope);
828 }
829 Expression::Function(func) => {
830 for arg in &func.args {
831 collect_subqueries_in_expr(arg, parent_scope);
832 }
833 }
834 Expression::Case(case) => {
835 if let Some(operand) = &case.operand {
836 collect_subqueries_in_expr(operand, parent_scope);
837 }
838 for (when_expr, then_expr) in &case.whens {
839 collect_subqueries_in_expr(when_expr, parent_scope);
840 collect_subqueries_in_expr(then_expr, parent_scope);
841 }
842 if let Some(else_clause) = &case.else_ {
843 collect_subqueries_in_expr(else_clause, parent_scope);
844 }
845 }
846 Expression::Paren(paren) => {
847 collect_subqueries_in_expr(&paren.this, parent_scope);
848 }
849 Expression::Alias(alias) => {
850 collect_subqueries_in_expr(&alias.this, parent_scope);
851 }
852 _ => {}
853 }
854}
855
856pub fn walk_in_scope<'a>(
868 expression: &'a Expression,
869 bfs: bool,
870) -> impl Iterator<Item = &'a Expression> {
871 WalkInScopeIter::new(expression, bfs)
872}
873
874struct WalkInScopeIter<'a> {
876 queue: VecDeque<&'a Expression>,
877 bfs: bool,
878}
879
880impl<'a> WalkInScopeIter<'a> {
881 fn new(expression: &'a Expression, bfs: bool) -> Self {
882 let mut queue = VecDeque::new();
883 queue.push_back(expression);
884 Self { queue, bfs }
885 }
886
887 fn should_stop_at(&self, expr: &Expression, is_root: bool) -> bool {
888 if is_root {
889 return false;
890 }
891
892 if matches!(expr, Expression::Cte(_)) {
894 return true;
895 }
896
897 if let Expression::Subquery(subquery) = expr {
899 if subquery.alias.is_some() {
900 return true;
901 }
902 }
903
904 if matches!(
906 expr,
907 Expression::Select(_)
908 | Expression::Union(_)
909 | Expression::Intersect(_)
910 | Expression::Except(_)
911 ) {
912 return true;
913 }
914
915 false
916 }
917
918 fn get_children(&self, expr: &'a Expression) -> Vec<&'a Expression> {
919 let mut children = Vec::new();
920
921 match expr {
922 Expression::Prepare(prepare) => {
923 children.push(&prepare.statement);
924 }
925 Expression::Select(select) => {
926 for e in &select.expressions {
928 children.push(e);
929 }
930 if let Some(from) = &select.from {
932 for table in &from.expressions {
933 if !self.should_stop_at(table, false) {
934 children.push(table);
935 }
936 }
937 }
938 for join in &select.joins {
940 if let Some(on) = &join.on {
941 children.push(on);
942 }
943 }
945 if let Some(where_clause) = &select.where_clause {
947 children.push(&where_clause.this);
948 }
949 if let Some(group_by) = &select.group_by {
951 for e in &group_by.expressions {
952 children.push(e);
953 }
954 }
955 if let Some(having) = &select.having {
957 children.push(&having.this);
958 }
959 if let Some(order_by) = &select.order_by {
961 for ord in &order_by.expressions {
962 children.push(&ord.this);
963 }
964 }
965 if let Some(limit) = &select.limit {
967 children.push(&limit.this);
968 }
969 if let Some(offset) = &select.offset {
971 children.push(&offset.this);
972 }
973 }
974 Expression::And(bin)
975 | Expression::Or(bin)
976 | Expression::Add(bin)
977 | Expression::Sub(bin)
978 | Expression::Mul(bin)
979 | Expression::Div(bin)
980 | Expression::Mod(bin)
981 | Expression::Eq(bin)
982 | Expression::Neq(bin)
983 | Expression::Lt(bin)
984 | Expression::Lte(bin)
985 | Expression::Gt(bin)
986 | Expression::Gte(bin)
987 | Expression::BitwiseAnd(bin)
988 | Expression::BitwiseOr(bin)
989 | Expression::BitwiseXor(bin)
990 | Expression::Concat(bin) => {
991 children.push(&bin.left);
992 children.push(&bin.right);
993 }
994 Expression::Like(like) | Expression::ILike(like) => {
995 children.push(&like.left);
996 children.push(&like.right);
997 if let Some(escape) = &like.escape {
998 children.push(escape);
999 }
1000 }
1001 Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
1002 children.push(&un.this);
1003 }
1004 Expression::Function(func) => {
1005 for arg in &func.args {
1006 children.push(arg);
1007 }
1008 }
1009 Expression::AggregateFunction(agg) => {
1010 for arg in &agg.args {
1011 children.push(arg);
1012 }
1013 }
1014 Expression::WindowFunction(wf) => {
1015 children.push(&wf.this);
1016 for e in &wf.over.partition_by {
1017 children.push(e);
1018 }
1019 for e in &wf.over.order_by {
1020 children.push(&e.this);
1021 }
1022 }
1023 Expression::Alias(alias) => {
1024 children.push(&alias.this);
1025 }
1026 Expression::Case(case) => {
1027 if let Some(operand) = &case.operand {
1028 children.push(operand);
1029 }
1030 for (when_expr, then_expr) in &case.whens {
1031 children.push(when_expr);
1032 children.push(then_expr);
1033 }
1034 if let Some(else_clause) = &case.else_ {
1035 children.push(else_clause);
1036 }
1037 }
1038 Expression::Paren(paren) => {
1039 children.push(&paren.this);
1040 }
1041 Expression::Ordered(ord) => {
1042 children.push(&ord.this);
1043 }
1044 Expression::In(in_expr) => {
1045 children.push(&in_expr.this);
1046 for e in &in_expr.expressions {
1047 children.push(e);
1048 }
1049 }
1051 Expression::Between(between) => {
1052 children.push(&between.this);
1053 children.push(&between.low);
1054 children.push(&between.high);
1055 }
1056 Expression::IsNull(is_null) => {
1057 children.push(&is_null.this);
1058 }
1059 Expression::Cast(cast) => {
1060 children.push(&cast.this);
1061 }
1062 Expression::Extract(extract) => {
1063 children.push(&extract.this);
1064 }
1065 Expression::Coalesce(coalesce) => {
1066 for e in &coalesce.expressions {
1067 children.push(e);
1068 }
1069 }
1070 Expression::NullIf(nullif) => {
1071 children.push(&nullif.this);
1072 children.push(&nullif.expression);
1073 }
1074 Expression::Table(_table) => {
1075 }
1078 Expression::TryCatch(try_catch) => {
1079 for stmt in &try_catch.try_body {
1080 children.push(stmt);
1081 }
1082 if let Some(catch_body) = &try_catch.catch_body {
1083 for stmt in catch_body {
1084 children.push(stmt);
1085 }
1086 }
1087 }
1088 Expression::Column(_) | Expression::Literal(_) | Expression::Identifier(_) => {
1089 }
1091 Expression::Subquery(_) | Expression::Exists(_) => {}
1093 _ => {
1094 }
1096 }
1097
1098 children
1099 }
1100}
1101
1102impl<'a> Iterator for WalkInScopeIter<'a> {
1103 type Item = &'a Expression;
1104
1105 fn next(&mut self) -> Option<Self::Item> {
1106 let expr = if self.bfs {
1107 self.queue.pop_front()?
1108 } else {
1109 self.queue.pop_back()?
1110 };
1111
1112 let children = self.get_children(expr);
1114
1115 if self.bfs {
1116 for child in children {
1117 if !self.should_stop_at(child, false) {
1118 self.queue.push_back(child);
1119 }
1120 }
1121 } else {
1122 for child in children.into_iter().rev() {
1123 if !self.should_stop_at(child, false) {
1124 self.queue.push_back(child);
1125 }
1126 }
1127 }
1128
1129 Some(expr)
1130 }
1131}
1132
1133pub fn find_in_scope<'a, F>(
1145 expression: &'a Expression,
1146 predicate: F,
1147 bfs: bool,
1148) -> Option<&'a Expression>
1149where
1150 F: Fn(&Expression) -> bool,
1151{
1152 walk_in_scope(expression, bfs).find(|e| predicate(e))
1153}
1154
1155pub fn find_all_in_scope<'a, F>(
1167 expression: &'a Expression,
1168 predicate: F,
1169 bfs: bool,
1170) -> Vec<&'a Expression>
1171where
1172 F: Fn(&Expression) -> bool,
1173{
1174 walk_in_scope(expression, bfs)
1175 .filter(|e| predicate(e))
1176 .collect()
1177}
1178
1179pub fn traverse_scope(expression: &Expression) -> Vec<Scope> {
1189 match expression {
1190 Expression::Select(_)
1191 | Expression::Union(_)
1192 | Expression::Intersect(_)
1193 | Expression::Except(_)
1194 | Expression::Prepare(_)
1195 | Expression::CreateTable(_) => {
1196 let root = build_scope(expression);
1197 root.traverse().into_iter().cloned().collect()
1198 }
1199 _ => Vec::new(),
1200 }
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205 use super::*;
1206 use crate::parser::Parser;
1207
1208 fn parse_and_build_scope(sql: &str) -> Scope {
1209 let ast = Parser::parse_sql(sql).expect("Failed to parse SQL");
1210 build_scope(&ast[0])
1211 }
1212
1213 #[test]
1214 fn test_simple_select_scope() {
1215 let mut scope = parse_and_build_scope("SELECT a, b FROM t");
1216
1217 assert!(scope.is_root());
1218 assert!(!scope.can_be_correlated);
1219 assert!(scope.sources.contains_key("t"));
1220
1221 let columns = scope.columns();
1222 assert_eq!(columns.len(), 2);
1223 }
1224
1225 #[test]
1226 fn test_derived_table_scope() {
1227 let mut scope = parse_and_build_scope("SELECT x.a FROM (SELECT a FROM t) AS x");
1228
1229 assert!(scope.sources.contains_key("x"));
1230 assert_eq!(scope.derived_table_scopes.len(), 1);
1231
1232 let derived = &mut scope.derived_table_scopes[0];
1233 assert!(derived.is_derived_table());
1234 assert!(derived.sources.contains_key("t"));
1235 }
1236
1237 #[test]
1238 fn test_non_correlated_subquery() {
1239 let mut scope = parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s)");
1240
1241 assert_eq!(scope.subquery_scopes.len(), 1);
1242
1243 let subquery = &mut scope.subquery_scopes[0];
1244 assert!(subquery.is_subquery());
1245 assert!(subquery.can_be_correlated);
1246
1247 assert!(subquery.sources.contains_key("s"));
1249 assert!(!subquery.is_correlated_subquery());
1250 }
1251
1252 #[test]
1253 fn test_correlated_subquery() {
1254 let mut scope =
1255 parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s WHERE s.x = t.y)");
1256
1257 assert_eq!(scope.subquery_scopes.len(), 1);
1258
1259 let subquery = &mut scope.subquery_scopes[0];
1260 assert!(subquery.is_subquery());
1261 assert!(subquery.can_be_correlated);
1262
1263 let external = subquery.external_columns();
1265 assert!(!external.is_empty());
1266 assert!(external.iter().any(|c| c.table.as_deref() == Some("t")));
1267 assert!(subquery.is_correlated_subquery());
1268 }
1269
1270 #[test]
1271 fn test_cte_scope() {
1272 let scope = parse_and_build_scope("WITH cte AS (SELECT a FROM t) SELECT * FROM cte");
1273
1274 assert_eq!(scope.cte_scopes.len(), 1);
1275 assert!(scope.cte_sources.contains_key("cte"));
1276
1277 let cte = &scope.cte_scopes[0];
1278 assert!(cte.is_cte());
1279 }
1280
1281 #[test]
1282 fn test_multiple_sources() {
1283 let scope = parse_and_build_scope("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
1284
1285 assert!(scope.sources.contains_key("t"));
1286 assert!(scope.sources.contains_key("s"));
1287 assert_eq!(scope.sources.len(), 2);
1288 }
1289
1290 #[test]
1291 fn test_aliased_table() {
1292 let scope = parse_and_build_scope("SELECT x.a FROM t AS x");
1293
1294 assert!(scope.sources.contains_key("x"));
1296 assert!(!scope.sources.contains_key("t"));
1297 }
1298
1299 #[test]
1300 fn test_local_columns() {
1301 let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1302
1303 let local = scope.local_columns();
1304 assert_eq!(local.len(), 5);
1307 assert!(local.iter().all(|c| c.table.is_some()));
1308 }
1309
1310 #[test]
1311 fn test_columns_include_join_on_clause_references() {
1312 let mut scope = parse_and_build_scope(
1313 "SELECT o.total FROM orders o JOIN customers c ON c.id = o.customer_id",
1314 );
1315
1316 let cols: Vec<String> = scope
1317 .columns()
1318 .iter()
1319 .map(|c| match &c.table {
1320 Some(t) => format!("{}.{}", t, c.name),
1321 None => c.name.clone(),
1322 })
1323 .collect();
1324
1325 assert!(cols.contains(&"o.total".to_string()));
1326 assert!(cols.contains(&"c.id".to_string()));
1327 assert!(cols.contains(&"o.customer_id".to_string()));
1328 }
1329
1330 #[test]
1331 fn test_unqualified_columns() {
1332 let mut scope = parse_and_build_scope("SELECT a, b, t.c FROM t");
1333
1334 let unqualified = scope.unqualified_columns();
1335 assert_eq!(unqualified.len(), 2);
1337 assert!(unqualified.iter().all(|c| c.table.is_none()));
1338 }
1339
1340 #[test]
1341 fn test_source_columns() {
1342 let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1343
1344 let t_cols = scope.source_columns("t");
1345 assert!(t_cols.len() >= 2);
1347 assert!(t_cols.iter().all(|c| c.table.as_deref() == Some("t")));
1348
1349 let s_cols = scope.source_columns("s");
1350 assert!(s_cols.len() >= 1);
1352 assert!(s_cols.iter().all(|c| c.table.as_deref() == Some("s")));
1353 }
1354
1355 #[test]
1356 fn test_rename_source() {
1357 let mut scope = parse_and_build_scope("SELECT a FROM t");
1358
1359 assert!(scope.sources.contains_key("t"));
1360 scope.rename_source("t", "new_name".to_string());
1361 assert!(!scope.sources.contains_key("t"));
1362 assert!(scope.sources.contains_key("new_name"));
1363 }
1364
1365 #[test]
1366 fn test_remove_source() {
1367 let mut scope = parse_and_build_scope("SELECT a FROM t");
1368
1369 assert!(scope.sources.contains_key("t"));
1370 scope.remove_source("t");
1371 assert!(!scope.sources.contains_key("t"));
1372 }
1373
1374 #[test]
1375 fn test_walk_in_scope() {
1376 let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1377 let expr = &ast[0];
1378
1379 let walked: Vec<_> = walk_in_scope(expr, true).collect();
1381 assert!(!walked.is_empty());
1382
1383 assert!(walked.iter().any(|e| matches!(e, Expression::Select(_))));
1385 assert!(walked.iter().any(|e| matches!(e, Expression::Column(_))));
1387 }
1388
1389 #[test]
1390 fn test_find_in_scope() {
1391 let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1392 let expr = &ast[0];
1393
1394 let found = find_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1396 assert!(found.is_some());
1397 assert!(matches!(found.unwrap(), Expression::Column(_)));
1398 }
1399
1400 #[test]
1401 fn test_find_all_in_scope() {
1402 let ast = Parser::parse_sql("SELECT a, b, c FROM t").expect("Failed to parse");
1403 let expr = &ast[0];
1404
1405 let found = find_all_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1407 assert_eq!(found.len(), 3);
1408 }
1409
1410 #[test]
1411 fn test_traverse_scope() {
1412 let ast =
1413 Parser::parse_sql("SELECT a FROM (SELECT b FROM t) AS x").expect("Failed to parse");
1414 let expr = &ast[0];
1415
1416 let scopes = traverse_scope(expr);
1417 assert!(!scopes.is_empty());
1420 assert!(scopes.iter().any(|s| s.is_root()));
1422 }
1423
1424 #[test]
1425 fn test_branch_with_options() {
1426 let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1427 let scope = build_scope(&ast[0]);
1428
1429 let child = scope.branch_with_options(
1430 ast[0].clone(),
1431 ScopeType::Subquery, None,
1433 None,
1434 Some(vec!["col1".to_string(), "col2".to_string()]),
1435 );
1436
1437 assert_eq!(child.outer_columns, vec!["col1", "col2"]);
1438 assert!(child.can_be_correlated); }
1440
1441 #[test]
1442 fn test_is_udtf() {
1443 let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1444 let scope = Scope::new(ast[0].clone());
1445 assert!(!scope.is_udtf());
1446
1447 let root = build_scope(&ast[0]);
1448 let udtf_scope = root.branch(ast[0].clone(), ScopeType::Udtf);
1449 assert!(udtf_scope.is_udtf());
1450 }
1451
1452 #[test]
1453 fn test_is_union() {
1454 let scope = parse_and_build_scope("SELECT a FROM t UNION SELECT b FROM s");
1455
1456 assert!(scope.is_root());
1457 assert_eq!(scope.union_scopes.len(), 2);
1458 assert!(scope.union_scopes[0].is_union());
1460 assert!(scope.union_scopes[1].is_union());
1461 }
1462
1463 #[test]
1464 fn test_union_output_columns() {
1465 let scope = parse_and_build_scope(
1466 "SELECT id, name FROM customers UNION ALL SELECT id, name FROM employees",
1467 );
1468 assert_eq!(scope.output_columns(), vec!["id", "name"]);
1469 }
1470
1471 #[test]
1472 fn test_clear_cache() {
1473 let mut scope = parse_and_build_scope("SELECT t.a FROM t");
1474
1475 let _ = scope.columns();
1477 assert!(scope.columns_cache.is_some());
1478
1479 scope.clear_cache();
1481 assert!(scope.columns_cache.is_none());
1482 assert!(scope.external_columns_cache.is_none());
1483 }
1484
1485 #[test]
1486 fn test_scope_traverse() {
1487 let scope = parse_and_build_scope(
1488 "WITH cte AS (SELECT a FROM t) SELECT * FROM cte WHERE EXISTS (SELECT b FROM s)",
1489 );
1490
1491 let traversed = scope.traverse();
1492 assert!(traversed.len() >= 3);
1494 }
1495
1496 #[test]
1497 fn test_create_table_as_select_scope() {
1498 let scope = parse_and_build_scope("CREATE TABLE out_table AS SELECT 1 AS id FROM src");
1500 assert!(
1501 scope.sources.contains_key("src"),
1502 "CTAS scope should contain the FROM table"
1503 );
1504 assert!(
1505 !scope.sources.contains_key("out_table"),
1506 "CTAS target table should not be treated as a source"
1507 );
1508
1509 let scope = parse_and_build_scope(
1511 "CREATE TABLE out_table AS SELECT a.id FROM foo AS a JOIN bar AS b ON a.id = b.id",
1512 );
1513 assert!(scope.sources.contains_key("a"));
1514 assert!(scope.sources.contains_key("b"));
1515 assert!(
1516 !scope.sources.contains_key("out_table"),
1517 "CTAS target table should not be treated as a source"
1518 );
1519
1520 let scope = parse_and_build_scope(
1522 "CREATE TABLE out_table AS WITH cte AS (SELECT 1 AS id FROM src) SELECT * FROM cte",
1523 );
1524 assert!(
1525 scope.sources.contains_key("cte"),
1526 "CTAS with CTE should resolve CTE as source"
1527 );
1528 assert!(
1529 !scope.sources.contains_key("out_table"),
1530 "CTAS target table should not be treated as a source"
1531 );
1532 assert_eq!(scope.cte_scopes.len(), 1);
1533 }
1534
1535 #[test]
1536 fn test_create_table_as_select_traverse() {
1537 let ast = Parser::parse_sql("CREATE TABLE t AS SELECT a FROM src").unwrap();
1538 let scopes = traverse_scope(&ast[0]);
1539 assert!(
1540 !scopes.is_empty(),
1541 "traverse_scope should return scopes for CTAS"
1542 );
1543 }
1544}