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 table-generating lateral views (Hive/Spark style UDTFs).
643            for lateral_view in &select.lateral_views {
644                add_lateral_view_to_scope(lateral_view, current_scope);
645            }
646
647            // Process subqueries in WHERE, SELECT expressions, etc.
648            collect_subqueries(expression, current_scope);
649        }
650        Expression::Union(union) => {
651            let mut left_scope = current_scope.branch(union.left.clone(), ScopeType::SetOperation);
652            build_scope_impl(&union.left, &mut left_scope);
653
654            let mut right_scope =
655                current_scope.branch(union.right.clone(), ScopeType::SetOperation);
656            build_scope_impl(&union.right, &mut right_scope);
657
658            current_scope.union_scopes.push(left_scope);
659            current_scope.union_scopes.push(right_scope);
660        }
661        Expression::Intersect(intersect) => {
662            let mut left_scope =
663                current_scope.branch(intersect.left.clone(), ScopeType::SetOperation);
664            build_scope_impl(&intersect.left, &mut left_scope);
665
666            let mut right_scope =
667                current_scope.branch(intersect.right.clone(), ScopeType::SetOperation);
668            build_scope_impl(&intersect.right, &mut right_scope);
669
670            current_scope.union_scopes.push(left_scope);
671            current_scope.union_scopes.push(right_scope);
672        }
673        Expression::Except(except) => {
674            let mut left_scope = current_scope.branch(except.left.clone(), ScopeType::SetOperation);
675            build_scope_impl(&except.left, &mut left_scope);
676
677            let mut right_scope =
678                current_scope.branch(except.right.clone(), ScopeType::SetOperation);
679            build_scope_impl(&except.right, &mut right_scope);
680
681            current_scope.union_scopes.push(left_scope);
682            current_scope.union_scopes.push(right_scope);
683        }
684        Expression::CreateTable(create) => {
685            // Handle CREATE TABLE ... AS [WITH ...] SELECT ...
686            // Process CTEs if present
687            if let Some(with) = &create.with_cte {
688                for cte in &with.ctes {
689                    let cte_name = cte.alias.name.clone();
690                    let mut cte_scope = current_scope
691                        .branch(Expression::Cte(Box::new(cte.clone())), ScopeType::Cte);
692                    build_scope_impl(&cte.this, &mut cte_scope);
693                    current_scope.add_cte_source(cte_name, Expression::Cte(Box::new(cte.clone())));
694                    current_scope.cte_scopes.push(cte_scope);
695                }
696            }
697            // Traverse the AS SELECT body
698            if let Some(as_select) = &create.as_select {
699                build_scope_impl(as_select, current_scope);
700            }
701        }
702        _ => {}
703    }
704}
705
706fn add_table_to_scope(expr: &Expression, scope: &mut Scope) {
707    match expr {
708        Expression::Table(table) => {
709            let name = table
710                .alias
711                .as_ref()
712                .map(|a| a.name.clone())
713                .unwrap_or_else(|| table.name.name.clone());
714            let cte_source = if table.schema.is_none() && table.catalog.is_none() {
715                scope.cte_sources.get(&table.name.name).or_else(|| {
716                    scope
717                        .cte_sources
718                        .iter()
719                        .find(|(cte_name, _)| cte_name.eq_ignore_ascii_case(&table.name.name))
720                        .map(|(_, source)| source)
721                })
722            } else {
723                None
724            };
725
726            if let Some(source) = cte_source {
727                scope.add_source_info(name, source.clone());
728            } else {
729                scope.add_source(name, expr.clone(), false);
730            }
731        }
732        Expression::Subquery(subquery) => {
733            let name = subquery
734                .alias
735                .as_ref()
736                .map(|a| a.name.clone())
737                .unwrap_or_default();
738
739            let mut derived_scope = scope.branch(subquery.this.clone(), ScopeType::DerivedTable);
740            build_scope_impl(&subquery.this, &mut derived_scope);
741
742            scope.add_source(name.clone(), expr.clone(), true);
743            scope.derived_table_scopes.push(derived_scope);
744        }
745        Expression::Unnest(unnest) => {
746            if let Some(alias) = &unnest.alias {
747                scope.add_virtual_source(alias.name.clone(), expr.clone());
748            }
749        }
750        Expression::Alias(alias) if matches!(&alias.this, Expression::Unnest(_)) => {
751            scope.add_virtual_source(alias.alias.name.clone(), expr.clone());
752        }
753        Expression::Lateral(lateral) => {
754            if let Some(alias) = &lateral.alias {
755                scope.add_virtual_source(alias.clone(), expr.clone());
756            }
757        }
758        Expression::LateralView(lateral_view) => {
759            add_lateral_view_to_scope(lateral_view, scope);
760        }
761        Expression::Paren(paren) => {
762            add_table_to_scope(&paren.this, scope);
763        }
764        _ => {}
765    }
766}
767
768fn add_lateral_view_to_scope(lateral_view: &crate::expressions::LateralView, scope: &mut Scope) {
769    let alias = lateral_view
770        .table_alias
771        .as_ref()
772        .or_else(|| lateral_view.column_aliases.first())
773        .map(|alias| alias.name.clone());
774
775    if let Some(alias) = alias {
776        scope.add_virtual_source(
777            alias,
778            Expression::LateralView(Box::new(lateral_view.clone())),
779        );
780    }
781}
782
783fn collect_subqueries(expr: &Expression, parent_scope: &mut Scope) {
784    match expr {
785        Expression::Select(select) => {
786            // Check WHERE for subqueries
787            if let Some(where_clause) = &select.where_clause {
788                collect_subqueries_in_expr(&where_clause.this, parent_scope);
789            }
790            // Check SELECT expressions for subqueries
791            for e in &select.expressions {
792                collect_subqueries_in_expr(e, parent_scope);
793            }
794            // Check HAVING for subqueries
795            if let Some(having) = &select.having {
796                collect_subqueries_in_expr(&having.this, parent_scope);
797            }
798        }
799        _ => {}
800    }
801}
802
803fn collect_subqueries_in_expr(expr: &Expression, parent_scope: &mut Scope) {
804    match expr {
805        Expression::Subquery(subquery) if subquery.alias.is_none() => {
806            // This is a scalar subquery or IN subquery (not a derived table)
807            let mut sub_scope = parent_scope.branch(subquery.this.clone(), ScopeType::Subquery);
808            build_scope_impl(&subquery.this, &mut sub_scope);
809            parent_scope.subquery_scopes.push(sub_scope);
810        }
811        Expression::In(in_expr) => {
812            collect_subqueries_in_expr(&in_expr.this, parent_scope);
813            if let Some(query) = &in_expr.query {
814                let mut sub_scope = parent_scope.branch(query.clone(), ScopeType::Subquery);
815                build_scope_impl(query, &mut sub_scope);
816                parent_scope.subquery_scopes.push(sub_scope);
817            }
818        }
819        Expression::Exists(exists) => {
820            let mut sub_scope = parent_scope.branch(exists.this.clone(), ScopeType::Subquery);
821            build_scope_impl(&exists.this, &mut sub_scope);
822            parent_scope.subquery_scopes.push(sub_scope);
823        }
824        // Binary operations
825        Expression::And(bin)
826        | Expression::Or(bin)
827        | Expression::Add(bin)
828        | Expression::Sub(bin)
829        | Expression::Mul(bin)
830        | Expression::Div(bin)
831        | Expression::Mod(bin)
832        | Expression::Eq(bin)
833        | Expression::Neq(bin)
834        | Expression::Lt(bin)
835        | Expression::Lte(bin)
836        | Expression::Gt(bin)
837        | Expression::Gte(bin)
838        | Expression::BitwiseAnd(bin)
839        | Expression::BitwiseOr(bin)
840        | Expression::BitwiseXor(bin)
841        | Expression::Concat(bin) => {
842            collect_subqueries_in_expr(&bin.left, parent_scope);
843            collect_subqueries_in_expr(&bin.right, parent_scope);
844        }
845        // LIKE/ILIKE operations (have different structure with escape)
846        Expression::Like(like) | Expression::ILike(like) => {
847            collect_subqueries_in_expr(&like.left, parent_scope);
848            collect_subqueries_in_expr(&like.right, parent_scope);
849            if let Some(escape) = &like.escape {
850                collect_subqueries_in_expr(escape, parent_scope);
851            }
852        }
853        // Unary operations
854        Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
855            collect_subqueries_in_expr(&un.this, parent_scope);
856        }
857        Expression::Function(func) => {
858            for arg in &func.args {
859                collect_subqueries_in_expr(arg, parent_scope);
860            }
861        }
862        Expression::Case(case) => {
863            if let Some(operand) = &case.operand {
864                collect_subqueries_in_expr(operand, parent_scope);
865            }
866            for (when_expr, then_expr) in &case.whens {
867                collect_subqueries_in_expr(when_expr, parent_scope);
868                collect_subqueries_in_expr(then_expr, parent_scope);
869            }
870            if let Some(else_clause) = &case.else_ {
871                collect_subqueries_in_expr(else_clause, parent_scope);
872            }
873        }
874        Expression::Paren(paren) => {
875            collect_subqueries_in_expr(&paren.this, parent_scope);
876        }
877        Expression::Alias(alias) => {
878            collect_subqueries_in_expr(&alias.this, parent_scope);
879        }
880        _ => {}
881    }
882}
883
884/// Walk within a scope, yielding expressions without crossing scope boundaries.
885///
886/// This iterator visits all nodes in the syntax tree, stopping at nodes that
887/// start child scopes (CTEs, derived tables, subqueries in FROM/JOIN).
888///
889/// # Arguments
890/// * `expression` - The expression to walk
891/// * `bfs` - If true, uses breadth-first search; otherwise uses depth-first search
892///
893/// # Returns
894/// An iterator over expressions within the scope
895pub fn walk_in_scope<'a>(
896    expression: &'a Expression,
897    bfs: bool,
898) -> impl Iterator<Item = &'a Expression> {
899    WalkInScopeIter::new(expression, bfs)
900}
901
902/// Iterator for walking within a scope
903struct WalkInScopeIter<'a> {
904    queue: VecDeque<&'a Expression>,
905    bfs: bool,
906}
907
908impl<'a> WalkInScopeIter<'a> {
909    fn new(expression: &'a Expression, bfs: bool) -> Self {
910        let mut queue = VecDeque::new();
911        queue.push_back(expression);
912        Self { queue, bfs }
913    }
914
915    fn should_stop_at(&self, expr: &Expression, is_root: bool) -> bool {
916        if is_root {
917            return false;
918        }
919
920        // Stop at CTE definitions
921        if matches!(expr, Expression::Cte(_)) {
922            return true;
923        }
924
925        // Stop at subqueries that are derived tables (in FROM/JOIN)
926        if let Expression::Subquery(subquery) = expr {
927            if subquery.alias.is_some() {
928                return true;
929            }
930        }
931
932        // Stop at standalone SELECT/UNION/etc that would be subqueries
933        if matches!(
934            expr,
935            Expression::Select(_)
936                | Expression::Union(_)
937                | Expression::Intersect(_)
938                | Expression::Except(_)
939        ) {
940            return true;
941        }
942
943        false
944    }
945
946    fn get_children(&self, expr: &'a Expression) -> Vec<&'a Expression> {
947        let mut children = Vec::new();
948
949        match expr {
950            Expression::Prepare(prepare) => {
951                children.push(&prepare.statement);
952            }
953            Expression::Select(select) => {
954                // Walk SELECT expressions
955                for e in &select.expressions {
956                    children.push(e);
957                }
958                // Walk FROM (but tables/subqueries create new scopes)
959                if let Some(from) = &select.from {
960                    for table in &from.expressions {
961                        if !self.should_stop_at(table, false) {
962                            children.push(table);
963                        }
964                    }
965                }
966                // Walk JOINs (but their sources create new scopes)
967                for join in &select.joins {
968                    if let Some(on) = &join.on {
969                        children.push(on);
970                    }
971                    // Don't traverse join.this as it's a source (table or subquery)
972                }
973                // Walk WHERE
974                if let Some(where_clause) = &select.where_clause {
975                    children.push(&where_clause.this);
976                }
977                // Walk GROUP BY
978                if let Some(group_by) = &select.group_by {
979                    for e in &group_by.expressions {
980                        children.push(e);
981                    }
982                }
983                // Walk HAVING
984                if let Some(having) = &select.having {
985                    children.push(&having.this);
986                }
987                // Walk ORDER BY
988                if let Some(order_by) = &select.order_by {
989                    for ord in &order_by.expressions {
990                        children.push(&ord.this);
991                    }
992                }
993                // Walk LIMIT
994                if let Some(limit) = &select.limit {
995                    children.push(&limit.this);
996                }
997                // Walk OFFSET
998                if let Some(offset) = &select.offset {
999                    children.push(&offset.this);
1000                }
1001            }
1002            Expression::And(bin)
1003            | Expression::Or(bin)
1004            | Expression::Add(bin)
1005            | Expression::Sub(bin)
1006            | Expression::Mul(bin)
1007            | Expression::Div(bin)
1008            | Expression::Mod(bin)
1009            | Expression::Eq(bin)
1010            | Expression::Neq(bin)
1011            | Expression::Lt(bin)
1012            | Expression::Lte(bin)
1013            | Expression::Gt(bin)
1014            | Expression::Gte(bin)
1015            | Expression::BitwiseAnd(bin)
1016            | Expression::BitwiseOr(bin)
1017            | Expression::BitwiseXor(bin)
1018            | Expression::Concat(bin) => {
1019                children.push(&bin.left);
1020                children.push(&bin.right);
1021            }
1022            Expression::Like(like) | Expression::ILike(like) => {
1023                children.push(&like.left);
1024                children.push(&like.right);
1025                if let Some(escape) = &like.escape {
1026                    children.push(escape);
1027                }
1028            }
1029            Expression::Not(un) | Expression::Neg(un) | Expression::BitwiseNot(un) => {
1030                children.push(&un.this);
1031            }
1032            Expression::Function(func) => {
1033                for arg in &func.args {
1034                    children.push(arg);
1035                }
1036            }
1037            Expression::AggregateFunction(agg) => {
1038                for arg in &agg.args {
1039                    children.push(arg);
1040                }
1041            }
1042            Expression::WindowFunction(wf) => {
1043                children.push(&wf.this);
1044                for e in &wf.over.partition_by {
1045                    children.push(e);
1046                }
1047                for e in &wf.over.order_by {
1048                    children.push(&e.this);
1049                }
1050            }
1051            Expression::Alias(alias) => {
1052                children.push(&alias.this);
1053            }
1054            Expression::Case(case) => {
1055                if let Some(operand) = &case.operand {
1056                    children.push(operand);
1057                }
1058                for (when_expr, then_expr) in &case.whens {
1059                    children.push(when_expr);
1060                    children.push(then_expr);
1061                }
1062                if let Some(else_clause) = &case.else_ {
1063                    children.push(else_clause);
1064                }
1065            }
1066            Expression::Paren(paren) => {
1067                children.push(&paren.this);
1068            }
1069            Expression::Ordered(ord) => {
1070                children.push(&ord.this);
1071            }
1072            Expression::In(in_expr) => {
1073                children.push(&in_expr.this);
1074                for e in &in_expr.expressions {
1075                    children.push(e);
1076                }
1077                // Note: in_expr.query creates a new scope - don't traverse
1078            }
1079            Expression::Between(between) => {
1080                children.push(&between.this);
1081                children.push(&between.low);
1082                children.push(&between.high);
1083            }
1084            Expression::IsNull(is_null) => {
1085                children.push(&is_null.this);
1086            }
1087            Expression::Cast(cast) => {
1088                children.push(&cast.this);
1089            }
1090            Expression::Extract(extract) => {
1091                children.push(&extract.this);
1092            }
1093            Expression::Coalesce(coalesce) => {
1094                for e in &coalesce.expressions {
1095                    children.push(e);
1096                }
1097            }
1098            Expression::NullIf(nullif) => {
1099                children.push(&nullif.this);
1100                children.push(&nullif.expression);
1101            }
1102            Expression::Table(_table) => {
1103                // Tables don't have child expressions to traverse within scope
1104                // (joins are handled at the Select level)
1105            }
1106            Expression::TryCatch(try_catch) => {
1107                for stmt in &try_catch.try_body {
1108                    children.push(stmt);
1109                }
1110                if let Some(catch_body) = &try_catch.catch_body {
1111                    for stmt in catch_body {
1112                        children.push(stmt);
1113                    }
1114                }
1115            }
1116            Expression::Column(_) | Expression::Literal(_) | Expression::Identifier(_) => {
1117                // Leaf nodes - no children
1118            }
1119            // Subqueries and Exists create new scopes - don't traverse into them
1120            Expression::Subquery(_) | Expression::Exists(_) => {}
1121            _ => {
1122                // For other expressions, we could add more cases as needed
1123            }
1124        }
1125
1126        children
1127    }
1128}
1129
1130impl<'a> Iterator for WalkInScopeIter<'a> {
1131    type Item = &'a Expression;
1132
1133    fn next(&mut self) -> Option<Self::Item> {
1134        let expr = if self.bfs {
1135            self.queue.pop_front()?
1136        } else {
1137            self.queue.pop_back()?
1138        };
1139
1140        // Get children that don't cross scope boundaries
1141        let children = self.get_children(expr);
1142
1143        if self.bfs {
1144            for child in children {
1145                if !self.should_stop_at(child, false) {
1146                    self.queue.push_back(child);
1147                }
1148            }
1149        } else {
1150            for child in children.into_iter().rev() {
1151                if !self.should_stop_at(child, false) {
1152                    self.queue.push_back(child);
1153                }
1154            }
1155        }
1156
1157        Some(expr)
1158    }
1159}
1160
1161/// Find the first expression matching the predicate within this scope.
1162///
1163/// This does NOT traverse into subscopes.
1164///
1165/// # Arguments
1166/// * `expression` - The root expression
1167/// * `predicate` - Function that returns true for matching expressions
1168/// * `bfs` - If true, uses breadth-first search; otherwise depth-first
1169///
1170/// # Returns
1171/// The first matching expression, or None
1172pub fn find_in_scope<'a, F>(
1173    expression: &'a Expression,
1174    predicate: F,
1175    bfs: bool,
1176) -> Option<&'a Expression>
1177where
1178    F: Fn(&Expression) -> bool,
1179{
1180    walk_in_scope(expression, bfs).find(|e| predicate(e))
1181}
1182
1183/// Find all expressions matching the predicate within this scope.
1184///
1185/// This does NOT traverse into subscopes.
1186///
1187/// # Arguments
1188/// * `expression` - The root expression
1189/// * `predicate` - Function that returns true for matching expressions
1190/// * `bfs` - If true, uses breadth-first search; otherwise depth-first
1191///
1192/// # Returns
1193/// A vector of matching expressions
1194pub fn find_all_in_scope<'a, F>(
1195    expression: &'a Expression,
1196    predicate: F,
1197    bfs: bool,
1198) -> Vec<&'a Expression>
1199where
1200    F: Fn(&Expression) -> bool,
1201{
1202    walk_in_scope(expression, bfs)
1203        .filter(|e| predicate(e))
1204        .collect()
1205}
1206
1207/// Traverse an expression by its "scopes".
1208///
1209/// Returns a list of all scopes in depth-first post-order.
1210///
1211/// # Arguments
1212/// * `expression` - The expression to traverse
1213///
1214/// # Returns
1215/// A vector of all scopes found
1216pub fn traverse_scope(expression: &Expression) -> Vec<Scope> {
1217    match expression {
1218        Expression::Select(_)
1219        | Expression::Union(_)
1220        | Expression::Intersect(_)
1221        | Expression::Except(_)
1222        | Expression::Prepare(_)
1223        | Expression::CreateTable(_) => {
1224            let root = build_scope(expression);
1225            root.traverse().into_iter().cloned().collect()
1226        }
1227        _ => Vec::new(),
1228    }
1229}
1230
1231#[cfg(test)]
1232mod tests {
1233    use super::*;
1234    use crate::parser::Parser;
1235
1236    fn parse_and_build_scope(sql: &str) -> Scope {
1237        let ast = Parser::parse_sql(sql).expect("Failed to parse SQL");
1238        build_scope(&ast[0])
1239    }
1240
1241    #[test]
1242    fn test_simple_select_scope() {
1243        let mut scope = parse_and_build_scope("SELECT a, b FROM t");
1244
1245        assert!(scope.is_root());
1246        assert!(!scope.can_be_correlated);
1247        assert!(scope.sources.contains_key("t"));
1248
1249        let columns = scope.columns();
1250        assert_eq!(columns.len(), 2);
1251    }
1252
1253    #[test]
1254    fn test_derived_table_scope() {
1255        let mut scope = parse_and_build_scope("SELECT x.a FROM (SELECT a FROM t) AS x");
1256
1257        assert!(scope.sources.contains_key("x"));
1258        assert_eq!(scope.derived_table_scopes.len(), 1);
1259
1260        let derived = &mut scope.derived_table_scopes[0];
1261        assert!(derived.is_derived_table());
1262        assert!(derived.sources.contains_key("t"));
1263    }
1264
1265    #[test]
1266    fn test_non_correlated_subquery() {
1267        let mut scope = parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s)");
1268
1269        assert_eq!(scope.subquery_scopes.len(), 1);
1270
1271        let subquery = &mut scope.subquery_scopes[0];
1272        assert!(subquery.is_subquery());
1273        assert!(subquery.can_be_correlated);
1274
1275        // The subquery references only 's', which is in its own sources
1276        assert!(subquery.sources.contains_key("s"));
1277        assert!(!subquery.is_correlated_subquery());
1278    }
1279
1280    #[test]
1281    fn test_correlated_subquery() {
1282        let mut scope =
1283            parse_and_build_scope("SELECT * FROM t WHERE EXISTS (SELECT b FROM s WHERE s.x = t.y)");
1284
1285        assert_eq!(scope.subquery_scopes.len(), 1);
1286
1287        let subquery = &mut scope.subquery_scopes[0];
1288        assert!(subquery.is_subquery());
1289        assert!(subquery.can_be_correlated);
1290
1291        // The subquery references 't.y' which is external
1292        let external = subquery.external_columns();
1293        assert!(!external.is_empty());
1294        assert!(external.iter().any(|c| c.table.as_deref() == Some("t")));
1295        assert!(subquery.is_correlated_subquery());
1296    }
1297
1298    #[test]
1299    fn test_cte_scope() {
1300        let scope = parse_and_build_scope("WITH cte AS (SELECT a FROM t) SELECT * FROM cte");
1301
1302        assert_eq!(scope.cte_scopes.len(), 1);
1303        assert!(scope.cte_sources.contains_key("cte"));
1304
1305        let cte = &scope.cte_scopes[0];
1306        assert!(cte.is_cte());
1307    }
1308
1309    #[test]
1310    fn test_multiple_sources() {
1311        let scope = parse_and_build_scope("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
1312
1313        assert!(scope.sources.contains_key("t"));
1314        assert!(scope.sources.contains_key("s"));
1315        assert_eq!(scope.sources.len(), 2);
1316    }
1317
1318    #[test]
1319    fn test_aliased_table() {
1320        let scope = parse_and_build_scope("SELECT x.a FROM t AS x");
1321
1322        // Should be indexed by alias, not original name
1323        assert!(scope.sources.contains_key("x"));
1324        assert!(!scope.sources.contains_key("t"));
1325    }
1326
1327    #[test]
1328    fn test_local_columns() {
1329        let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1330
1331        let local = scope.local_columns();
1332        // All columns are local since both t and s are in scope.
1333        // Includes JOIN ON references (t.id, s.id).
1334        assert_eq!(local.len(), 5);
1335        assert!(local.iter().all(|c| c.table.is_some()));
1336    }
1337
1338    #[test]
1339    fn test_columns_include_join_on_clause_references() {
1340        let mut scope = parse_and_build_scope(
1341            "SELECT o.total FROM orders o JOIN customers c ON c.id = o.customer_id",
1342        );
1343
1344        let cols: Vec<String> = scope
1345            .columns()
1346            .iter()
1347            .map(|c| match &c.table {
1348                Some(t) => format!("{}.{}", t, c.name),
1349                None => c.name.clone(),
1350            })
1351            .collect();
1352
1353        assert!(cols.contains(&"o.total".to_string()));
1354        assert!(cols.contains(&"c.id".to_string()));
1355        assert!(cols.contains(&"o.customer_id".to_string()));
1356    }
1357
1358    #[test]
1359    fn test_unqualified_columns() {
1360        let mut scope = parse_and_build_scope("SELECT a, b, t.c FROM t");
1361
1362        let unqualified = scope.unqualified_columns();
1363        // Only a and b are unqualified
1364        assert_eq!(unqualified.len(), 2);
1365        assert!(unqualified.iter().all(|c| c.table.is_none()));
1366    }
1367
1368    #[test]
1369    fn test_source_columns() {
1370        let mut scope = parse_and_build_scope("SELECT t.a, t.b, s.c FROM t JOIN s ON t.id = s.id");
1371
1372        let t_cols = scope.source_columns("t");
1373        // t.a, t.b, and t.id from JOIN condition
1374        assert!(t_cols.len() >= 2);
1375        assert!(t_cols.iter().all(|c| c.table.as_deref() == Some("t")));
1376
1377        let s_cols = scope.source_columns("s");
1378        // s.c and s.id from JOIN condition
1379        assert!(s_cols.len() >= 1);
1380        assert!(s_cols.iter().all(|c| c.table.as_deref() == Some("s")));
1381    }
1382
1383    #[test]
1384    fn test_rename_source() {
1385        let mut scope = parse_and_build_scope("SELECT a FROM t");
1386
1387        assert!(scope.sources.contains_key("t"));
1388        scope.rename_source("t", "new_name".to_string());
1389        assert!(!scope.sources.contains_key("t"));
1390        assert!(scope.sources.contains_key("new_name"));
1391    }
1392
1393    #[test]
1394    fn test_remove_source() {
1395        let mut scope = parse_and_build_scope("SELECT a FROM t");
1396
1397        assert!(scope.sources.contains_key("t"));
1398        scope.remove_source("t");
1399        assert!(!scope.sources.contains_key("t"));
1400    }
1401
1402    #[test]
1403    fn test_walk_in_scope() {
1404        let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1405        let expr = &ast[0];
1406
1407        // Walk should visit all expressions within the scope
1408        let walked: Vec<_> = walk_in_scope(expr, true).collect();
1409        assert!(!walked.is_empty());
1410
1411        // Should include the root SELECT
1412        assert!(walked.iter().any(|e| matches!(e, Expression::Select(_))));
1413        // Should include columns
1414        assert!(walked.iter().any(|e| matches!(e, Expression::Column(_))));
1415    }
1416
1417    #[test]
1418    fn test_find_in_scope() {
1419        let ast = Parser::parse_sql("SELECT a, b FROM t WHERE a > 1").expect("Failed to parse");
1420        let expr = &ast[0];
1421
1422        // Find the first column
1423        let found = find_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1424        assert!(found.is_some());
1425        assert!(matches!(found.unwrap(), Expression::Column(_)));
1426    }
1427
1428    #[test]
1429    fn test_find_all_in_scope() {
1430        let ast = Parser::parse_sql("SELECT a, b, c FROM t").expect("Failed to parse");
1431        let expr = &ast[0];
1432
1433        // Find all columns
1434        let found = find_all_in_scope(expr, |e| matches!(e, Expression::Column(_)), true);
1435        assert_eq!(found.len(), 3);
1436    }
1437
1438    #[test]
1439    fn test_traverse_scope() {
1440        let ast =
1441            Parser::parse_sql("SELECT a FROM (SELECT b FROM t) AS x").expect("Failed to parse");
1442        let expr = &ast[0];
1443
1444        let scopes = traverse_scope(expr);
1445        // traverse_scope returns all scopes via Scope::traverse
1446        // which includes derived table and root scopes
1447        assert!(!scopes.is_empty());
1448        // The root scope is always included
1449        assert!(scopes.iter().any(|s| s.is_root()));
1450    }
1451
1452    #[test]
1453    fn test_branch_with_options() {
1454        let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1455        let scope = build_scope(&ast[0]);
1456
1457        let child = scope.branch_with_options(
1458            ast[0].clone(),
1459            ScopeType::Subquery, // Use Subquery to test can_be_correlated
1460            None,
1461            None,
1462            Some(vec!["col1".to_string(), "col2".to_string()]),
1463        );
1464
1465        assert_eq!(child.outer_columns, vec!["col1", "col2"]);
1466        assert!(child.can_be_correlated); // Subqueries are correlated
1467    }
1468
1469    #[test]
1470    fn test_is_udtf() {
1471        let ast = Parser::parse_sql("SELECT a FROM t").expect("Failed to parse");
1472        let scope = Scope::new(ast[0].clone());
1473        assert!(!scope.is_udtf());
1474
1475        let root = build_scope(&ast[0]);
1476        let udtf_scope = root.branch(ast[0].clone(), ScopeType::Udtf);
1477        assert!(udtf_scope.is_udtf());
1478    }
1479
1480    #[test]
1481    fn test_is_union() {
1482        let scope = parse_and_build_scope("SELECT a FROM t UNION SELECT b FROM s");
1483
1484        assert!(scope.is_root());
1485        assert_eq!(scope.union_scopes.len(), 2);
1486        // The children are set operation scopes
1487        assert!(scope.union_scopes[0].is_union());
1488        assert!(scope.union_scopes[1].is_union());
1489    }
1490
1491    #[test]
1492    fn test_union_output_columns() {
1493        let scope = parse_and_build_scope(
1494            "SELECT id, name FROM customers UNION ALL SELECT id, name FROM employees",
1495        );
1496        assert_eq!(scope.output_columns(), vec!["id", "name"]);
1497    }
1498
1499    #[test]
1500    fn test_clear_cache() {
1501        let mut scope = parse_and_build_scope("SELECT t.a FROM t");
1502
1503        // First call populates cache
1504        let _ = scope.columns();
1505        assert!(scope.columns_cache.is_some());
1506
1507        // Clear cache
1508        scope.clear_cache();
1509        assert!(scope.columns_cache.is_none());
1510        assert!(scope.external_columns_cache.is_none());
1511    }
1512
1513    #[test]
1514    fn test_scope_traverse() {
1515        let scope = parse_and_build_scope(
1516            "WITH cte AS (SELECT a FROM t) SELECT * FROM cte WHERE EXISTS (SELECT b FROM s)",
1517        );
1518
1519        let traversed = scope.traverse();
1520        // Should include: CTE scope, subquery scope, root scope
1521        assert!(traversed.len() >= 3);
1522    }
1523
1524    #[test]
1525    fn test_create_table_as_select_scope() {
1526        // Simple CTAS
1527        let scope = parse_and_build_scope("CREATE TABLE out_table AS SELECT 1 AS id FROM src");
1528        assert!(
1529            scope.sources.contains_key("src"),
1530            "CTAS scope should contain the FROM table"
1531        );
1532        assert!(
1533            !scope.sources.contains_key("out_table"),
1534            "CTAS target table should not be treated as a source"
1535        );
1536
1537        // CTAS with multiple FROM tables
1538        let scope = parse_and_build_scope(
1539            "CREATE TABLE out_table AS SELECT a.id FROM foo AS a JOIN bar AS b ON a.id = b.id",
1540        );
1541        assert!(scope.sources.contains_key("a"));
1542        assert!(scope.sources.contains_key("b"));
1543        assert!(
1544            !scope.sources.contains_key("out_table"),
1545            "CTAS target table should not be treated as a source"
1546        );
1547
1548        // CTAS with CTEs
1549        let scope = parse_and_build_scope(
1550            "CREATE TABLE out_table AS WITH cte AS (SELECT 1 AS id FROM src) SELECT * FROM cte",
1551        );
1552        assert!(
1553            scope.sources.contains_key("cte"),
1554            "CTAS with CTE should resolve CTE as source"
1555        );
1556        assert!(
1557            !scope.sources.contains_key("out_table"),
1558            "CTAS target table should not be treated as a source"
1559        );
1560        assert_eq!(scope.cte_scopes.len(), 1);
1561    }
1562
1563    #[test]
1564    fn test_create_table_as_select_traverse() {
1565        let ast = Parser::parse_sql("CREATE TABLE t AS SELECT a FROM src").unwrap();
1566        let scopes = traverse_scope(&ast[0]);
1567        assert!(
1568            !scopes.is_empty(),
1569            "traverse_scope should return scopes for CTAS"
1570        );
1571    }
1572}