Skip to main content

polyglot_sql/
scope.rs

1//! Scope Analysis Module
2//!
3//! This module provides scope analysis for SQL queries, enabling detection of
4//! correlated subqueries, column references, and scope relationships.
5//!
6//! Ported from sqlglot's optimizer/scope.py
7
8use crate::expressions::Expression;
9use serde::{Deserialize, Serialize};
10use std::collections::{HashMap, HashSet, VecDeque};
11#[cfg(feature = "bindings")]
12use ts_rs::TS;
13
14/// Type of scope in a SQL query
15#[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 scope of the query
20    Root,
21    /// Subquery scope (e.g., WHERE x IN (SELECT ...))
22    Subquery,
23    /// Derived table scope (e.g., FROM (SELECT ...) AS t)
24    DerivedTable,
25    /// Common Table Expression scope
26    Cte,
27    /// Union/Intersect/Except scope
28    SetOperation,
29    /// User-Defined Table Function scope
30    Udtf,
31}
32
33/// Information about a source (table or subquery) in a scope
34#[derive(Debug, Clone)]
35pub struct SourceInfo {
36    /// The source expression (Table or subquery)
37    pub expression: Expression,
38    /// Whether this source is a scope (vs. a plain table)
39    pub is_scope: bool,
40}
41
42/// A column reference found in a scope
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct ColumnRef {
45    /// The table/alias qualifier (if any)
46    pub table: Option<String>,
47    /// The column name
48    pub name: String,
49}
50
51/// Represents a scope in a SQL query
52///
53/// A scope is the context of a SELECT statement and its sources.
54/// Scopes can be nested (subqueries, CTEs, derived tables) and form a tree.
55#[derive(Debug, Clone)]
56pub struct Scope {
57    /// The expression at the root of this scope
58    pub expression: Expression,
59
60    /// Type of this scope relative to its parent
61    pub scope_type: ScopeType,
62
63    /// Mapping of source names to their info
64    pub sources: HashMap<String, SourceInfo>,
65
66    /// Sources from LATERAL views (have access to preceding sources)
67    pub lateral_sources: HashMap<String, SourceInfo>,
68
69    /// CTE sources available to this scope
70    pub cte_sources: HashMap<String, SourceInfo>,
71
72    /// If this is a derived table or CTE with alias columns, this is that list
73    /// e.g., `SELECT * FROM (SELECT ...) AS y(col1, col2)` => ["col1", "col2"]
74    pub outer_columns: Vec<String>,
75
76    /// Whether this scope can potentially be correlated
77    /// (true for subqueries and UDTFs)
78    pub can_be_correlated: bool,
79
80    /// Child subquery scopes
81    pub subquery_scopes: Vec<Scope>,
82
83    /// Child derived table scopes
84    pub derived_table_scopes: Vec<Scope>,
85
86    /// Child CTE scopes
87    pub cte_scopes: Vec<Scope>,
88
89    /// Child UDTF (User Defined Table Function) scopes
90    pub udtf_scopes: Vec<Scope>,
91
92    /// Combined derived_table_scopes + udtf_scopes in definition order
93    pub table_scopes: Vec<Scope>,
94
95    /// Union/set operation scopes (left and right)
96    pub union_scopes: Vec<Scope>,
97
98    /// Cached columns
99    columns_cache: Option<Vec<ColumnRef>>,
100
101    /// Cached external columns
102    external_columns_cache: Option<Vec<ColumnRef>>,
103}
104
105impl Scope {
106    /// Create a new root scope
107    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    /// Create a child scope branching from this one
128    pub fn branch(&self, expression: Expression, scope_type: ScopeType) -> Self {
129        self.branch_with_options(expression, scope_type, None, None, None)
130    }
131
132    /// Create a child scope with additional options
133    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    /// Clear all cached properties
165    pub fn clear_cache(&mut self) {
166        self.columns_cache = None;
167        self.external_columns_cache = None;
168    }
169
170    /// Add a source to this scope
171    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    /// Add a lateral source to this scope
183    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    /// Add a CTE source to this scope
202    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    /// Rename a source
221    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    /// Remove a source
229    pub fn remove_source(&mut self, name: &str) {
230        self.sources.remove(name);
231        self.clear_cache();
232    }
233
234    /// Collect all column references in this scope
235    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    /// Get all source names in this scope
245    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    /// Get columns that reference sources outside this scope
252    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                // A column is external if it has a table qualifier that's not in our sources
264                match &col.table {
265                    Some(table) => !source_names.contains(table),
266                    None => false, // Unqualified columns might be local
267                }
268            })
269            .collect();
270
271        self.external_columns_cache = Some(external.clone());
272        external
273    }
274
275    /// Get columns that reference sources in this scope (not external)
276    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    /// Get unqualified columns (columns without table qualifier)
287    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    /// Get columns for a specific source
296    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    /// Determine if this scope is a correlated subquery
305    ///
306    /// A subquery is correlated if:
307    /// 1. It can be correlated (is a subquery or UDTF), AND
308    /// 2. It references columns from outer scopes
309    pub fn is_correlated_subquery(&mut self) -> bool {
310        self.can_be_correlated && !self.external_columns().is_empty()
311    }
312
313    /// Check if this is a subquery scope
314    pub fn is_subquery(&self) -> bool {
315        self.scope_type == ScopeType::Subquery
316    }
317
318    /// Check if this is a derived table scope
319    pub fn is_derived_table(&self) -> bool {
320        self.scope_type == ScopeType::DerivedTable
321    }
322
323    /// Check if this is a CTE scope
324    pub fn is_cte(&self) -> bool {
325        self.scope_type == ScopeType::Cte
326    }
327
328    /// Check if this is the root scope
329    pub fn is_root(&self) -> bool {
330        self.scope_type == ScopeType::Root
331    }
332
333    /// Check if this is a UDTF scope
334    pub fn is_udtf(&self) -> bool {
335        self.scope_type == ScopeType::Udtf
336    }
337
338    /// Check if this is a union/set operation scope
339    pub fn is_union(&self) -> bool {
340        self.scope_type == ScopeType::SetOperation
341    }
342
343    /// Traverse all scopes in this tree (depth-first post-order)
344    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        // First traverse children
352        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        // Then add self
365        result.push(self);
366    }
367
368    /// Count references to each scope in this tree
369    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
385/// Collect all column references from an expression tree
386fn 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            // Collect from SELECT expressions
396            for e in &select.expressions {
397                collect_columns(e, columns);
398            }
399            // Collect from JOIN ON / MATCH_CONDITION clauses
400            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            // Collect from WHERE
409            if let Some(where_clause) = &select.where_clause {
410                collect_columns(&where_clause.this, columns);
411            }
412            // Collect from HAVING
413            if let Some(having) = &select.having {
414                collect_columns(&having.this, columns);
415            }
416            // Collect from ORDER BY
417            if let Some(order_by) = &select.order_by {
418                for ord in &order_by.expressions {
419                    collect_columns(&ord.this, columns);
420                }
421            }
422            // Collect from GROUP BY
423            if let Some(group_by) = &select.group_by {
424                for e in &group_by.expressions {
425                    collect_columns(e, columns);
426                }
427            }
428            // Note: We don't recurse into FROM/JOIN source subqueries here
429            // as those create their own scopes.
430        }
431        // Binary operations
432        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        // LIKE/ILIKE operations
453        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        // Unary operations
461        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            // Note: in_expr.query is a subquery - creates its own scope
510        }
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            // These create their own scopes - don't collect from here
527        }
528        _ => {
529            // For other expressions, we might need to add more cases
530        }
531    }
532}
533
534/// Build scope tree from an expression
535///
536/// This traverses the expression tree and builds a hierarchy of Scope objects
537/// that track sources and column references at each level.
538pub 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            // Process CTEs first
548            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            // Process FROM clause
560            if let Some(from) = &select.from {
561                for table in &from.expressions {
562                    add_table_to_scope(table, current_scope);
563                }
564            }
565
566            // Process JOINs
567            for join in &select.joins {
568                add_table_to_scope(&join.this, current_scope);
569            }
570
571            // Process subqueries in WHERE, SELECT expressions, etc.
572            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            let cte_source = if table.schema.is_none() && table.catalog.is_none() {
621                scope.cte_sources.get(&table.name.name).or_else(|| {
622                    scope
623                        .cte_sources
624                        .iter()
625                        .find(|(cte_name, _)| cte_name.eq_ignore_ascii_case(&table.name.name))
626                        .map(|(_, source)| source)
627                })
628            } else {
629                None
630            };
631
632            if let Some(source) = cte_source {
633                scope.add_source(name, source.expression.clone(), true);
634            } else {
635                scope.add_source(name, expr.clone(), false);
636            }
637        }
638        Expression::Subquery(subquery) => {
639            let name = subquery
640                .alias
641                .as_ref()
642                .map(|a| a.name.clone())
643                .unwrap_or_default();
644
645            let mut derived_scope = scope.branch(subquery.this.clone(), ScopeType::DerivedTable);
646            build_scope_impl(&subquery.this, &mut derived_scope);
647
648            scope.add_source(name.clone(), expr.clone(), true);
649            scope.derived_table_scopes.push(derived_scope);
650        }
651        Expression::Paren(paren) => {
652            add_table_to_scope(&paren.this, scope);
653        }
654        _ => {}
655    }
656}
657
658fn collect_subqueries(expr: &Expression, parent_scope: &mut Scope) {
659    match expr {
660        Expression::Select(select) => {
661            // Check WHERE for subqueries
662            if let Some(where_clause) = &select.where_clause {
663                collect_subqueries_in_expr(&where_clause.this, parent_scope);
664            }
665            // Check SELECT expressions for subqueries
666            for e in &select.expressions {
667                collect_subqueries_in_expr(e, parent_scope);
668            }
669            // Check HAVING for subqueries
670            if let Some(having) = &select.having {
671                collect_subqueries_in_expr(&having.this, parent_scope);
672            }
673        }
674        _ => {}
675    }
676}
677
678fn collect_subqueries_in_expr(expr: &Expression, parent_scope: &mut Scope) {
679    match expr {
680        Expression::Subquery(subquery) if subquery.alias.is_none() => {
681            // This is a scalar subquery or IN subquery (not a derived table)
682            let mut sub_scope = parent_scope.branch(subquery.this.clone(), ScopeType::Subquery);
683            build_scope_impl(&subquery.this, &mut sub_scope);
684            parent_scope.subquery_scopes.push(sub_scope);
685        }
686        Expression::In(in_expr) => {
687            collect_subqueries_in_expr(&in_expr.this, parent_scope);
688            if let Some(query) = &in_expr.query {
689                let mut sub_scope = parent_scope.branch(query.clone(), ScopeType::Subquery);
690                build_scope_impl(query, &mut sub_scope);
691                parent_scope.subquery_scopes.push(sub_scope);
692            }
693        }
694        Expression::Exists(exists) => {
695            let mut sub_scope = parent_scope.branch(exists.this.clone(), ScopeType::Subquery);
696            build_scope_impl(&exists.this, &mut sub_scope);
697            parent_scope.subquery_scopes.push(sub_scope);
698        }
699        // Binary operations
700        Expression::And(bin)
701        | Expression::Or(bin)
702        | Expression::Add(bin)
703        | Expression::Sub(bin)
704        | Expression::Mul(bin)
705        | Expression::Div(bin)
706        | Expression::Mod(bin)
707        | Expression::Eq(bin)
708        | Expression::Neq(bin)
709        | Expression::Lt(bin)
710        | Expression::Lte(bin)
711        | Expression::Gt(bin)
712        | Expression::Gte(bin)
713        | Expression::BitwiseAnd(bin)
714        | Expression::BitwiseOr(bin)
715        | Expression::BitwiseXor(bin)
716        | Expression::Concat(bin) => {
717            collect_subqueries_in_expr(&bin.left, parent_scope);
718            collect_subqueries_in_expr(&bin.right, parent_scope);
719        }
720        // LIKE/ILIKE operations (have different structure with escape)
721        Expression::Like(like) | Expression::ILike(like) => {
722            collect_subqueries_in_expr(&like.left, parent_scope);
723            collect_subqueries_in_expr(&like.right, parent_scope);
724            if let Some(escape) = &like.escape {
725                collect_subqueries_in_expr(escape, parent_scope);
726            }
727        }
728        // Unary operations
729        Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
730            collect_subqueries_in_expr(&un.this, parent_scope);
731        }
732        Expression::Function(func) => {
733            for arg in &func.args {
734                collect_subqueries_in_expr(arg, parent_scope);
735            }
736        }
737        Expression::Case(case) => {
738            if let Some(operand) = &case.operand {
739                collect_subqueries_in_expr(operand, parent_scope);
740            }
741            for (when_expr, then_expr) in &case.whens {
742                collect_subqueries_in_expr(when_expr, parent_scope);
743                collect_subqueries_in_expr(then_expr, parent_scope);
744            }
745            if let Some(else_clause) = &case.else_ {
746                collect_subqueries_in_expr(else_clause, parent_scope);
747            }
748        }
749        Expression::Paren(paren) => {
750            collect_subqueries_in_expr(&paren.this, parent_scope);
751        }
752        Expression::Alias(alias) => {
753            collect_subqueries_in_expr(&alias.this, parent_scope);
754        }
755        _ => {}
756    }
757}
758
759/// Walk within a scope, yielding expressions without crossing scope boundaries.
760///
761/// This iterator visits all nodes in the syntax tree, stopping at nodes that
762/// start child scopes (CTEs, derived tables, subqueries in FROM/JOIN).
763///
764/// # Arguments
765/// * `expression` - The expression to walk
766/// * `bfs` - If true, uses breadth-first search; otherwise uses depth-first search
767///
768/// # Returns
769/// An iterator over expressions within the scope
770pub fn walk_in_scope<'a>(
771    expression: &'a Expression,
772    bfs: bool,
773) -> impl Iterator<Item = &'a Expression> {
774    WalkInScopeIter::new(expression, bfs)
775}
776
777/// Iterator for walking within a scope
778struct WalkInScopeIter<'a> {
779    queue: VecDeque<&'a Expression>,
780    bfs: bool,
781}
782
783impl<'a> WalkInScopeIter<'a> {
784    fn new(expression: &'a Expression, bfs: bool) -> Self {
785        let mut queue = VecDeque::new();
786        queue.push_back(expression);
787        Self { queue, bfs }
788    }
789
790    fn should_stop_at(&self, expr: &Expression, is_root: bool) -> bool {
791        if is_root {
792            return false;
793        }
794
795        // Stop at CTE definitions
796        if matches!(expr, Expression::Cte(_)) {
797            return true;
798        }
799
800        // Stop at subqueries that are derived tables (in FROM/JOIN)
801        if let Expression::Subquery(subquery) = expr {
802            if subquery.alias.is_some() {
803                return true;
804            }
805        }
806
807        // Stop at standalone SELECT/UNION/etc that would be subqueries
808        if matches!(
809            expr,
810            Expression::Select(_)
811                | Expression::Union(_)
812                | Expression::Intersect(_)
813                | Expression::Except(_)
814        ) {
815            return true;
816        }
817
818        false
819    }
820
821    fn get_children(&self, expr: &'a Expression) -> Vec<&'a Expression> {
822        let mut children = Vec::new();
823
824        match expr {
825            Expression::Select(select) => {
826                // Walk SELECT expressions
827                for e in &select.expressions {
828                    children.push(e);
829                }
830                // Walk FROM (but tables/subqueries create new scopes)
831                if let Some(from) = &select.from {
832                    for table in &from.expressions {
833                        if !self.should_stop_at(table, false) {
834                            children.push(table);
835                        }
836                    }
837                }
838                // Walk JOINs (but their sources create new scopes)
839                for join in &select.joins {
840                    if let Some(on) = &join.on {
841                        children.push(on);
842                    }
843                    // Don't traverse join.this as it's a source (table or subquery)
844                }
845                // Walk WHERE
846                if let Some(where_clause) = &select.where_clause {
847                    children.push(&where_clause.this);
848                }
849                // Walk GROUP BY
850                if let Some(group_by) = &select.group_by {
851                    for e in &group_by.expressions {
852                        children.push(e);
853                    }
854                }
855                // Walk HAVING
856                if let Some(having) = &select.having {
857                    children.push(&having.this);
858                }
859                // Walk ORDER BY
860                if let Some(order_by) = &select.order_by {
861                    for ord in &order_by.expressions {
862                        children.push(&ord.this);
863                    }
864                }
865                // Walk LIMIT
866                if let Some(limit) = &select.limit {
867                    children.push(&limit.this);
868                }
869                // Walk OFFSET
870                if let Some(offset) = &select.offset {
871                    children.push(&offset.this);
872                }
873            }
874            Expression::And(bin)
875            | Expression::Or(bin)
876            | Expression::Add(bin)
877            | Expression::Sub(bin)
878            | Expression::Mul(bin)
879            | Expression::Div(bin)
880            | Expression::Mod(bin)
881            | Expression::Eq(bin)
882            | Expression::Neq(bin)
883            | Expression::Lt(bin)
884            | Expression::Lte(bin)
885            | Expression::Gt(bin)
886            | Expression::Gte(bin)
887            | Expression::BitwiseAnd(bin)
888            | Expression::BitwiseOr(bin)
889            | Expression::BitwiseXor(bin)
890            | Expression::Concat(bin) => {
891                children.push(&bin.left);
892                children.push(&bin.right);
893            }
894            Expression::Like(like) | Expression::ILike(like) => {
895                children.push(&like.left);
896                children.push(&like.right);
897                if let Some(escape) = &like.escape {
898                    children.push(escape);
899                }
900            }
901            Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
902                children.push(&un.this);
903            }
904            Expression::Function(func) => {
905                for arg in &func.args {
906                    children.push(arg);
907                }
908            }
909            Expression::AggregateFunction(agg) => {
910                for arg in &agg.args {
911                    children.push(arg);
912                }
913            }
914            Expression::WindowFunction(wf) => {
915                children.push(&wf.this);
916                for e in &wf.over.partition_by {
917                    children.push(e);
918                }
919                for e in &wf.over.order_by {
920                    children.push(&e.this);
921                }
922            }
923            Expression::Alias(alias) => {
924                children.push(&alias.this);
925            }
926            Expression::Case(case) => {
927                if let Some(operand) = &case.operand {
928                    children.push(operand);
929                }
930                for (when_expr, then_expr) in &case.whens {
931                    children.push(when_expr);
932                    children.push(then_expr);
933                }
934                if let Some(else_clause) = &case.else_ {
935                    children.push(else_clause);
936                }
937            }
938            Expression::Paren(paren) => {
939                children.push(&paren.this);
940            }
941            Expression::Ordered(ord) => {
942                children.push(&ord.this);
943            }
944            Expression::In(in_expr) => {
945                children.push(&in_expr.this);
946                for e in &in_expr.expressions {
947                    children.push(e);
948                }
949                // Note: in_expr.query creates a new scope - don't traverse
950            }
951            Expression::Between(between) => {
952                children.push(&between.this);
953                children.push(&between.low);
954                children.push(&between.high);
955            }
956            Expression::IsNull(is_null) => {
957                children.push(&is_null.this);
958            }
959            Expression::Cast(cast) => {
960                children.push(&cast.this);
961            }
962            Expression::Extract(extract) => {
963                children.push(&extract.this);
964            }
965            Expression::Coalesce(coalesce) => {
966                for e in &coalesce.expressions {
967                    children.push(e);
968                }
969            }
970            Expression::NullIf(nullif) => {
971                children.push(&nullif.this);
972                children.push(&nullif.expression);
973            }
974            Expression::Table(_table) => {
975                // Tables don't have child expressions to traverse within scope
976                // (joins are handled at the Select level)
977            }
978            Expression::Column(_) | Expression::Literal(_) | Expression::Identifier(_) => {
979                // Leaf nodes - no children
980            }
981            // Subqueries and Exists create new scopes - don't traverse into them
982            Expression::Subquery(_) | Expression::Exists(_) => {}
983            _ => {
984                // For other expressions, we could add more cases as needed
985            }
986        }
987
988        children
989    }
990}
991
992impl<'a> Iterator for WalkInScopeIter<'a> {
993    type Item = &'a Expression;
994
995    fn next(&mut self) -> Option<Self::Item> {
996        let expr = if self.bfs {
997            self.queue.pop_front()?
998        } else {
999            self.queue.pop_back()?
1000        };
1001
1002        // Get children that don't cross scope boundaries
1003        let children = self.get_children(expr);
1004
1005        if self.bfs {
1006            for child in children {
1007                if !self.should_stop_at(child, false) {
1008                    self.queue.push_back(child);
1009                }
1010            }
1011        } else {
1012            for child in children.into_iter().rev() {
1013                if !self.should_stop_at(child, false) {
1014                    self.queue.push_back(child);
1015                }
1016            }
1017        }
1018
1019        Some(expr)
1020    }
1021}
1022
1023/// Find the first expression matching the predicate within this scope.
1024///
1025/// This does NOT traverse into subscopes.
1026///
1027/// # Arguments
1028/// * `expression` - The root expression
1029/// * `predicate` - Function that returns true for matching expressions
1030/// * `bfs` - If true, uses breadth-first search; otherwise depth-first
1031///
1032/// # Returns
1033/// The first matching expression, or None
1034pub fn find_in_scope<'a, F>(
1035    expression: &'a Expression,
1036    predicate: F,
1037    bfs: bool,
1038) -> Option<&'a Expression>
1039where
1040    F: Fn(&Expression) -> bool,
1041{
1042    walk_in_scope(expression, bfs).find(|e| predicate(e))
1043}
1044
1045/// Find all expressions matching the predicate within this scope.
1046///
1047/// This does NOT traverse into subscopes.
1048///
1049/// # Arguments
1050/// * `expression` - The root expression
1051/// * `predicate` - Function that returns true for matching expressions
1052/// * `bfs` - If true, uses breadth-first search; otherwise depth-first
1053///
1054/// # Returns
1055/// A vector of matching expressions
1056pub fn find_all_in_scope<'a, F>(
1057    expression: &'a Expression,
1058    predicate: F,
1059    bfs: bool,
1060) -> Vec<&'a Expression>
1061where
1062    F: Fn(&Expression) -> bool,
1063{
1064    walk_in_scope(expression, bfs)
1065        .filter(|e| predicate(e))
1066        .collect()
1067}
1068
1069/// Traverse an expression by its "scopes".
1070///
1071/// Returns a list of all scopes in depth-first post-order.
1072///
1073/// # Arguments
1074/// * `expression` - The expression to traverse
1075///
1076/// # Returns
1077/// A vector of all scopes found
1078pub fn traverse_scope(expression: &Expression) -> Vec<Scope> {
1079    match expression {
1080        Expression::Select(_)
1081        | Expression::Union(_)
1082        | Expression::Intersect(_)
1083        | Expression::Except(_) => {
1084            let root = build_scope(expression);
1085            root.traverse().into_iter().cloned().collect()
1086        }
1087        _ => Vec::new(),
1088    }
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use super::*;
1094    use crate::parser::Parser;
1095
1096    fn parse_and_build_scope(sql: &str) -> Scope {
1097        let ast = Parser::parse_sql(sql).expect("Failed to parse SQL");
1098        build_scope(&ast[0])
1099    }
1100
1101    #[test]
1102    fn test_simple_select_scope() {
1103        let mut scope = parse_and_build_scope("SELECT a, b FROM t");
1104
1105        assert!(scope.is_root());
1106        assert!(!scope.can_be_correlated);
1107        assert!(scope.sources.contains_key("t"));
1108
1109        let columns = scope.columns();
1110        assert_eq!(columns.len(), 2);
1111    }
1112
1113    #[test]
1114    fn test_derived_table_scope() {
1115        let mut scope = parse_and_build_scope("SELECT x.a FROM (SELECT a FROM t) AS x");
1116
1117        assert!(scope.sources.contains_key("x"));
1118        assert_eq!(scope.derived_table_scopes.len(), 1);
1119
1120        let derived = &mut scope.derived_table_scopes[0];
1121        assert!(derived.is_derived_table());
1122        assert!(derived.sources.contains_key("t"));
1123    }
1124
1125    #[test]
1126    fn test_non_correlated_subquery() {
1127        let mut scope = parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s)");
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        // The subquery references only 's', which is in its own sources
1136        assert!(subquery.sources.contains_key("s"));
1137        assert!(!subquery.is_correlated_subquery());
1138    }
1139
1140    #[test]
1141    fn test_correlated_subquery() {
1142        let mut scope =
1143            parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s WHERE s.x = t.y)");
1144
1145        assert_eq!(scope.subquery_scopes.len(), 1);
1146
1147        let subquery = &mut scope.subquery_scopes[0];
1148        assert!(subquery.is_subquery());
1149        assert!(subquery.can_be_correlated);
1150
1151        // The subquery references 't.y' which is external
1152        let external = subquery.external_columns();
1153        assert!(!external.is_empty());
1154        assert!(external.iter().any(|c| c.table.as_deref() == Some("t")));
1155        assert!(subquery.is_correlated_subquery());
1156    }
1157
1158    #[test]
1159    fn test_cte_scope() {
1160        let scope = parse_and_build_scope("WITH cte AS (SELECT a FROM t) SELECT * FROM cte");
1161
1162        assert_eq!(scope.cte_scopes.len(), 1);
1163        assert!(scope.cte_sources.contains_key("cte"));
1164
1165        let cte = &scope.cte_scopes[0];
1166        assert!(cte.is_cte());
1167    }
1168
1169    #[test]
1170    fn test_multiple_sources() {
1171        let scope = parse_and_build_scope("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
1172
1173        assert!(scope.sources.contains_key("t"));
1174        assert!(scope.sources.contains_key("s"));
1175        assert_eq!(scope.sources.len(), 2);
1176    }
1177
1178    #[test]
1179    fn test_aliased_table() {
1180        let scope = parse_and_build_scope("SELECT x.a FROM t AS x");
1181
1182        // Should be indexed by alias, not original name
1183        assert!(scope.sources.contains_key("x"));
1184        assert!(!scope.sources.contains_key("t"));
1185    }
1186
1187    #[test]
1188    fn test_local_columns() {
1189        let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1190
1191        let local = scope.local_columns();
1192        // All columns are local since both t and s are in scope.
1193        // Includes JOIN ON references (t.id, s.id).
1194        assert_eq!(local.len(), 5);
1195        assert!(local.iter().all(|c| c.table.is_some()));
1196    }
1197
1198    #[test]
1199    fn test_columns_include_join_on_clause_references() {
1200        let mut scope = parse_and_build_scope(
1201            "SELECT o.total FROM orders o JOIN customers c ON c.id = o.customer_id",
1202        );
1203
1204        let cols: Vec<String> = scope
1205            .columns()
1206            .iter()
1207            .map(|c| match &c.table {
1208                Some(t) => format!("{}.{}", t, c.name),
1209                None => c.name.clone(),
1210            })
1211            .collect();
1212
1213        assert!(cols.contains(&"o.total".to_string()));
1214        assert!(cols.contains(&"c.id".to_string()));
1215        assert!(cols.contains(&"o.customer_id".to_string()));
1216    }
1217
1218    #[test]
1219    fn test_unqualified_columns() {
1220        let mut scope = parse_and_build_scope("SELECT a, b, t.c FROM t");
1221
1222        let unqualified = scope.unqualified_columns();
1223        // Only a and b are unqualified
1224        assert_eq!(unqualified.len(), 2);
1225        assert!(unqualified.iter().all(|c| c.table.is_none()));
1226    }
1227
1228    #[test]
1229    fn test_source_columns() {
1230        let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1231
1232        let t_cols = scope.source_columns("t");
1233        // t.a, t.b, and t.id from JOIN condition
1234        assert!(t_cols.len() >= 2);
1235        assert!(t_cols.iter().all(|c| c.table.as_deref() == Some("t")));
1236
1237        let s_cols = scope.source_columns("s");
1238        // s.c and s.id from JOIN condition
1239        assert!(s_cols.len() >= 1);
1240        assert!(s_cols.iter().all(|c| c.table.as_deref() == Some("s")));
1241    }
1242
1243    #[test]
1244    fn test_rename_source() {
1245        let mut scope = parse_and_build_scope("SELECT a FROM t");
1246
1247        assert!(scope.sources.contains_key("t"));
1248        scope.rename_source("t", "new_name".to_string());
1249        assert!(!scope.sources.contains_key("t"));
1250        assert!(scope.sources.contains_key("new_name"));
1251    }
1252
1253    #[test]
1254    fn test_remove_source() {
1255        let mut scope = parse_and_build_scope("SELECT a FROM t");
1256
1257        assert!(scope.sources.contains_key("t"));
1258        scope.remove_source("t");
1259        assert!(!scope.sources.contains_key("t"));
1260    }
1261
1262    #[test]
1263    fn test_walk_in_scope() {
1264        let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1265        let expr = &ast[0];
1266
1267        // Walk should visit all expressions within the scope
1268        let walked: Vec<_> = walk_in_scope(expr, true).collect();
1269        assert!(!walked.is_empty());
1270
1271        // Should include the root SELECT
1272        assert!(walked.iter().any(|e| matches!(e, Expression::Select(_))));
1273        // Should include columns
1274        assert!(walked.iter().any(|e| matches!(e, Expression::Column(_))));
1275    }
1276
1277    #[test]
1278    fn test_find_in_scope() {
1279        let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1280        let expr = &ast[0];
1281
1282        // Find the first column
1283        let found = find_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1284        assert!(found.is_some());
1285        assert!(matches!(found.unwrap(), Expression::Column(_)));
1286    }
1287
1288    #[test]
1289    fn test_find_all_in_scope() {
1290        let ast = Parser::parse_sql("SELECT a, b, c FROM t").expect("Failed to parse");
1291        let expr = &ast[0];
1292
1293        // Find all columns
1294        let found = find_all_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1295        assert_eq!(found.len(), 3);
1296    }
1297
1298    #[test]
1299    fn test_traverse_scope() {
1300        let ast =
1301            Parser::parse_sql("SELECT a FROM (SELECT b FROM t) AS x").expect("Failed to parse");
1302        let expr = &ast[0];
1303
1304        let scopes = traverse_scope(expr);
1305        // traverse_scope returns all scopes via Scope::traverse
1306        // which includes derived table and root scopes
1307        assert!(!scopes.is_empty());
1308        // The root scope is always included
1309        assert!(scopes.iter().any(|s| s.is_root()));
1310    }
1311
1312    #[test]
1313    fn test_branch_with_options() {
1314        let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1315        let scope = build_scope(&ast[0]);
1316
1317        let child = scope.branch_with_options(
1318            ast[0].clone(),
1319            ScopeType::Subquery, // Use Subquery to test can_be_correlated
1320            None,
1321            None,
1322            Some(vec!["col1".to_string(), "col2".to_string()]),
1323        );
1324
1325        assert_eq!(child.outer_columns, vec!["col1", "col2"]);
1326        assert!(child.can_be_correlated); // Subqueries are correlated
1327    }
1328
1329    #[test]
1330    fn test_is_udtf() {
1331        let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1332        let scope = Scope::new(ast[0].clone());
1333        assert!(!scope.is_udtf());
1334
1335        let root = build_scope(&ast[0]);
1336        let udtf_scope = root.branch(ast[0].clone(), ScopeType::Udtf);
1337        assert!(udtf_scope.is_udtf());
1338    }
1339
1340    #[test]
1341    fn test_is_union() {
1342        let scope = parse_and_build_scope("SELECT a FROM t UNION SELECT b FROM s");
1343
1344        assert!(scope.is_root());
1345        assert_eq!(scope.union_scopes.len(), 2);
1346        // The children are set operation scopes
1347        assert!(scope.union_scopes[0].is_union());
1348        assert!(scope.union_scopes[1].is_union());
1349    }
1350
1351    #[test]
1352    fn test_clear_cache() {
1353        let mut scope = parse_and_build_scope("SELECT t.a FROM t");
1354
1355        // First call populates cache
1356        let _ = scope.columns();
1357        assert!(scope.columns_cache.is_some());
1358
1359        // Clear cache
1360        scope.clear_cache();
1361        assert!(scope.columns_cache.is_none());
1362        assert!(scope.external_columns_cache.is_none());
1363    }
1364
1365    #[test]
1366    fn test_scope_traverse() {
1367        let scope = parse_and_build_scope(
1368            "WITH cte AS (SELECT a FROM t) SELECT * FROM cte WHERE EXISTS (SELECT b FROM s)",
1369        );
1370
1371        let traversed = scope.traverse();
1372        // Should include: CTE scope, subquery scope, root scope
1373        assert!(traversed.len() >= 3);
1374    }
1375}