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            scope.add_source(name, expr.clone(), false);
621        }
622        Expression::Subquery(subquery) => {
623            let name = subquery
624                .alias
625                .as_ref()
626                .map(|a| a.name.clone())
627                .unwrap_or_default();
628
629            let mut derived_scope = scope.branch(subquery.this.clone(), ScopeType::DerivedTable);
630            build_scope_impl(&subquery.this, &mut derived_scope);
631
632            scope.add_source(name.clone(), expr.clone(), true);
633            scope.derived_table_scopes.push(derived_scope);
634        }
635        Expression::Paren(paren) => {
636            add_table_to_scope(&paren.this, scope);
637        }
638        _ => {}
639    }
640}
641
642fn collect_subqueries(expr: &Expression, parent_scope: &mut Scope) {
643    match expr {
644        Expression::Select(select) => {
645            // Check WHERE for subqueries
646            if let Some(where_clause) = &select.where_clause {
647                collect_subqueries_in_expr(&where_clause.this, parent_scope);
648            }
649            // Check SELECT expressions for subqueries
650            for e in &select.expressions {
651                collect_subqueries_in_expr(e, parent_scope);
652            }
653            // Check HAVING for subqueries
654            if let Some(having) = &select.having {
655                collect_subqueries_in_expr(&having.this, parent_scope);
656            }
657        }
658        _ => {}
659    }
660}
661
662fn collect_subqueries_in_expr(expr: &Expression, parent_scope: &mut Scope) {
663    match expr {
664        Expression::Subquery(subquery) if subquery.alias.is_none() => {
665            // This is a scalar subquery or IN subquery (not a derived table)
666            let mut sub_scope = parent_scope.branch(subquery.this.clone(), ScopeType::Subquery);
667            build_scope_impl(&subquery.this, &mut sub_scope);
668            parent_scope.subquery_scopes.push(sub_scope);
669        }
670        Expression::In(in_expr) => {
671            collect_subqueries_in_expr(&in_expr.this, parent_scope);
672            if let Some(query) = &in_expr.query {
673                let mut sub_scope = parent_scope.branch(query.clone(), ScopeType::Subquery);
674                build_scope_impl(query, &mut sub_scope);
675                parent_scope.subquery_scopes.push(sub_scope);
676            }
677        }
678        Expression::Exists(exists) => {
679            let mut sub_scope = parent_scope.branch(exists.this.clone(), ScopeType::Subquery);
680            build_scope_impl(&exists.this, &mut sub_scope);
681            parent_scope.subquery_scopes.push(sub_scope);
682        }
683        // Binary operations
684        Expression::And(bin)
685        | Expression::Or(bin)
686        | Expression::Add(bin)
687        | Expression::Sub(bin)
688        | Expression::Mul(bin)
689        | Expression::Div(bin)
690        | Expression::Mod(bin)
691        | Expression::Eq(bin)
692        | Expression::Neq(bin)
693        | Expression::Lt(bin)
694        | Expression::Lte(bin)
695        | Expression::Gt(bin)
696        | Expression::Gte(bin)
697        | Expression::BitwiseAnd(bin)
698        | Expression::BitwiseOr(bin)
699        | Expression::BitwiseXor(bin)
700        | Expression::Concat(bin) => {
701            collect_subqueries_in_expr(&bin.left, parent_scope);
702            collect_subqueries_in_expr(&bin.right, parent_scope);
703        }
704        // LIKE/ILIKE operations (have different structure with escape)
705        Expression::Like(like) | Expression::ILike(like) => {
706            collect_subqueries_in_expr(&like.left, parent_scope);
707            collect_subqueries_in_expr(&like.right, parent_scope);
708            if let Some(escape) = &like.escape {
709                collect_subqueries_in_expr(escape, parent_scope);
710            }
711        }
712        // Unary operations
713        Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
714            collect_subqueries_in_expr(&un.this, parent_scope);
715        }
716        Expression::Function(func) => {
717            for arg in &func.args {
718                collect_subqueries_in_expr(arg, parent_scope);
719            }
720        }
721        Expression::Case(case) => {
722            if let Some(operand) = &case.operand {
723                collect_subqueries_in_expr(operand, parent_scope);
724            }
725            for (when_expr, then_expr) in &case.whens {
726                collect_subqueries_in_expr(when_expr, parent_scope);
727                collect_subqueries_in_expr(then_expr, parent_scope);
728            }
729            if let Some(else_clause) = &case.else_ {
730                collect_subqueries_in_expr(else_clause, parent_scope);
731            }
732        }
733        Expression::Paren(paren) => {
734            collect_subqueries_in_expr(&paren.this, parent_scope);
735        }
736        Expression::Alias(alias) => {
737            collect_subqueries_in_expr(&alias.this, parent_scope);
738        }
739        _ => {}
740    }
741}
742
743/// Walk within a scope, yielding expressions without crossing scope boundaries.
744///
745/// This iterator visits all nodes in the syntax tree, stopping at nodes that
746/// start child scopes (CTEs, derived tables, subqueries in FROM/JOIN).
747///
748/// # Arguments
749/// * `expression` - The expression to walk
750/// * `bfs` - If true, uses breadth-first search; otherwise uses depth-first search
751///
752/// # Returns
753/// An iterator over expressions within the scope
754pub fn walk_in_scope<'a>(
755    expression: &'a Expression,
756    bfs: bool,
757) -> impl Iterator<Item = &'a Expression> {
758    WalkInScopeIter::new(expression, bfs)
759}
760
761/// Iterator for walking within a scope
762struct WalkInScopeIter<'a> {
763    queue: VecDeque<&'a Expression>,
764    bfs: bool,
765}
766
767impl<'a> WalkInScopeIter<'a> {
768    fn new(expression: &'a Expression, bfs: bool) -> Self {
769        let mut queue = VecDeque::new();
770        queue.push_back(expression);
771        Self { queue, bfs }
772    }
773
774    fn should_stop_at(&self, expr: &Expression, is_root: bool) -> bool {
775        if is_root {
776            return false;
777        }
778
779        // Stop at CTE definitions
780        if matches!(expr, Expression::Cte(_)) {
781            return true;
782        }
783
784        // Stop at subqueries that are derived tables (in FROM/JOIN)
785        if let Expression::Subquery(subquery) = expr {
786            if subquery.alias.is_some() {
787                return true;
788            }
789        }
790
791        // Stop at standalone SELECT/UNION/etc that would be subqueries
792        if matches!(
793            expr,
794            Expression::Select(_)
795                | Expression::Union(_)
796                | Expression::Intersect(_)
797                | Expression::Except(_)
798        ) {
799            return true;
800        }
801
802        false
803    }
804
805    fn get_children(&self, expr: &'a Expression) -> Vec<&'a Expression> {
806        let mut children = Vec::new();
807
808        match expr {
809            Expression::Select(select) => {
810                // Walk SELECT expressions
811                for e in &select.expressions {
812                    children.push(e);
813                }
814                // Walk FROM (but tables/subqueries create new scopes)
815                if let Some(from) = &select.from {
816                    for table in &from.expressions {
817                        if !self.should_stop_at(table, false) {
818                            children.push(table);
819                        }
820                    }
821                }
822                // Walk JOINs (but their sources create new scopes)
823                for join in &select.joins {
824                    if let Some(on) = &join.on {
825                        children.push(on);
826                    }
827                    // Don't traverse join.this as it's a source (table or subquery)
828                }
829                // Walk WHERE
830                if let Some(where_clause) = &select.where_clause {
831                    children.push(&where_clause.this);
832                }
833                // Walk GROUP BY
834                if let Some(group_by) = &select.group_by {
835                    for e in &group_by.expressions {
836                        children.push(e);
837                    }
838                }
839                // Walk HAVING
840                if let Some(having) = &select.having {
841                    children.push(&having.this);
842                }
843                // Walk ORDER BY
844                if let Some(order_by) = &select.order_by {
845                    for ord in &order_by.expressions {
846                        children.push(&ord.this);
847                    }
848                }
849                // Walk LIMIT
850                if let Some(limit) = &select.limit {
851                    children.push(&limit.this);
852                }
853                // Walk OFFSET
854                if let Some(offset) = &select.offset {
855                    children.push(&offset.this);
856                }
857            }
858            Expression::And(bin)
859            | Expression::Or(bin)
860            | Expression::Add(bin)
861            | Expression::Sub(bin)
862            | Expression::Mul(bin)
863            | Expression::Div(bin)
864            | Expression::Mod(bin)
865            | Expression::Eq(bin)
866            | Expression::Neq(bin)
867            | Expression::Lt(bin)
868            | Expression::Lte(bin)
869            | Expression::Gt(bin)
870            | Expression::Gte(bin)
871            | Expression::BitwiseAnd(bin)
872            | Expression::BitwiseOr(bin)
873            | Expression::BitwiseXor(bin)
874            | Expression::Concat(bin) => {
875                children.push(&bin.left);
876                children.push(&bin.right);
877            }
878            Expression::Like(like) | Expression::ILike(like) => {
879                children.push(&like.left);
880                children.push(&like.right);
881                if let Some(escape) = &like.escape {
882                    children.push(escape);
883                }
884            }
885            Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
886                children.push(&un.this);
887            }
888            Expression::Function(func) => {
889                for arg in &func.args {
890                    children.push(arg);
891                }
892            }
893            Expression::AggregateFunction(agg) => {
894                for arg in &agg.args {
895                    children.push(arg);
896                }
897            }
898            Expression::WindowFunction(wf) => {
899                children.push(&wf.this);
900                for e in &wf.over.partition_by {
901                    children.push(e);
902                }
903                for e in &wf.over.order_by {
904                    children.push(&e.this);
905                }
906            }
907            Expression::Alias(alias) => {
908                children.push(&alias.this);
909            }
910            Expression::Case(case) => {
911                if let Some(operand) = &case.operand {
912                    children.push(operand);
913                }
914                for (when_expr, then_expr) in &case.whens {
915                    children.push(when_expr);
916                    children.push(then_expr);
917                }
918                if let Some(else_clause) = &case.else_ {
919                    children.push(else_clause);
920                }
921            }
922            Expression::Paren(paren) => {
923                children.push(&paren.this);
924            }
925            Expression::Ordered(ord) => {
926                children.push(&ord.this);
927            }
928            Expression::In(in_expr) => {
929                children.push(&in_expr.this);
930                for e in &in_expr.expressions {
931                    children.push(e);
932                }
933                // Note: in_expr.query creates a new scope - don't traverse
934            }
935            Expression::Between(between) => {
936                children.push(&between.this);
937                children.push(&between.low);
938                children.push(&between.high);
939            }
940            Expression::IsNull(is_null) => {
941                children.push(&is_null.this);
942            }
943            Expression::Cast(cast) => {
944                children.push(&cast.this);
945            }
946            Expression::Extract(extract) => {
947                children.push(&extract.this);
948            }
949            Expression::Coalesce(coalesce) => {
950                for e in &coalesce.expressions {
951                    children.push(e);
952                }
953            }
954            Expression::NullIf(nullif) => {
955                children.push(&nullif.this);
956                children.push(&nullif.expression);
957            }
958            Expression::Table(_table) => {
959                // Tables don't have child expressions to traverse within scope
960                // (joins are handled at the Select level)
961            }
962            Expression::Column(_) | Expression::Literal(_) | Expression::Identifier(_) => {
963                // Leaf nodes - no children
964            }
965            // Subqueries and Exists create new scopes - don't traverse into them
966            Expression::Subquery(_) | Expression::Exists(_) => {}
967            _ => {
968                // For other expressions, we could add more cases as needed
969            }
970        }
971
972        children
973    }
974}
975
976impl<'a> Iterator for WalkInScopeIter<'a> {
977    type Item = &'a Expression;
978
979    fn next(&mut self) -> Option<Self::Item> {
980        let expr = if self.bfs {
981            self.queue.pop_front()?
982        } else {
983            self.queue.pop_back()?
984        };
985
986        // Get children that don't cross scope boundaries
987        let children = self.get_children(expr);
988
989        if self.bfs {
990            for child in children {
991                if !self.should_stop_at(child, false) {
992                    self.queue.push_back(child);
993                }
994            }
995        } else {
996            for child in children.into_iter().rev() {
997                if !self.should_stop_at(child, false) {
998                    self.queue.push_back(child);
999                }
1000            }
1001        }
1002
1003        Some(expr)
1004    }
1005}
1006
1007/// Find the first expression matching the predicate within this scope.
1008///
1009/// This does NOT traverse into subscopes.
1010///
1011/// # Arguments
1012/// * `expression` - The root expression
1013/// * `predicate` - Function that returns true for matching expressions
1014/// * `bfs` - If true, uses breadth-first search; otherwise depth-first
1015///
1016/// # Returns
1017/// The first matching expression, or None
1018pub fn find_in_scope<'a, F>(
1019    expression: &'a Expression,
1020    predicate: F,
1021    bfs: bool,
1022) -> Option<&'a Expression>
1023where
1024    F: Fn(&Expression) -> bool,
1025{
1026    walk_in_scope(expression, bfs).find(|e| predicate(e))
1027}
1028
1029/// Find all expressions matching the predicate within this scope.
1030///
1031/// This does NOT traverse into subscopes.
1032///
1033/// # Arguments
1034/// * `expression` - The root expression
1035/// * `predicate` - Function that returns true for matching expressions
1036/// * `bfs` - If true, uses breadth-first search; otherwise depth-first
1037///
1038/// # Returns
1039/// A vector of matching expressions
1040pub fn find_all_in_scope<'a, F>(
1041    expression: &'a Expression,
1042    predicate: F,
1043    bfs: bool,
1044) -> Vec<&'a Expression>
1045where
1046    F: Fn(&Expression) -> bool,
1047{
1048    walk_in_scope(expression, bfs)
1049        .filter(|e| predicate(e))
1050        .collect()
1051}
1052
1053/// Traverse an expression by its "scopes".
1054///
1055/// Returns a list of all scopes in depth-first post-order.
1056///
1057/// # Arguments
1058/// * `expression` - The expression to traverse
1059///
1060/// # Returns
1061/// A vector of all scopes found
1062pub fn traverse_scope(expression: &Expression) -> Vec<Scope> {
1063    match expression {
1064        Expression::Select(_)
1065        | Expression::Union(_)
1066        | Expression::Intersect(_)
1067        | Expression::Except(_) => {
1068            let root = build_scope(expression);
1069            root.traverse().into_iter().cloned().collect()
1070        }
1071        _ => Vec::new(),
1072    }
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078    use crate::parser::Parser;
1079
1080    fn parse_and_build_scope(sql: &str) -> Scope {
1081        let ast = Parser::parse_sql(sql).expect("Failed to parse SQL");
1082        build_scope(&ast[0])
1083    }
1084
1085    #[test]
1086    fn test_simple_select_scope() {
1087        let mut scope = parse_and_build_scope("SELECT a, b FROM t");
1088
1089        assert!(scope.is_root());
1090        assert!(!scope.can_be_correlated);
1091        assert!(scope.sources.contains_key("t"));
1092
1093        let columns = scope.columns();
1094        assert_eq!(columns.len(), 2);
1095    }
1096
1097    #[test]
1098    fn test_derived_table_scope() {
1099        let mut scope = parse_and_build_scope("SELECT x.a FROM (SELECT a FROM t) AS x");
1100
1101        assert!(scope.sources.contains_key("x"));
1102        assert_eq!(scope.derived_table_scopes.len(), 1);
1103
1104        let derived = &mut scope.derived_table_scopes[0];
1105        assert!(derived.is_derived_table());
1106        assert!(derived.sources.contains_key("t"));
1107    }
1108
1109    #[test]
1110    fn test_non_correlated_subquery() {
1111        let mut scope = parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s)");
1112
1113        assert_eq!(scope.subquery_scopes.len(), 1);
1114
1115        let subquery = &mut scope.subquery_scopes[0];
1116        assert!(subquery.is_subquery());
1117        assert!(subquery.can_be_correlated);
1118
1119        // The subquery references only 's', which is in its own sources
1120        assert!(subquery.sources.contains_key("s"));
1121        assert!(!subquery.is_correlated_subquery());
1122    }
1123
1124    #[test]
1125    fn test_correlated_subquery() {
1126        let mut scope =
1127            parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s WHERE s.x = t.y)");
1128
1129        assert_eq!(scope.subquery_scopes.len(), 1);
1130
1131        let subquery = &mut scope.subquery_scopes[0];
1132        assert!(subquery.is_subquery());
1133        assert!(subquery.can_be_correlated);
1134
1135        // The subquery references 't.y' which is external
1136        let external = subquery.external_columns();
1137        assert!(!external.is_empty());
1138        assert!(external.iter().any(|c| c.table.as_deref() == Some("t")));
1139        assert!(subquery.is_correlated_subquery());
1140    }
1141
1142    #[test]
1143    fn test_cte_scope() {
1144        let scope = parse_and_build_scope("WITH cte AS (SELECT a FROM t) SELECT * FROM cte");
1145
1146        assert_eq!(scope.cte_scopes.len(), 1);
1147        assert!(scope.cte_sources.contains_key("cte"));
1148
1149        let cte = &scope.cte_scopes[0];
1150        assert!(cte.is_cte());
1151    }
1152
1153    #[test]
1154    fn test_multiple_sources() {
1155        let scope = parse_and_build_scope("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
1156
1157        assert!(scope.sources.contains_key("t"));
1158        assert!(scope.sources.contains_key("s"));
1159        assert_eq!(scope.sources.len(), 2);
1160    }
1161
1162    #[test]
1163    fn test_aliased_table() {
1164        let scope = parse_and_build_scope("SELECT x.a FROM t AS x");
1165
1166        // Should be indexed by alias, not original name
1167        assert!(scope.sources.contains_key("x"));
1168        assert!(!scope.sources.contains_key("t"));
1169    }
1170
1171    #[test]
1172    fn test_local_columns() {
1173        let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1174
1175        let local = scope.local_columns();
1176        // All columns are local since both t and s are in scope.
1177        // Includes JOIN ON references (t.id, s.id).
1178        assert_eq!(local.len(), 5);
1179        assert!(local.iter().all(|c| c.table.is_some()));
1180    }
1181
1182    #[test]
1183    fn test_columns_include_join_on_clause_references() {
1184        let mut scope = parse_and_build_scope(
1185            "SELECT o.total FROM orders o JOIN customers c ON c.id = o.customer_id",
1186        );
1187
1188        let cols: Vec<String> = scope
1189            .columns()
1190            .iter()
1191            .map(|c| match &c.table {
1192                Some(t) => format!("{}.{}", t, c.name),
1193                None => c.name.clone(),
1194            })
1195            .collect();
1196
1197        assert!(cols.contains(&"o.total".to_string()));
1198        assert!(cols.contains(&"c.id".to_string()));
1199        assert!(cols.contains(&"o.customer_id".to_string()));
1200    }
1201
1202    #[test]
1203    fn test_unqualified_columns() {
1204        let mut scope = parse_and_build_scope("SELECT a, b, t.c FROM t");
1205
1206        let unqualified = scope.unqualified_columns();
1207        // Only a and b are unqualified
1208        assert_eq!(unqualified.len(), 2);
1209        assert!(unqualified.iter().all(|c| c.table.is_none()));
1210    }
1211
1212    #[test]
1213    fn test_source_columns() {
1214        let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1215
1216        let t_cols = scope.source_columns("t");
1217        // t.a, t.b, and t.id from JOIN condition
1218        assert!(t_cols.len() >= 2);
1219        assert!(t_cols.iter().all(|c| c.table.as_deref() == Some("t")));
1220
1221        let s_cols = scope.source_columns("s");
1222        // s.c and s.id from JOIN condition
1223        assert!(s_cols.len() >= 1);
1224        assert!(s_cols.iter().all(|c| c.table.as_deref() == Some("s")));
1225    }
1226
1227    #[test]
1228    fn test_rename_source() {
1229        let mut scope = parse_and_build_scope("SELECT a FROM t");
1230
1231        assert!(scope.sources.contains_key("t"));
1232        scope.rename_source("t", "new_name".to_string());
1233        assert!(!scope.sources.contains_key("t"));
1234        assert!(scope.sources.contains_key("new_name"));
1235    }
1236
1237    #[test]
1238    fn test_remove_source() {
1239        let mut scope = parse_and_build_scope("SELECT a FROM t");
1240
1241        assert!(scope.sources.contains_key("t"));
1242        scope.remove_source("t");
1243        assert!(!scope.sources.contains_key("t"));
1244    }
1245
1246    #[test]
1247    fn test_walk_in_scope() {
1248        let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1249        let expr = &ast[0];
1250
1251        // Walk should visit all expressions within the scope
1252        let walked: Vec<_> = walk_in_scope(expr, true).collect();
1253        assert!(!walked.is_empty());
1254
1255        // Should include the root SELECT
1256        assert!(walked.iter().any(|e| matches!(e, Expression::Select(_))));
1257        // Should include columns
1258        assert!(walked.iter().any(|e| matches!(e, Expression::Column(_))));
1259    }
1260
1261    #[test]
1262    fn test_find_in_scope() {
1263        let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1264        let expr = &ast[0];
1265
1266        // Find the first column
1267        let found = find_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1268        assert!(found.is_some());
1269        assert!(matches!(found.unwrap(), Expression::Column(_)));
1270    }
1271
1272    #[test]
1273    fn test_find_all_in_scope() {
1274        let ast = Parser::parse_sql("SELECT a, b, c FROM t").expect("Failed to parse");
1275        let expr = &ast[0];
1276
1277        // Find all columns
1278        let found = find_all_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1279        assert_eq!(found.len(), 3);
1280    }
1281
1282    #[test]
1283    fn test_traverse_scope() {
1284        let ast =
1285            Parser::parse_sql("SELECT a FROM (SELECT b FROM t) AS x").expect("Failed to parse");
1286        let expr = &ast[0];
1287
1288        let scopes = traverse_scope(expr);
1289        // traverse_scope returns all scopes via Scope::traverse
1290        // which includes derived table and root scopes
1291        assert!(!scopes.is_empty());
1292        // The root scope is always included
1293        assert!(scopes.iter().any(|s| s.is_root()));
1294    }
1295
1296    #[test]
1297    fn test_branch_with_options() {
1298        let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1299        let scope = build_scope(&ast[0]);
1300
1301        let child = scope.branch_with_options(
1302            ast[0].clone(),
1303            ScopeType::Subquery, // Use Subquery to test can_be_correlated
1304            None,
1305            None,
1306            Some(vec!["col1".to_string(), "col2".to_string()]),
1307        );
1308
1309        assert_eq!(child.outer_columns, vec!["col1", "col2"]);
1310        assert!(child.can_be_correlated); // Subqueries are correlated
1311    }
1312
1313    #[test]
1314    fn test_is_udtf() {
1315        let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1316        let scope = Scope::new(ast[0].clone());
1317        assert!(!scope.is_udtf());
1318
1319        let root = build_scope(&ast[0]);
1320        let udtf_scope = root.branch(ast[0].clone(), ScopeType::Udtf);
1321        assert!(udtf_scope.is_udtf());
1322    }
1323
1324    #[test]
1325    fn test_is_union() {
1326        let scope = parse_and_build_scope("SELECT a FROM t UNION SELECT b FROM s");
1327
1328        assert!(scope.is_root());
1329        assert_eq!(scope.union_scopes.len(), 2);
1330        // The children are set operation scopes
1331        assert!(scope.union_scopes[0].is_union());
1332        assert!(scope.union_scopes[1].is_union());
1333    }
1334
1335    #[test]
1336    fn test_clear_cache() {
1337        let mut scope = parse_and_build_scope("SELECT t.a FROM t");
1338
1339        // First call populates cache
1340        let _ = scope.columns();
1341        assert!(scope.columns_cache.is_some());
1342
1343        // Clear cache
1344        scope.clear_cache();
1345        assert!(scope.columns_cache.is_none());
1346        assert!(scope.external_columns_cache.is_none());
1347    }
1348
1349    #[test]
1350    fn test_scope_traverse() {
1351        let scope = parse_and_build_scope(
1352            "WITH cte AS (SELECT a FROM t) SELECT * FROM cte WHERE EXISTS (SELECT b FROM s)",
1353        );
1354
1355        let traversed = scope.traverse();
1356        // Should include: CTE scope, subquery scope, root scope
1357        assert!(traversed.len() >= 3);
1358    }
1359}