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