Skip to main content

polyglot_sql/
lineage.rs

1//! Column Lineage Tracking
2//!
3//! This module provides functionality to track column lineage through SQL queries,
4//! building a graph of how columns flow from source tables to the result set.
5//! Supports UNION/INTERSECT/EXCEPT, CTEs, derived tables, subqueries, and star expansion.
6//!
7
8use crate::dialects::DialectType;
9use crate::expressions::{Expression, Identifier, Select};
10use crate::optimizer::annotate_types::annotate_types;
11use crate::optimizer::qualify_columns::{qualify_columns, QualifyColumnsOptions};
12use crate::schema::{normalize_name, Schema};
13use crate::scope::{build_scope, Scope};
14use crate::traversal::ExpressionWalk;
15use crate::{Error, Result};
16use serde::{Deserialize, Serialize};
17use std::collections::{HashMap, HashSet};
18
19/// A node in the column lineage graph
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct LineageNode {
22    /// Name of this lineage step (e.g., "table.column")
23    pub name: String,
24    /// The expression at this node
25    pub expression: Expression,
26    /// The source expression (the full query context)
27    pub source: Expression,
28    /// Downstream nodes that depend on this one
29    pub downstream: Vec<LineageNode>,
30    /// Optional source name (e.g., for derived tables)
31    pub source_name: String,
32    /// Optional reference node name (e.g., for CTEs)
33    pub reference_node_name: String,
34}
35
36impl LineageNode {
37    /// Create a new lineage node
38    pub fn new(name: impl Into<String>, expression: Expression, source: Expression) -> Self {
39        Self {
40            name: name.into(),
41            expression,
42            source,
43            downstream: Vec::new(),
44            source_name: String::new(),
45            reference_node_name: String::new(),
46        }
47    }
48
49    /// Iterate over all nodes in the lineage graph using DFS
50    pub fn walk(&self) -> LineageWalker<'_> {
51        LineageWalker { stack: vec![self] }
52    }
53
54    /// Get all downstream column names
55    pub fn downstream_names(&self) -> Vec<String> {
56        self.downstream.iter().map(|n| n.name.clone()).collect()
57    }
58}
59
60/// Iterator for walking the lineage graph
61pub struct LineageWalker<'a> {
62    stack: Vec<&'a LineageNode>,
63}
64
65impl<'a> Iterator for LineageWalker<'a> {
66    type Item = &'a LineageNode;
67
68    fn next(&mut self) -> Option<Self::Item> {
69        if let Some(node) = self.stack.pop() {
70            // Add children in reverse order so they're visited in order
71            for child in node.downstream.iter().rev() {
72                self.stack.push(child);
73            }
74            Some(node)
75        } else {
76            None
77        }
78    }
79}
80
81// ---------------------------------------------------------------------------
82// ColumnRef: name or positional index for column lookup
83// ---------------------------------------------------------------------------
84
85/// Column reference for lineage tracing — by name or positional index.
86enum ColumnRef<'a> {
87    Name(&'a str),
88    Index(usize),
89}
90
91// ---------------------------------------------------------------------------
92// Public API
93// ---------------------------------------------------------------------------
94
95/// Build the lineage graph for a column in a SQL query
96///
97/// # Arguments
98/// * `column` - The column name to trace lineage for
99/// * `sql` - The SQL expression (SELECT, UNION, etc.)
100/// * `dialect` - Optional dialect for parsing
101/// * `trim_selects` - If true, trim the source SELECT to only include the target column
102///
103/// # Returns
104/// The root lineage node for the specified column
105///
106/// # Example
107/// ```ignore
108/// use polyglot_sql::lineage::lineage;
109/// use polyglot_sql::parse_one;
110/// use polyglot_sql::DialectType;
111///
112/// let sql = "SELECT a, b + 1 AS c FROM t";
113/// let expr = parse_one(sql, DialectType::Generic).unwrap();
114/// let node = lineage("c", &expr, None, false).unwrap();
115/// ```
116pub fn lineage(
117    column: &str,
118    sql: &Expression,
119    dialect: Option<DialectType>,
120    trim_selects: bool,
121) -> Result<LineageNode> {
122    // Fast path: skip clone when there are no CTEs to expand
123    let has_with = matches!(sql, Expression::Select(s) if s.with.is_some());
124    if !has_with {
125        return lineage_from_expression(column, sql, dialect, trim_selects);
126    }
127    let mut owned = sql.clone();
128    expand_cte_stars(&mut owned, None);
129    lineage_from_expression(column, &owned, dialect, trim_selects)
130}
131
132/// Build the lineage graph for a column in a SQL query using optional schema metadata.
133///
134/// When `schema` is provided, the query is first qualified with
135/// `optimizer::qualify_columns`, allowing more accurate lineage for unqualified or
136/// ambiguous column references.
137///
138/// # Arguments
139/// * `column` - The column name to trace lineage for
140/// * `sql` - The SQL expression (SELECT, UNION, etc.)
141/// * `schema` - Optional schema used for qualification
142/// * `dialect` - Optional dialect for qualification and lineage handling
143/// * `trim_selects` - If true, trim the source SELECT to only include the target column
144///
145/// # Returns
146/// The root lineage node for the specified column
147pub fn lineage_with_schema(
148    column: &str,
149    sql: &Expression,
150    schema: Option<&dyn Schema>,
151    dialect: Option<DialectType>,
152    trim_selects: bool,
153) -> Result<LineageNode> {
154    let mut qualified_expression = if let Some(schema) = schema {
155        let options = if let Some(dialect_type) = dialect.or_else(|| schema.dialect()) {
156            QualifyColumnsOptions::new().with_dialect(dialect_type)
157        } else {
158            QualifyColumnsOptions::new()
159        };
160
161        qualify_columns(sql.clone(), schema, &options).map_err(|e| {
162            Error::internal(format!("Lineage qualification failed with schema: {}", e))
163        })?
164    } else {
165        sql.clone()
166    };
167
168    // Annotate types in-place so lineage nodes carry type information
169    annotate_types(&mut qualified_expression, schema, dialect);
170
171    // Expand CTE stars on the already-owned expression (no extra clone).
172    // Pass schema so that stars from external tables can also be resolved.
173    expand_cte_stars(&mut qualified_expression, schema);
174
175    lineage_from_expression(column, &qualified_expression, dialect, trim_selects)
176}
177
178fn lineage_from_expression(
179    column: &str,
180    sql: &Expression,
181    dialect: Option<DialectType>,
182    trim_selects: bool,
183) -> Result<LineageNode> {
184    let scope = build_scope(sql);
185    to_node(
186        ColumnRef::Name(column),
187        &scope,
188        dialect,
189        "",
190        "",
191        "",
192        trim_selects,
193    )
194}
195
196// ---------------------------------------------------------------------------
197// CTE star expansion
198// ---------------------------------------------------------------------------
199
200/// Normalize an identifier for CTE name matching.
201///
202/// Follows SQL semantics: unquoted identifiers are case-insensitive (lowercased),
203/// quoted identifiers preserve their original case. This matches sqlglot's
204/// `normalize_identifiers` behavior.
205fn normalize_cte_name(ident: &Identifier) -> String {
206    if ident.quoted {
207        ident.name.clone()
208    } else {
209        ident.name.to_lowercase()
210    }
211}
212
213/// Expand SELECT * in CTEs by walking CTE definitions in order and propagating
214/// resolved column lists. This handles nested CTEs (e.g., cte2 AS (SELECT * FROM cte1))
215/// which qualify_columns cannot resolve because it processes each SELECT independently.
216///
217/// When `schema` is provided, stars from external tables (not CTEs) are also resolved
218/// by looking up column names in the schema. This enables correct expansion of patterns
219/// like `WITH cte AS (SELECT * FROM external_table) SELECT * FROM cte`.
220///
221/// CTE name matching follows SQL identifier semantics: unquoted names are compared
222/// case-insensitively (lowercased), while quoted names preserve their original case.
223/// This matches sqlglot's `normalize_identifiers` behavior.
224pub fn expand_cte_stars(expr: &mut Expression, schema: Option<&dyn Schema>) {
225    let select = match expr {
226        Expression::Select(s) => s,
227        _ => return,
228    };
229
230    let with = match &mut select.with {
231        Some(w) => w,
232        None => return,
233    };
234
235    let mut resolved_cte_columns: HashMap<String, Vec<String>> = HashMap::new();
236
237    for cte in &mut with.ctes {
238        let cte_name = normalize_cte_name(&cte.alias);
239
240        // If CTE has explicit column list (e.g., cte(a, b) AS (...)), use that
241        if !cte.columns.is_empty() {
242            let cols: Vec<String> = cte.columns.iter().map(|c| c.name.clone()).collect();
243            resolved_cte_columns.insert(cte_name, cols);
244            continue;
245        }
246
247        // Skip recursive CTEs (self-referencing) — their column resolution is complex.
248        // A CTE is recursive if the WITH block is marked recursive AND the CTE body
249        // references itself. We detect this conservatively: if the CTE name appears as
250        // a source in its own body, skip it. Non-recursive CTEs in a recursive WITH
251        // block are still expanded.
252        if with.recursive {
253            let is_self_referencing =
254                if let Some(body_select) = get_leftmost_select_mut(&mut cte.this) {
255                    let body_sources = get_select_sources(body_select);
256                    body_sources.iter().any(|s| s.normalized == cte_name)
257                } else {
258                    false
259                };
260            if is_self_referencing {
261                continue;
262            }
263        }
264
265        // Get the SELECT from the CTE body (handle UNION by taking left branch)
266        let body_select = match get_leftmost_select_mut(&mut cte.this) {
267            Some(s) => s,
268            None => continue,
269        };
270
271        let columns = rewrite_stars_in_select(body_select, &resolved_cte_columns, schema);
272        resolved_cte_columns.insert(cte_name, columns);
273    }
274
275    // Also expand stars in the outer SELECT itself
276    rewrite_stars_in_select(select, &resolved_cte_columns, schema);
277}
278
279/// Get the leftmost SELECT from an expression, drilling through UNION/INTERSECT/EXCEPT.
280///
281/// Per the SQL standard, the column names of a set operation (UNION, INTERSECT, EXCEPT)
282/// are determined by the left branch. This matches sqlglot's behavior.
283fn get_leftmost_select_mut(expr: &mut Expression) -> Option<&mut Select> {
284    let mut current = expr;
285    for _ in 0..MAX_LINEAGE_DEPTH {
286        match current {
287            Expression::Select(s) => return Some(s),
288            Expression::Union(u) => current = &mut u.left,
289            Expression::Intersect(i) => current = &mut i.left,
290            Expression::Except(e) => current = &mut e.left,
291            Expression::Paren(p) => current = &mut p.this,
292            _ => return None,
293        }
294    }
295    None
296}
297
298/// Rewrite star expressions in a SELECT using resolved CTE column lists.
299/// Falls back to `schema` for external table column lookup.
300/// Returns the list of output column names after expansion.
301fn rewrite_stars_in_select(
302    select: &mut Select,
303    resolved_ctes: &HashMap<String, Vec<String>>,
304    schema: Option<&dyn Schema>,
305) -> Vec<String> {
306    // The AST represents star expressions in two forms depending on syntax:
307    //   - `SELECT *`      → Expression::Star (unqualified star)
308    //   - `SELECT table.*` → Expression::Column { name: "*", table: Some(...) } (qualified star)
309    // Both must be checked to handle all star patterns.
310    let has_star = select
311        .expressions
312        .iter()
313        .any(|e| matches!(e, Expression::Star(_)));
314    let has_qualified_star = select
315        .expressions
316        .iter()
317        .any(|e| matches!(e, Expression::Column(c) if c.name.name == "*"));
318
319    if !has_star && !has_qualified_star {
320        // No stars — just extract column names without rewriting
321        return select
322            .expressions
323            .iter()
324            .filter_map(get_expression_output_name)
325            .collect();
326    }
327
328    let sources = get_select_sources(select);
329    let mut new_expressions = Vec::new();
330    let mut result_columns = Vec::new();
331
332    for expr in &select.expressions {
333        match expr {
334            Expression::Star(star) => {
335                let qual = star.table.as_ref();
336                if let Some(expanded) =
337                    expand_star_from_sources(qual, &sources, resolved_ctes, schema)
338                {
339                    for (src_alias, col_name) in &expanded {
340                        let table_id = Identifier::new(src_alias);
341                        new_expressions.push(make_column_expr(col_name, Some(&table_id)));
342                        result_columns.push(col_name.clone());
343                    }
344                } else {
345                    new_expressions.push(expr.clone());
346                    result_columns.push("*".to_string());
347                }
348            }
349            Expression::Column(c) if c.name.name == "*" => {
350                let qual = c.table.as_ref();
351                if let Some(expanded) =
352                    expand_star_from_sources(qual, &sources, resolved_ctes, schema)
353                {
354                    for (_src_alias, col_name) in &expanded {
355                        // Keep the original table qualifier for qualified stars (table.*)
356                        new_expressions.push(make_column_expr(col_name, c.table.as_ref()));
357                        result_columns.push(col_name.clone());
358                    }
359                } else {
360                    new_expressions.push(expr.clone());
361                    result_columns.push("*".to_string());
362                }
363            }
364            _ => {
365                new_expressions.push(expr.clone());
366                if let Some(name) = get_expression_output_name(expr) {
367                    result_columns.push(name);
368                }
369            }
370        }
371    }
372
373    select.expressions = new_expressions;
374    result_columns
375}
376
377/// Try to expand a star expression by looking up source columns from resolved CTEs,
378/// falling back to the schema for external tables.
379/// Returns (source_alias, column_name) pairs so the caller can set table qualifiers.
380/// `qualifier`: Optional table qualifier (for `table.*`). If None, expand all sources.
381fn expand_star_from_sources(
382    qualifier: Option<&Identifier>,
383    sources: &[SourceInfo],
384    resolved_ctes: &HashMap<String, Vec<String>>,
385    schema: Option<&dyn Schema>,
386) -> Option<Vec<(String, String)>> {
387    let mut expanded = Vec::new();
388
389    if let Some(qual) = qualifier {
390        // Qualified star: table.*
391        let qual_normalized = normalize_cte_name(qual);
392        for src in sources {
393            if src.normalized == qual_normalized || src.alias.to_lowercase() == qual_normalized {
394                // Try CTE first
395                if let Some(cols) = resolved_ctes.get(&src.normalized) {
396                    expanded.extend(cols.iter().map(|c| (src.alias.clone(), c.clone())));
397                    return Some(expanded);
398                }
399                // Fall back to schema
400                if let Some(cols) = lookup_schema_columns(schema, &src.fq_name) {
401                    expanded.extend(cols.into_iter().map(|c| (src.alias.clone(), c)));
402                    return Some(expanded);
403                }
404            }
405        }
406        None
407    } else {
408        // Unqualified star: expand all sources.
409        // Intentionally conservative: if any source can't be resolved, the entire
410        // expansion is aborted. Partial expansion would produce an incomplete column
411        // list, causing downstream lineage resolution to silently omit columns.
412        // This matches sqlglot's behavior (raises SqlglotError when schema is missing).
413        let mut any_expanded = false;
414        for src in sources {
415            if let Some(cols) = resolved_ctes.get(&src.normalized) {
416                expanded.extend(cols.iter().map(|c| (src.alias.clone(), c.clone())));
417                any_expanded = true;
418            } else if let Some(cols) = lookup_schema_columns(schema, &src.fq_name) {
419                expanded.extend(cols.into_iter().map(|c| (src.alias.clone(), c)));
420                any_expanded = true;
421            } else {
422                return None;
423            }
424        }
425        if any_expanded {
426            Some(expanded)
427        } else {
428            None
429        }
430    }
431}
432
433/// Look up column names for a table from the schema.
434fn lookup_schema_columns(schema: Option<&dyn Schema>, fq_name: &str) -> Option<Vec<String>> {
435    let schema = schema?;
436    if fq_name.is_empty() {
437        return None;
438    }
439    schema
440        .column_names(fq_name)
441        .ok()
442        .filter(|cols| !cols.is_empty() && !cols.contains(&"*".to_string()))
443}
444
445/// Create a Column expression with the given name and optional table qualifier.
446fn make_column_expr(name: &str, table: Option<&Identifier>) -> Expression {
447    Expression::Column(Box::new(crate::expressions::Column {
448        name: Identifier::new(name),
449        table: table.cloned(),
450        join_mark: false,
451        trailing_comments: Vec::new(),
452        span: None,
453        inferred_type: None,
454    }))
455}
456
457/// Extract the output name of a SELECT expression.
458fn get_expression_output_name(expr: &Expression) -> Option<String> {
459    match expr {
460        Expression::Alias(a) => Some(a.alias.name.clone()),
461        Expression::Column(c) => Some(c.name.name.clone()),
462        Expression::Identifier(id) => Some(id.name.clone()),
463        Expression::Star(_) => Some("*".to_string()),
464        _ => None,
465    }
466}
467
468/// Source info extracted from a SELECT's FROM/JOIN clauses in a single pass.
469struct SourceInfo {
470    alias: String,
471    /// Normalized name for CTE lookup: unquoted → lowercased, quoted → as-is.
472    normalized: String,
473    /// Fully-qualified table name for schema lookup (e.g., "db.schema.table").
474    fq_name: String,
475}
476
477/// Extract source info (alias, normalized CTE name, fully-qualified name) from a
478/// SELECT's FROM and JOIN clauses in a single pass.
479fn get_select_sources(select: &Select) -> Vec<SourceInfo> {
480    let mut sources = Vec::new();
481
482    fn extract_source(expr: &Expression) -> Option<SourceInfo> {
483        match expr {
484            Expression::Table(t) => {
485                let normalized = normalize_cte_name(&t.name);
486                let alias = t
487                    .alias
488                    .as_ref()
489                    .map(|a| a.name.clone())
490                    .unwrap_or_else(|| t.name.name.clone());
491                let mut parts = Vec::new();
492                if let Some(catalog) = &t.catalog {
493                    parts.push(catalog.name.clone());
494                }
495                if let Some(schema) = &t.schema {
496                    parts.push(schema.name.clone());
497                }
498                parts.push(t.name.name.clone());
499                let fq_name = parts.join(".");
500                Some(SourceInfo {
501                    alias,
502                    normalized,
503                    fq_name,
504                })
505            }
506            Expression::Subquery(s) => {
507                let alias = s.alias.as_ref()?.name.clone();
508                let normalized = alias.to_lowercase();
509                let fq_name = alias.clone();
510                Some(SourceInfo {
511                    alias,
512                    normalized,
513                    fq_name,
514                })
515            }
516            Expression::Paren(p) => extract_source(&p.this),
517            _ => None,
518        }
519    }
520
521    if let Some(from) = &select.from {
522        for expr in &from.expressions {
523            if let Some(info) = extract_source(expr) {
524                sources.push(info);
525            }
526        }
527    }
528    for join in &select.joins {
529        if let Some(info) = extract_source(&join.this) {
530            sources.push(info);
531        }
532    }
533    sources
534}
535
536/// Get all source tables from a lineage graph
537pub fn get_source_tables(node: &LineageNode) -> HashSet<String> {
538    let mut tables = HashSet::new();
539    collect_source_tables(node, &mut tables);
540    tables
541}
542
543/// Recursively collect source table names from lineage graph
544pub fn collect_source_tables(node: &LineageNode, tables: &mut HashSet<String>) {
545    if let Expression::Table(table) = &node.source {
546        tables.insert(table.name.name.clone());
547    }
548    for child in &node.downstream {
549        collect_source_tables(child, tables);
550    }
551}
552
553// ---------------------------------------------------------------------------
554// Core recursive lineage builder
555// ---------------------------------------------------------------------------
556
557/// Maximum recursion depth for lineage tracing to prevent stack overflow
558/// on circular or deeply nested CTE chains.
559const MAX_LINEAGE_DEPTH: usize = 64;
560
561/// Recursively build a lineage node for a column in a scope.
562fn to_node(
563    column: ColumnRef<'_>,
564    scope: &Scope,
565    dialect: Option<DialectType>,
566    scope_name: &str,
567    source_name: &str,
568    reference_node_name: &str,
569    trim_selects: bool,
570) -> Result<LineageNode> {
571    to_node_inner(
572        column,
573        scope,
574        dialect,
575        scope_name,
576        source_name,
577        reference_node_name,
578        trim_selects,
579        &[],
580        0,
581    )
582}
583
584fn to_node_inner(
585    column: ColumnRef<'_>,
586    scope: &Scope,
587    dialect: Option<DialectType>,
588    scope_name: &str,
589    source_name: &str,
590    reference_node_name: &str,
591    trim_selects: bool,
592    ancestor_cte_scopes: &[Scope],
593    depth: usize,
594) -> Result<LineageNode> {
595    if depth > MAX_LINEAGE_DEPTH {
596        return Err(Error::internal(format!(
597            "lineage recursion depth exceeded (>{MAX_LINEAGE_DEPTH}) — possible circular CTE reference for scope '{scope_name}'"
598        )));
599    }
600    let scope_expr = &scope.expression;
601
602    // Build combined CTE scopes: current scope's cte_scopes + ancestors
603    let mut all_cte_scopes: Vec<&Scope> = scope.cte_scopes.iter().collect();
604    for s in ancestor_cte_scopes {
605        all_cte_scopes.push(s);
606    }
607
608    // 0. Unwrap CTE scope — CTE scope expressions are Expression::Cte(...)
609    //    but we need the inner query (SELECT/UNION) for column lookup.
610    let effective_expr = match scope_expr {
611        Expression::Cte(cte) => &cte.this,
612        other => other,
613    };
614
615    // 1. Set operations (UNION / INTERSECT / EXCEPT)
616    if matches!(
617        effective_expr,
618        Expression::Union(_) | Expression::Intersect(_) | Expression::Except(_)
619    ) {
620        // For CTE wrapping a set op, create a temporary scope with the inner expression
621        if matches!(scope_expr, Expression::Cte(_)) {
622            let mut inner_scope = Scope::new(effective_expr.clone());
623            inner_scope.union_scopes = scope.union_scopes.clone();
624            inner_scope.sources = scope.sources.clone();
625            inner_scope.cte_sources = scope.cte_sources.clone();
626            inner_scope.cte_scopes = scope.cte_scopes.clone();
627            inner_scope.derived_table_scopes = scope.derived_table_scopes.clone();
628            inner_scope.subquery_scopes = scope.subquery_scopes.clone();
629            return handle_set_operation(
630                &column,
631                &inner_scope,
632                dialect,
633                scope_name,
634                source_name,
635                reference_node_name,
636                trim_selects,
637                ancestor_cte_scopes,
638                depth,
639            );
640        }
641        return handle_set_operation(
642            &column,
643            scope,
644            dialect,
645            scope_name,
646            source_name,
647            reference_node_name,
648            trim_selects,
649            ancestor_cte_scopes,
650            depth,
651        );
652    }
653
654    // 2. Find the select expression for this column
655    let select_expr = find_select_expr(effective_expr, &column, dialect)?;
656    let column_name = resolve_column_name(&column, &select_expr);
657
658    // 3. Trim source if requested
659    let node_source = if trim_selects {
660        trim_source(effective_expr, &select_expr)
661    } else {
662        effective_expr.clone()
663    };
664
665    // 4. Create the lineage node
666    let mut node = LineageNode::new(&column_name, select_expr.clone(), node_source);
667    node.source_name = source_name.to_string();
668    node.reference_node_name = reference_node_name.to_string();
669
670    // 5. Star handling — add downstream for each source
671    if matches!(&select_expr, Expression::Star(_)) {
672        for (name, source_info) in &scope.sources {
673            let child = LineageNode::new(
674                format!("{}.*", name),
675                Expression::Star(crate::expressions::Star {
676                    table: None,
677                    except: None,
678                    replace: None,
679                    rename: None,
680                    trailing_comments: vec![],
681                    span: None,
682                }),
683                source_info.expression.clone(),
684            );
685            node.downstream.push(child);
686        }
687        return Ok(node);
688    }
689
690    // 6. Subqueries in select — trace through scalar subqueries
691    let subqueries: Vec<&Expression> =
692        select_expr.find_all(|e| matches!(e, Expression::Subquery(sq) if sq.alias.is_none()));
693    for sq_expr in subqueries {
694        if let Expression::Subquery(sq) = sq_expr {
695            for sq_scope in &scope.subquery_scopes {
696                if sq_scope.expression == sq.this {
697                    if let Ok(child) = to_node_inner(
698                        ColumnRef::Index(0),
699                        sq_scope,
700                        dialect,
701                        &column_name,
702                        "",
703                        "",
704                        trim_selects,
705                        ancestor_cte_scopes,
706                        depth + 1,
707                    ) {
708                        node.downstream.push(child);
709                    }
710                    break;
711                }
712            }
713        }
714    }
715
716    // 7. Column references — trace each column to its source
717    let col_refs = find_column_refs_in_expr(&select_expr);
718    for col_ref in col_refs {
719        let col_name = &col_ref.column;
720        if let Some(ref table_id) = col_ref.table {
721            let tbl = &table_id.name;
722            resolve_qualified_column(
723                &mut node,
724                scope,
725                dialect,
726                tbl,
727                col_name,
728                &column_name,
729                trim_selects,
730                &all_cte_scopes,
731                depth,
732            );
733        } else {
734            resolve_unqualified_column(
735                &mut node,
736                scope,
737                dialect,
738                col_name,
739                &column_name,
740                trim_selects,
741                &all_cte_scopes,
742                depth,
743            );
744        }
745    }
746
747    Ok(node)
748}
749
750// ---------------------------------------------------------------------------
751// Set operation handling
752// ---------------------------------------------------------------------------
753
754fn handle_set_operation(
755    column: &ColumnRef<'_>,
756    scope: &Scope,
757    dialect: Option<DialectType>,
758    scope_name: &str,
759    source_name: &str,
760    reference_node_name: &str,
761    trim_selects: bool,
762    ancestor_cte_scopes: &[Scope],
763    depth: usize,
764) -> Result<LineageNode> {
765    let scope_expr = &scope.expression;
766
767    // Determine column index
768    let col_index = match column {
769        ColumnRef::Name(name) => column_to_index(scope_expr, name, dialect)?,
770        ColumnRef::Index(i) => *i,
771    };
772
773    let col_name = match column {
774        ColumnRef::Name(name) => name.to_string(),
775        ColumnRef::Index(_) => format!("_{col_index}"),
776    };
777
778    let mut node = LineageNode::new(&col_name, scope_expr.clone(), scope_expr.clone());
779    node.source_name = source_name.to_string();
780    node.reference_node_name = reference_node_name.to_string();
781
782    // Recurse into each union branch
783    for branch_scope in &scope.union_scopes {
784        if let Ok(child) = to_node_inner(
785            ColumnRef::Index(col_index),
786            branch_scope,
787            dialect,
788            scope_name,
789            "",
790            "",
791            trim_selects,
792            ancestor_cte_scopes,
793            depth + 1,
794        ) {
795            node.downstream.push(child);
796        }
797    }
798
799    Ok(node)
800}
801
802// ---------------------------------------------------------------------------
803// Column resolution helpers
804// ---------------------------------------------------------------------------
805
806fn resolve_qualified_column(
807    node: &mut LineageNode,
808    scope: &Scope,
809    dialect: Option<DialectType>,
810    table: &str,
811    col_name: &str,
812    parent_name: &str,
813    trim_selects: bool,
814    all_cte_scopes: &[&Scope],
815    depth: usize,
816) {
817    // Resolve CTE alias: if `table` is a FROM alias for a CTE (e.g., `FROM my_cte AS t`),
818    // resolve it to the actual CTE name so the CTE scope lookup succeeds.
819    let resolved_cte_name = resolve_cte_alias(scope, table);
820    let effective_table = resolved_cte_name.as_deref().unwrap_or(table);
821
822    // Check if table is a CTE reference — check both the current scope's cte_sources
823    // and ancestor CTE scopes (for sibling CTEs in parent WITH clauses).
824    let is_cte = scope.cte_sources.contains_key(effective_table)
825        || all_cte_scopes.iter().any(
826            |s| matches!(&s.expression, Expression::Cte(cte) if cte.alias.name == effective_table),
827        );
828    if is_cte {
829        if let Some(child_scope) = find_child_scope_in(all_cte_scopes, scope, effective_table) {
830            // Build ancestor CTE scopes from all_cte_scopes for the recursive call
831            let ancestors: Vec<Scope> = all_cte_scopes.iter().map(|s| (*s).clone()).collect();
832            if let Ok(child) = to_node_inner(
833                ColumnRef::Name(col_name),
834                child_scope,
835                dialect,
836                parent_name,
837                effective_table,
838                parent_name,
839                trim_selects,
840                &ancestors,
841                depth + 1,
842            ) {
843                node.downstream.push(child);
844                return;
845            }
846        }
847    }
848
849    // Check if table is a derived table (is_scope = true in sources)
850    if let Some(source_info) = scope.sources.get(table) {
851        if source_info.is_scope {
852            if let Some(child_scope) = find_child_scope(scope, table) {
853                let ancestors: Vec<Scope> = all_cte_scopes.iter().map(|s| (*s).clone()).collect();
854                if let Ok(child) = to_node_inner(
855                    ColumnRef::Name(col_name),
856                    child_scope,
857                    dialect,
858                    parent_name,
859                    table,
860                    parent_name,
861                    trim_selects,
862                    &ancestors,
863                    depth + 1,
864                ) {
865                    node.downstream.push(child);
866                    return;
867                }
868            }
869        }
870    }
871
872    // Base table source found in current scope: preserve alias in the display name
873    // but store the resolved table expression and name for downstream consumers.
874    if let Some(source_info) = scope.sources.get(table) {
875        if !source_info.is_scope {
876            node.downstream.push(make_table_column_node_from_source(
877                table,
878                col_name,
879                &source_info.expression,
880            ));
881            return;
882        }
883    }
884
885    // Base table or unresolved — terminal node
886    node.downstream
887        .push(make_table_column_node(table, col_name));
888}
889
890/// Resolve a FROM alias to the original CTE name.
891///
892/// When a query uses `FROM my_cte AS alias`, the scope's `sources` map contains
893/// `"alias"` → CTE expression, but `cte_sources` only contains `"my_cte"`.
894/// This function checks if `name` is such an alias and returns the CTE name.
895fn resolve_cte_alias(scope: &Scope, name: &str) -> Option<String> {
896    // If it's already a known CTE name, no resolution needed
897    if scope.cte_sources.contains_key(name) {
898        return None;
899    }
900    // Check if the source's expression is a CTE — if so, extract the CTE name
901    if let Some(source_info) = scope.sources.get(name) {
902        if source_info.is_scope {
903            if let Expression::Cte(cte) = &source_info.expression {
904                let cte_name = &cte.alias.name;
905                if scope.cte_sources.contains_key(cte_name) {
906                    return Some(cte_name.clone());
907                }
908            }
909        }
910    }
911    None
912}
913
914fn resolve_unqualified_column(
915    node: &mut LineageNode,
916    scope: &Scope,
917    dialect: Option<DialectType>,
918    col_name: &str,
919    parent_name: &str,
920    trim_selects: bool,
921    all_cte_scopes: &[&Scope],
922    depth: usize,
923) {
924    // Try to find which source this column belongs to.
925    // Build the source list from the actual FROM/JOIN clauses to avoid
926    // mixing in CTE definitions that are in scope but not referenced.
927    let from_source_names = source_names_from_from_join(scope);
928
929    if from_source_names.len() == 1 {
930        let tbl = &from_source_names[0];
931        resolve_qualified_column(
932            node,
933            scope,
934            dialect,
935            tbl,
936            col_name,
937            parent_name,
938            trim_selects,
939            all_cte_scopes,
940            depth,
941        );
942        return;
943    }
944
945    // Multiple sources — can't resolve without schema info, add unqualified node
946    let child = LineageNode::new(
947        col_name.to_string(),
948        Expression::Column(Box::new(crate::expressions::Column {
949            name: crate::expressions::Identifier::new(col_name.to_string()),
950            table: None,
951            join_mark: false,
952            trailing_comments: vec![],
953            span: None,
954            inferred_type: None,
955        })),
956        node.source.clone(),
957    );
958    node.downstream.push(child);
959}
960
961fn source_names_from_from_join(scope: &Scope) -> Vec<String> {
962    fn source_name(expr: &Expression) -> Option<String> {
963        match expr {
964            Expression::Table(table) => Some(
965                table
966                    .alias
967                    .as_ref()
968                    .map(|a| a.name.clone())
969                    .unwrap_or_else(|| table.name.name.clone()),
970            ),
971            Expression::Subquery(subquery) => {
972                subquery.alias.as_ref().map(|alias| alias.name.clone())
973            }
974            Expression::Paren(paren) => source_name(&paren.this),
975            _ => None,
976        }
977    }
978
979    let effective_expr = match &scope.expression {
980        Expression::Cte(cte) => &cte.this,
981        expr => expr,
982    };
983
984    let mut names = Vec::new();
985    let mut seen = std::collections::HashSet::new();
986
987    if let Expression::Select(select) = effective_expr {
988        if let Some(from) = &select.from {
989            for expr in &from.expressions {
990                if let Some(name) = source_name(expr) {
991                    if !name.is_empty() && seen.insert(name.clone()) {
992                        names.push(name);
993                    }
994                }
995            }
996        }
997        for join in &select.joins {
998            if let Some(name) = source_name(&join.this) {
999                if !name.is_empty() && seen.insert(name.clone()) {
1000                    names.push(name);
1001                }
1002            }
1003        }
1004    }
1005
1006    names
1007}
1008
1009// ---------------------------------------------------------------------------
1010// Helper functions
1011// ---------------------------------------------------------------------------
1012
1013/// Get the alias or name of an expression
1014fn get_alias_or_name(expr: &Expression) -> Option<String> {
1015    match expr {
1016        Expression::Alias(alias) => Some(alias.alias.name.clone()),
1017        Expression::Column(col) => Some(col.name.name.clone()),
1018        Expression::Identifier(id) => Some(id.name.clone()),
1019        Expression::Star(_) => Some("*".to_string()),
1020        // Annotated wraps an expression with trailing comments (e.g. `SELECT\n-- comment\na`).
1021        // Unwrap to get the actual column/alias name from the inner expression.
1022        Expression::Annotated(a) => get_alias_or_name(&a.this),
1023        _ => None,
1024    }
1025}
1026
1027/// Resolve the display name for a column reference.
1028fn resolve_column_name(column: &ColumnRef<'_>, select_expr: &Expression) -> String {
1029    match column {
1030        ColumnRef::Name(n) => n.to_string(),
1031        ColumnRef::Index(_) => get_alias_or_name(select_expr).unwrap_or_else(|| "?".to_string()),
1032    }
1033}
1034
1035/// Find the select expression matching a column reference.
1036fn find_select_expr(
1037    scope_expr: &Expression,
1038    column: &ColumnRef<'_>,
1039    dialect: Option<DialectType>,
1040) -> Result<Expression> {
1041    if let Expression::Select(ref select) = scope_expr {
1042        match column {
1043            ColumnRef::Name(name) => {
1044                let normalized_name = normalize_column_name(name, dialect);
1045                for expr in &select.expressions {
1046                    if let Some(alias_or_name) = get_alias_or_name(expr) {
1047                        if normalize_column_name(&alias_or_name, dialect) == normalized_name {
1048                            return Ok(expr.clone());
1049                        }
1050                    }
1051                }
1052                Err(crate::error::Error::parse(
1053                    format!("Cannot find column '{}' in query", name),
1054                    0,
1055                    0,
1056                    0,
1057                    0,
1058                ))
1059            }
1060            ColumnRef::Index(idx) => select.expressions.get(*idx).cloned().ok_or_else(|| {
1061                crate::error::Error::parse(format!("Column index {} out of range", idx), 0, 0, 0, 0)
1062            }),
1063        }
1064    } else {
1065        Err(crate::error::Error::parse(
1066            "Expected SELECT expression for column lookup",
1067            0,
1068            0,
1069            0,
1070            0,
1071        ))
1072    }
1073}
1074
1075/// Find the positional index of a column name in a set operation's first SELECT branch.
1076fn column_to_index(
1077    set_op_expr: &Expression,
1078    name: &str,
1079    dialect: Option<DialectType>,
1080) -> Result<usize> {
1081    let normalized_name = normalize_column_name(name, dialect);
1082    let mut expr = set_op_expr;
1083    loop {
1084        match expr {
1085            Expression::Union(u) => expr = &u.left,
1086            Expression::Intersect(i) => expr = &i.left,
1087            Expression::Except(e) => expr = &e.left,
1088            Expression::Select(select) => {
1089                for (i, e) in select.expressions.iter().enumerate() {
1090                    if let Some(alias_or_name) = get_alias_or_name(e) {
1091                        if normalize_column_name(&alias_or_name, dialect) == normalized_name {
1092                            return Ok(i);
1093                        }
1094                    }
1095                }
1096                return Err(crate::error::Error::parse(
1097                    format!("Cannot find column '{}' in set operation", name),
1098                    0,
1099                    0,
1100                    0,
1101                    0,
1102                ));
1103            }
1104            _ => {
1105                return Err(crate::error::Error::parse(
1106                    "Expected SELECT or set operation",
1107                    0,
1108                    0,
1109                    0,
1110                    0,
1111                ))
1112            }
1113        }
1114    }
1115}
1116
1117fn normalize_column_name(name: &str, dialect: Option<DialectType>) -> String {
1118    normalize_name(name, dialect, false, true)
1119}
1120
1121/// If trim_selects is enabled, return a copy of the SELECT with only the target column.
1122fn trim_source(select_expr: &Expression, target_expr: &Expression) -> Expression {
1123    if let Expression::Select(select) = select_expr {
1124        let mut trimmed = select.as_ref().clone();
1125        trimmed.expressions = vec![target_expr.clone()];
1126        Expression::Select(Box::new(trimmed))
1127    } else {
1128        select_expr.clone()
1129    }
1130}
1131
1132/// Find the child scope (CTE or derived table) for a given source name.
1133fn find_child_scope<'a>(scope: &'a Scope, source_name: &str) -> Option<&'a Scope> {
1134    // Check CTE scopes
1135    if scope.cte_sources.contains_key(source_name) {
1136        for cte_scope in &scope.cte_scopes {
1137            if let Expression::Cte(cte) = &cte_scope.expression {
1138                if cte.alias.name == source_name {
1139                    return Some(cte_scope);
1140                }
1141            }
1142        }
1143    }
1144
1145    // Check derived table scopes
1146    if let Some(source_info) = scope.sources.get(source_name) {
1147        if source_info.is_scope && !scope.cte_sources.contains_key(source_name) {
1148            if let Expression::Subquery(sq) = &source_info.expression {
1149                for dt_scope in &scope.derived_table_scopes {
1150                    if dt_scope.expression == sq.this {
1151                        return Some(dt_scope);
1152                    }
1153                }
1154            }
1155        }
1156    }
1157
1158    None
1159}
1160
1161/// Find a CTE scope by name, searching through a combined list of CTE scopes.
1162/// This handles nested CTEs where the current scope doesn't have the CTE scope
1163/// as a direct child but knows about it via cte_sources.
1164fn find_child_scope_in<'a>(
1165    all_cte_scopes: &[&'a Scope],
1166    scope: &'a Scope,
1167    source_name: &str,
1168) -> Option<&'a Scope> {
1169    // First try the scope's own cte_scopes
1170    for cte_scope in &scope.cte_scopes {
1171        if let Expression::Cte(cte) = &cte_scope.expression {
1172            if cte.alias.name == source_name {
1173                return Some(cte_scope);
1174            }
1175        }
1176    }
1177
1178    // Then search through all ancestor CTE scopes
1179    for cte_scope in all_cte_scopes {
1180        if let Expression::Cte(cte) = &cte_scope.expression {
1181            if cte.alias.name == source_name {
1182                return Some(cte_scope);
1183            }
1184        }
1185    }
1186
1187    // Fall back to derived table scopes
1188    if let Some(source_info) = scope.sources.get(source_name) {
1189        if source_info.is_scope {
1190            if let Expression::Subquery(sq) = &source_info.expression {
1191                for dt_scope in &scope.derived_table_scopes {
1192                    if dt_scope.expression == sq.this {
1193                        return Some(dt_scope);
1194                    }
1195                }
1196            }
1197        }
1198    }
1199
1200    None
1201}
1202
1203/// Create a terminal lineage node for a table.column reference.
1204fn make_table_column_node(table: &str, column: &str) -> LineageNode {
1205    let mut node = LineageNode::new(
1206        format!("{}.{}", table, column),
1207        Expression::Column(Box::new(crate::expressions::Column {
1208            name: crate::expressions::Identifier::new(column.to_string()),
1209            table: Some(crate::expressions::Identifier::new(table.to_string())),
1210            join_mark: false,
1211            trailing_comments: vec![],
1212            span: None,
1213            inferred_type: None,
1214        })),
1215        Expression::Table(Box::new(crate::expressions::TableRef::new(table))),
1216    );
1217    node.source_name = table.to_string();
1218    node
1219}
1220
1221fn table_name_from_table_ref(table_ref: &crate::expressions::TableRef) -> String {
1222    let mut parts: Vec<String> = Vec::new();
1223    if let Some(catalog) = &table_ref.catalog {
1224        parts.push(catalog.name.clone());
1225    }
1226    if let Some(schema) = &table_ref.schema {
1227        parts.push(schema.name.clone());
1228    }
1229    parts.push(table_ref.name.name.clone());
1230    parts.join(".")
1231}
1232
1233fn make_table_column_node_from_source(
1234    table_alias: &str,
1235    column: &str,
1236    source: &Expression,
1237) -> LineageNode {
1238    let mut node = LineageNode::new(
1239        format!("{}.{}", table_alias, column),
1240        Expression::Column(Box::new(crate::expressions::Column {
1241            name: crate::expressions::Identifier::new(column.to_string()),
1242            table: Some(crate::expressions::Identifier::new(table_alias.to_string())),
1243            join_mark: false,
1244            trailing_comments: vec![],
1245            span: None,
1246            inferred_type: None,
1247        })),
1248        source.clone(),
1249    );
1250
1251    if let Expression::Table(table_ref) = source {
1252        node.source_name = table_name_from_table_ref(table_ref);
1253    } else {
1254        node.source_name = table_alias.to_string();
1255    }
1256
1257    node
1258}
1259
1260/// Simple column reference extracted from an expression
1261#[derive(Debug, Clone)]
1262struct SimpleColumnRef {
1263    table: Option<crate::expressions::Identifier>,
1264    column: String,
1265}
1266
1267/// Find all column references in an expression (does not recurse into subqueries).
1268fn find_column_refs_in_expr(expr: &Expression) -> Vec<SimpleColumnRef> {
1269    let mut refs = Vec::new();
1270    collect_column_refs(expr, &mut refs);
1271    refs
1272}
1273
1274fn collect_column_refs(expr: &Expression, refs: &mut Vec<SimpleColumnRef>) {
1275    let mut stack: Vec<&Expression> = vec![expr];
1276
1277    while let Some(current) = stack.pop() {
1278        match current {
1279            // === Leaf: collect Column references ===
1280            Expression::Column(col) => {
1281                refs.push(SimpleColumnRef {
1282                    table: col.table.clone(),
1283                    column: col.name.name.clone(),
1284                });
1285            }
1286
1287            // === Boundary: don't recurse into subqueries (handled separately) ===
1288            Expression::Subquery(_) | Expression::Exists(_) => {}
1289
1290            // === BinaryOp variants: left, right ===
1291            Expression::And(op)
1292            | Expression::Or(op)
1293            | Expression::Eq(op)
1294            | Expression::Neq(op)
1295            | Expression::Lt(op)
1296            | Expression::Lte(op)
1297            | Expression::Gt(op)
1298            | Expression::Gte(op)
1299            | Expression::Add(op)
1300            | Expression::Sub(op)
1301            | Expression::Mul(op)
1302            | Expression::Div(op)
1303            | Expression::Mod(op)
1304            | Expression::BitwiseAnd(op)
1305            | Expression::BitwiseOr(op)
1306            | Expression::BitwiseXor(op)
1307            | Expression::BitwiseLeftShift(op)
1308            | Expression::BitwiseRightShift(op)
1309            | Expression::Concat(op)
1310            | Expression::Adjacent(op)
1311            | Expression::TsMatch(op)
1312            | Expression::PropertyEQ(op)
1313            | Expression::ArrayContainsAll(op)
1314            | Expression::ArrayContainedBy(op)
1315            | Expression::ArrayOverlaps(op)
1316            | Expression::JSONBContainsAllTopKeys(op)
1317            | Expression::JSONBContainsAnyTopKeys(op)
1318            | Expression::JSONBDeleteAtPath(op)
1319            | Expression::ExtendsLeft(op)
1320            | Expression::ExtendsRight(op)
1321            | Expression::Is(op)
1322            | Expression::MemberOf(op)
1323            | Expression::NullSafeEq(op)
1324            | Expression::NullSafeNeq(op)
1325            | Expression::Glob(op)
1326            | Expression::Match(op) => {
1327                stack.push(&op.left);
1328                stack.push(&op.right);
1329            }
1330
1331            // === UnaryOp variants: this ===
1332            Expression::Not(u) | Expression::Neg(u) | Expression::BitwiseNot(u) => {
1333                stack.push(&u.this);
1334            }
1335
1336            // === UnaryFunc variants: this ===
1337            Expression::Upper(f)
1338            | Expression::Lower(f)
1339            | Expression::Length(f)
1340            | Expression::LTrim(f)
1341            | Expression::RTrim(f)
1342            | Expression::Reverse(f)
1343            | Expression::Abs(f)
1344            | Expression::Sqrt(f)
1345            | Expression::Cbrt(f)
1346            | Expression::Ln(f)
1347            | Expression::Exp(f)
1348            | Expression::Sign(f)
1349            | Expression::Date(f)
1350            | Expression::Time(f)
1351            | Expression::DateFromUnixDate(f)
1352            | Expression::UnixDate(f)
1353            | Expression::UnixSeconds(f)
1354            | Expression::UnixMillis(f)
1355            | Expression::UnixMicros(f)
1356            | Expression::TimeStrToDate(f)
1357            | Expression::DateToDi(f)
1358            | Expression::DiToDate(f)
1359            | Expression::TsOrDiToDi(f)
1360            | Expression::TsOrDsToDatetime(f)
1361            | Expression::TsOrDsToTimestamp(f)
1362            | Expression::YearOfWeek(f)
1363            | Expression::YearOfWeekIso(f)
1364            | Expression::Initcap(f)
1365            | Expression::Ascii(f)
1366            | Expression::Chr(f)
1367            | Expression::Soundex(f)
1368            | Expression::ByteLength(f)
1369            | Expression::Hex(f)
1370            | Expression::LowerHex(f)
1371            | Expression::Unicode(f)
1372            | Expression::Radians(f)
1373            | Expression::Degrees(f)
1374            | Expression::Sin(f)
1375            | Expression::Cos(f)
1376            | Expression::Tan(f)
1377            | Expression::Asin(f)
1378            | Expression::Acos(f)
1379            | Expression::Atan(f)
1380            | Expression::IsNan(f)
1381            | Expression::IsInf(f)
1382            | Expression::ArrayLength(f)
1383            | Expression::ArraySize(f)
1384            | Expression::Cardinality(f)
1385            | Expression::ArrayReverse(f)
1386            | Expression::ArrayDistinct(f)
1387            | Expression::ArrayFlatten(f)
1388            | Expression::ArrayCompact(f)
1389            | Expression::Explode(f)
1390            | Expression::ExplodeOuter(f)
1391            | Expression::ToArray(f)
1392            | Expression::MapFromEntries(f)
1393            | Expression::MapKeys(f)
1394            | Expression::MapValues(f)
1395            | Expression::JsonArrayLength(f)
1396            | Expression::JsonKeys(f)
1397            | Expression::JsonType(f)
1398            | Expression::ParseJson(f)
1399            | Expression::ToJson(f)
1400            | Expression::Typeof(f)
1401            | Expression::BitwiseCount(f)
1402            | Expression::Year(f)
1403            | Expression::Month(f)
1404            | Expression::Day(f)
1405            | Expression::Hour(f)
1406            | Expression::Minute(f)
1407            | Expression::Second(f)
1408            | Expression::DayOfWeek(f)
1409            | Expression::DayOfWeekIso(f)
1410            | Expression::DayOfMonth(f)
1411            | Expression::DayOfYear(f)
1412            | Expression::WeekOfYear(f)
1413            | Expression::Quarter(f)
1414            | Expression::Epoch(f)
1415            | Expression::EpochMs(f)
1416            | Expression::TimeStrToUnix(f)
1417            | Expression::SHA(f)
1418            | Expression::SHA1Digest(f)
1419            | Expression::TimeToUnix(f)
1420            | Expression::JSONBool(f)
1421            | Expression::Int64(f)
1422            | Expression::MD5NumberLower64(f)
1423            | Expression::MD5NumberUpper64(f)
1424            | Expression::DateStrToDate(f)
1425            | Expression::DateToDateStr(f) => {
1426                stack.push(&f.this);
1427            }
1428
1429            // === BinaryFunc variants: this, expression ===
1430            Expression::Power(f)
1431            | Expression::NullIf(f)
1432            | Expression::IfNull(f)
1433            | Expression::Nvl(f)
1434            | Expression::UnixToTimeStr(f)
1435            | Expression::Contains(f)
1436            | Expression::StartsWith(f)
1437            | Expression::EndsWith(f)
1438            | Expression::Levenshtein(f)
1439            | Expression::ModFunc(f)
1440            | Expression::Atan2(f)
1441            | Expression::IntDiv(f)
1442            | Expression::AddMonths(f)
1443            | Expression::MonthsBetween(f)
1444            | Expression::NextDay(f)
1445            | Expression::ArrayContains(f)
1446            | Expression::ArrayPosition(f)
1447            | Expression::ArrayAppend(f)
1448            | Expression::ArrayPrepend(f)
1449            | Expression::ArrayUnion(f)
1450            | Expression::ArrayExcept(f)
1451            | Expression::ArrayRemove(f)
1452            | Expression::StarMap(f)
1453            | Expression::MapFromArrays(f)
1454            | Expression::MapContainsKey(f)
1455            | Expression::ElementAt(f)
1456            | Expression::JsonMergePatch(f)
1457            | Expression::JSONBContains(f)
1458            | Expression::JSONBExtract(f) => {
1459                stack.push(&f.this);
1460                stack.push(&f.expression);
1461            }
1462
1463            // === VarArgFunc variants: expressions ===
1464            Expression::Greatest(f)
1465            | Expression::Least(f)
1466            | Expression::Coalesce(f)
1467            | Expression::ArrayConcat(f)
1468            | Expression::ArrayIntersect(f)
1469            | Expression::ArrayZip(f)
1470            | Expression::MapConcat(f)
1471            | Expression::JsonArray(f) => {
1472                for e in &f.expressions {
1473                    stack.push(e);
1474                }
1475            }
1476
1477            // === AggFunc variants: this, filter, having_max, limit ===
1478            Expression::Sum(f)
1479            | Expression::Avg(f)
1480            | Expression::Min(f)
1481            | Expression::Max(f)
1482            | Expression::ArrayAgg(f)
1483            | Expression::CountIf(f)
1484            | Expression::Stddev(f)
1485            | Expression::StddevPop(f)
1486            | Expression::StddevSamp(f)
1487            | Expression::Variance(f)
1488            | Expression::VarPop(f)
1489            | Expression::VarSamp(f)
1490            | Expression::Median(f)
1491            | Expression::Mode(f)
1492            | Expression::First(f)
1493            | Expression::Last(f)
1494            | Expression::AnyValue(f)
1495            | Expression::ApproxDistinct(f)
1496            | Expression::ApproxCountDistinct(f)
1497            | Expression::LogicalAnd(f)
1498            | Expression::LogicalOr(f)
1499            | Expression::Skewness(f)
1500            | Expression::ArrayConcatAgg(f)
1501            | Expression::ArrayUniqueAgg(f)
1502            | Expression::BoolXorAgg(f)
1503            | Expression::BitwiseAndAgg(f)
1504            | Expression::BitwiseOrAgg(f)
1505            | Expression::BitwiseXorAgg(f) => {
1506                stack.push(&f.this);
1507                if let Some(ref filter) = f.filter {
1508                    stack.push(filter);
1509                }
1510                if let Some((ref expr, _)) = f.having_max {
1511                    stack.push(expr);
1512                }
1513                if let Some(ref limit) = f.limit {
1514                    stack.push(limit);
1515                }
1516            }
1517
1518            // === Generic Function / AggregateFunction: args ===
1519            Expression::Function(func) => {
1520                for arg in &func.args {
1521                    stack.push(arg);
1522                }
1523            }
1524            Expression::AggregateFunction(func) => {
1525                for arg in &func.args {
1526                    stack.push(arg);
1527                }
1528                if let Some(ref filter) = func.filter {
1529                    stack.push(filter);
1530                }
1531                if let Some(ref limit) = func.limit {
1532                    stack.push(limit);
1533                }
1534            }
1535
1536            // === WindowFunction: this (skip Over for lineage purposes) ===
1537            Expression::WindowFunction(wf) => {
1538                stack.push(&wf.this);
1539            }
1540
1541            // === Containers and special expressions ===
1542            Expression::Alias(a) => {
1543                stack.push(&a.this);
1544            }
1545            Expression::Cast(c) | Expression::TryCast(c) | Expression::SafeCast(c) => {
1546                stack.push(&c.this);
1547                if let Some(ref fmt) = c.format {
1548                    stack.push(fmt);
1549                }
1550                if let Some(ref def) = c.default {
1551                    stack.push(def);
1552                }
1553            }
1554            Expression::Paren(p) => {
1555                stack.push(&p.this);
1556            }
1557            Expression::Annotated(a) => {
1558                stack.push(&a.this);
1559            }
1560            Expression::Case(case) => {
1561                if let Some(ref operand) = case.operand {
1562                    stack.push(operand);
1563                }
1564                for (cond, result) in &case.whens {
1565                    stack.push(cond);
1566                    stack.push(result);
1567                }
1568                if let Some(ref else_expr) = case.else_ {
1569                    stack.push(else_expr);
1570                }
1571            }
1572            Expression::Collation(c) => {
1573                stack.push(&c.this);
1574            }
1575            Expression::In(i) => {
1576                stack.push(&i.this);
1577                for e in &i.expressions {
1578                    stack.push(e);
1579                }
1580                if let Some(ref q) = i.query {
1581                    stack.push(q);
1582                }
1583                if let Some(ref u) = i.unnest {
1584                    stack.push(u);
1585                }
1586            }
1587            Expression::Between(b) => {
1588                stack.push(&b.this);
1589                stack.push(&b.low);
1590                stack.push(&b.high);
1591            }
1592            Expression::IsNull(n) => {
1593                stack.push(&n.this);
1594            }
1595            Expression::IsTrue(t) | Expression::IsFalse(t) => {
1596                stack.push(&t.this);
1597            }
1598            Expression::IsJson(j) => {
1599                stack.push(&j.this);
1600            }
1601            Expression::Like(l) | Expression::ILike(l) => {
1602                stack.push(&l.left);
1603                stack.push(&l.right);
1604                if let Some(ref esc) = l.escape {
1605                    stack.push(esc);
1606                }
1607            }
1608            Expression::SimilarTo(s) => {
1609                stack.push(&s.this);
1610                stack.push(&s.pattern);
1611                if let Some(ref esc) = s.escape {
1612                    stack.push(esc);
1613                }
1614            }
1615            Expression::Ordered(o) => {
1616                stack.push(&o.this);
1617            }
1618            Expression::Array(a) => {
1619                for e in &a.expressions {
1620                    stack.push(e);
1621                }
1622            }
1623            Expression::Tuple(t) => {
1624                for e in &t.expressions {
1625                    stack.push(e);
1626                }
1627            }
1628            Expression::Struct(s) => {
1629                for (_, e) in &s.fields {
1630                    stack.push(e);
1631                }
1632            }
1633            Expression::Subscript(s) => {
1634                stack.push(&s.this);
1635                stack.push(&s.index);
1636            }
1637            Expression::Dot(d) => {
1638                stack.push(&d.this);
1639            }
1640            Expression::MethodCall(m) => {
1641                stack.push(&m.this);
1642                for arg in &m.args {
1643                    stack.push(arg);
1644                }
1645            }
1646            Expression::ArraySlice(s) => {
1647                stack.push(&s.this);
1648                if let Some(ref start) = s.start {
1649                    stack.push(start);
1650                }
1651                if let Some(ref end) = s.end {
1652                    stack.push(end);
1653                }
1654            }
1655            Expression::Lambda(l) => {
1656                stack.push(&l.body);
1657            }
1658            Expression::NamedArgument(n) => {
1659                stack.push(&n.value);
1660            }
1661            Expression::BracedWildcard(e) | Expression::ReturnStmt(e) => {
1662                stack.push(e);
1663            }
1664
1665            // === Custom function structs ===
1666            Expression::Substring(f) => {
1667                stack.push(&f.this);
1668                stack.push(&f.start);
1669                if let Some(ref len) = f.length {
1670                    stack.push(len);
1671                }
1672            }
1673            Expression::Trim(f) => {
1674                stack.push(&f.this);
1675                if let Some(ref chars) = f.characters {
1676                    stack.push(chars);
1677                }
1678            }
1679            Expression::Replace(f) => {
1680                stack.push(&f.this);
1681                stack.push(&f.old);
1682                stack.push(&f.new);
1683            }
1684            Expression::IfFunc(f) => {
1685                stack.push(&f.condition);
1686                stack.push(&f.true_value);
1687                if let Some(ref fv) = f.false_value {
1688                    stack.push(fv);
1689                }
1690            }
1691            Expression::Nvl2(f) => {
1692                stack.push(&f.this);
1693                stack.push(&f.true_value);
1694                stack.push(&f.false_value);
1695            }
1696            Expression::ConcatWs(f) => {
1697                stack.push(&f.separator);
1698                for e in &f.expressions {
1699                    stack.push(e);
1700                }
1701            }
1702            Expression::Count(f) => {
1703                if let Some(ref this) = f.this {
1704                    stack.push(this);
1705                }
1706                if let Some(ref filter) = f.filter {
1707                    stack.push(filter);
1708                }
1709            }
1710            Expression::GroupConcat(f) => {
1711                stack.push(&f.this);
1712                if let Some(ref sep) = f.separator {
1713                    stack.push(sep);
1714                }
1715                if let Some(ref filter) = f.filter {
1716                    stack.push(filter);
1717                }
1718            }
1719            Expression::StringAgg(f) => {
1720                stack.push(&f.this);
1721                if let Some(ref sep) = f.separator {
1722                    stack.push(sep);
1723                }
1724                if let Some(ref filter) = f.filter {
1725                    stack.push(filter);
1726                }
1727                if let Some(ref limit) = f.limit {
1728                    stack.push(limit);
1729                }
1730            }
1731            Expression::ListAgg(f) => {
1732                stack.push(&f.this);
1733                if let Some(ref sep) = f.separator {
1734                    stack.push(sep);
1735                }
1736                if let Some(ref filter) = f.filter {
1737                    stack.push(filter);
1738                }
1739            }
1740            Expression::SumIf(f) => {
1741                stack.push(&f.this);
1742                stack.push(&f.condition);
1743                if let Some(ref filter) = f.filter {
1744                    stack.push(filter);
1745                }
1746            }
1747            Expression::DateAdd(f) | Expression::DateSub(f) => {
1748                stack.push(&f.this);
1749                stack.push(&f.interval);
1750            }
1751            Expression::DateDiff(f) => {
1752                stack.push(&f.this);
1753                stack.push(&f.expression);
1754            }
1755            Expression::DateTrunc(f) | Expression::TimestampTrunc(f) => {
1756                stack.push(&f.this);
1757            }
1758            Expression::Extract(f) => {
1759                stack.push(&f.this);
1760            }
1761            Expression::Round(f) => {
1762                stack.push(&f.this);
1763                if let Some(ref d) = f.decimals {
1764                    stack.push(d);
1765                }
1766            }
1767            Expression::Floor(f) => {
1768                stack.push(&f.this);
1769                if let Some(ref s) = f.scale {
1770                    stack.push(s);
1771                }
1772                if let Some(ref t) = f.to {
1773                    stack.push(t);
1774                }
1775            }
1776            Expression::Ceil(f) => {
1777                stack.push(&f.this);
1778                if let Some(ref d) = f.decimals {
1779                    stack.push(d);
1780                }
1781                if let Some(ref t) = f.to {
1782                    stack.push(t);
1783                }
1784            }
1785            Expression::Log(f) => {
1786                stack.push(&f.this);
1787                if let Some(ref b) = f.base {
1788                    stack.push(b);
1789                }
1790            }
1791            Expression::AtTimeZone(f) => {
1792                stack.push(&f.this);
1793                stack.push(&f.zone);
1794            }
1795            Expression::Lead(f) | Expression::Lag(f) => {
1796                stack.push(&f.this);
1797                if let Some(ref off) = f.offset {
1798                    stack.push(off);
1799                }
1800                if let Some(ref def) = f.default {
1801                    stack.push(def);
1802                }
1803            }
1804            Expression::FirstValue(f) | Expression::LastValue(f) => {
1805                stack.push(&f.this);
1806            }
1807            Expression::NthValue(f) => {
1808                stack.push(&f.this);
1809                stack.push(&f.offset);
1810            }
1811            Expression::Position(f) => {
1812                stack.push(&f.substring);
1813                stack.push(&f.string);
1814                if let Some(ref start) = f.start {
1815                    stack.push(start);
1816                }
1817            }
1818            Expression::Decode(f) => {
1819                stack.push(&f.this);
1820                for (search, result) in &f.search_results {
1821                    stack.push(search);
1822                    stack.push(result);
1823                }
1824                if let Some(ref def) = f.default {
1825                    stack.push(def);
1826                }
1827            }
1828            Expression::CharFunc(f) => {
1829                for arg in &f.args {
1830                    stack.push(arg);
1831                }
1832            }
1833            Expression::ArraySort(f) => {
1834                stack.push(&f.this);
1835                if let Some(ref cmp) = f.comparator {
1836                    stack.push(cmp);
1837                }
1838            }
1839            Expression::ArrayJoin(f) | Expression::ArrayToString(f) => {
1840                stack.push(&f.this);
1841                stack.push(&f.separator);
1842                if let Some(ref nr) = f.null_replacement {
1843                    stack.push(nr);
1844                }
1845            }
1846            Expression::ArrayFilter(f) => {
1847                stack.push(&f.this);
1848                stack.push(&f.filter);
1849            }
1850            Expression::ArrayTransform(f) => {
1851                stack.push(&f.this);
1852                stack.push(&f.transform);
1853            }
1854            Expression::Sequence(f)
1855            | Expression::Generate(f)
1856            | Expression::ExplodingGenerateSeries(f) => {
1857                stack.push(&f.start);
1858                stack.push(&f.stop);
1859                if let Some(ref step) = f.step {
1860                    stack.push(step);
1861                }
1862            }
1863            Expression::JsonExtract(f)
1864            | Expression::JsonExtractScalar(f)
1865            | Expression::JsonQuery(f)
1866            | Expression::JsonValue(f) => {
1867                stack.push(&f.this);
1868                stack.push(&f.path);
1869            }
1870            Expression::JsonExtractPath(f) | Expression::JsonRemove(f) => {
1871                stack.push(&f.this);
1872                for p in &f.paths {
1873                    stack.push(p);
1874                }
1875            }
1876            Expression::JsonObject(f) => {
1877                for (k, v) in &f.pairs {
1878                    stack.push(k);
1879                    stack.push(v);
1880                }
1881            }
1882            Expression::JsonSet(f) | Expression::JsonInsert(f) => {
1883                stack.push(&f.this);
1884                for (path, val) in &f.path_values {
1885                    stack.push(path);
1886                    stack.push(val);
1887                }
1888            }
1889            Expression::Overlay(f) => {
1890                stack.push(&f.this);
1891                stack.push(&f.replacement);
1892                stack.push(&f.from);
1893                if let Some(ref len) = f.length {
1894                    stack.push(len);
1895                }
1896            }
1897            Expression::Convert(f) => {
1898                stack.push(&f.this);
1899                if let Some(ref style) = f.style {
1900                    stack.push(style);
1901                }
1902            }
1903            Expression::ApproxPercentile(f) => {
1904                stack.push(&f.this);
1905                stack.push(&f.percentile);
1906                if let Some(ref acc) = f.accuracy {
1907                    stack.push(acc);
1908                }
1909                if let Some(ref filter) = f.filter {
1910                    stack.push(filter);
1911                }
1912            }
1913            Expression::Percentile(f)
1914            | Expression::PercentileCont(f)
1915            | Expression::PercentileDisc(f) => {
1916                stack.push(&f.this);
1917                stack.push(&f.percentile);
1918                if let Some(ref filter) = f.filter {
1919                    stack.push(filter);
1920                }
1921            }
1922            Expression::WithinGroup(f) => {
1923                stack.push(&f.this);
1924            }
1925            Expression::Left(f) | Expression::Right(f) => {
1926                stack.push(&f.this);
1927                stack.push(&f.length);
1928            }
1929            Expression::Repeat(f) => {
1930                stack.push(&f.this);
1931                stack.push(&f.times);
1932            }
1933            Expression::Lpad(f) | Expression::Rpad(f) => {
1934                stack.push(&f.this);
1935                stack.push(&f.length);
1936                if let Some(ref fill) = f.fill {
1937                    stack.push(fill);
1938                }
1939            }
1940            Expression::Split(f) => {
1941                stack.push(&f.this);
1942                stack.push(&f.delimiter);
1943            }
1944            Expression::RegexpLike(f) => {
1945                stack.push(&f.this);
1946                stack.push(&f.pattern);
1947                if let Some(ref flags) = f.flags {
1948                    stack.push(flags);
1949                }
1950            }
1951            Expression::RegexpReplace(f) => {
1952                stack.push(&f.this);
1953                stack.push(&f.pattern);
1954                stack.push(&f.replacement);
1955                if let Some(ref flags) = f.flags {
1956                    stack.push(flags);
1957                }
1958            }
1959            Expression::RegexpExtract(f) => {
1960                stack.push(&f.this);
1961                stack.push(&f.pattern);
1962                if let Some(ref group) = f.group {
1963                    stack.push(group);
1964                }
1965            }
1966            Expression::ToDate(f) => {
1967                stack.push(&f.this);
1968                if let Some(ref fmt) = f.format {
1969                    stack.push(fmt);
1970                }
1971            }
1972            Expression::ToTimestamp(f) => {
1973                stack.push(&f.this);
1974                if let Some(ref fmt) = f.format {
1975                    stack.push(fmt);
1976                }
1977            }
1978            Expression::DateFormat(f) | Expression::FormatDate(f) => {
1979                stack.push(&f.this);
1980                stack.push(&f.format);
1981            }
1982            Expression::LastDay(f) => {
1983                stack.push(&f.this);
1984            }
1985            Expression::FromUnixtime(f) => {
1986                stack.push(&f.this);
1987                if let Some(ref fmt) = f.format {
1988                    stack.push(fmt);
1989                }
1990            }
1991            Expression::UnixTimestamp(f) => {
1992                if let Some(ref this) = f.this {
1993                    stack.push(this);
1994                }
1995                if let Some(ref fmt) = f.format {
1996                    stack.push(fmt);
1997                }
1998            }
1999            Expression::MakeDate(f) => {
2000                stack.push(&f.year);
2001                stack.push(&f.month);
2002                stack.push(&f.day);
2003            }
2004            Expression::MakeTimestamp(f) => {
2005                stack.push(&f.year);
2006                stack.push(&f.month);
2007                stack.push(&f.day);
2008                stack.push(&f.hour);
2009                stack.push(&f.minute);
2010                stack.push(&f.second);
2011                if let Some(ref tz) = f.timezone {
2012                    stack.push(tz);
2013                }
2014            }
2015            Expression::TruncFunc(f) => {
2016                stack.push(&f.this);
2017                if let Some(ref d) = f.decimals {
2018                    stack.push(d);
2019                }
2020            }
2021            Expression::ArrayFunc(f) => {
2022                for e in &f.expressions {
2023                    stack.push(e);
2024                }
2025            }
2026            Expression::Unnest(f) => {
2027                stack.push(&f.this);
2028                for e in &f.expressions {
2029                    stack.push(e);
2030                }
2031            }
2032            Expression::StructFunc(f) => {
2033                for (_, e) in &f.fields {
2034                    stack.push(e);
2035                }
2036            }
2037            Expression::StructExtract(f) => {
2038                stack.push(&f.this);
2039            }
2040            Expression::NamedStruct(f) => {
2041                for (k, v) in &f.pairs {
2042                    stack.push(k);
2043                    stack.push(v);
2044                }
2045            }
2046            Expression::MapFunc(f) => {
2047                for k in &f.keys {
2048                    stack.push(k);
2049                }
2050                for v in &f.values {
2051                    stack.push(v);
2052                }
2053            }
2054            Expression::TransformKeys(f) | Expression::TransformValues(f) => {
2055                stack.push(&f.this);
2056                stack.push(&f.transform);
2057            }
2058            Expression::JsonArrayAgg(f) => {
2059                stack.push(&f.this);
2060                if let Some(ref filter) = f.filter {
2061                    stack.push(filter);
2062                }
2063            }
2064            Expression::JsonObjectAgg(f) => {
2065                stack.push(&f.key);
2066                stack.push(&f.value);
2067                if let Some(ref filter) = f.filter {
2068                    stack.push(filter);
2069                }
2070            }
2071            Expression::NTile(f) => {
2072                if let Some(ref n) = f.num_buckets {
2073                    stack.push(n);
2074                }
2075            }
2076            Expression::Rand(f) => {
2077                if let Some(ref s) = f.seed {
2078                    stack.push(s);
2079                }
2080                if let Some(ref lo) = f.lower {
2081                    stack.push(lo);
2082                }
2083                if let Some(ref hi) = f.upper {
2084                    stack.push(hi);
2085                }
2086            }
2087            Expression::Any(q) | Expression::All(q) => {
2088                stack.push(&q.this);
2089                stack.push(&q.subquery);
2090            }
2091            Expression::Overlaps(o) => {
2092                if let Some(ref this) = o.this {
2093                    stack.push(this);
2094                }
2095                if let Some(ref expr) = o.expression {
2096                    stack.push(expr);
2097                }
2098                if let Some(ref ls) = o.left_start {
2099                    stack.push(ls);
2100                }
2101                if let Some(ref le) = o.left_end {
2102                    stack.push(le);
2103                }
2104                if let Some(ref rs) = o.right_start {
2105                    stack.push(rs);
2106                }
2107                if let Some(ref re) = o.right_end {
2108                    stack.push(re);
2109                }
2110            }
2111            Expression::Interval(i) => {
2112                if let Some(ref this) = i.this {
2113                    stack.push(this);
2114                }
2115            }
2116            Expression::TimeStrToTime(f) => {
2117                stack.push(&f.this);
2118                if let Some(ref zone) = f.zone {
2119                    stack.push(zone);
2120                }
2121            }
2122            Expression::JSONBExtractScalar(f) => {
2123                stack.push(&f.this);
2124                stack.push(&f.expression);
2125                if let Some(ref jt) = f.json_type {
2126                    stack.push(jt);
2127                }
2128            }
2129
2130            // === True leaves and non-expression-bearing nodes ===
2131            // Literals, Identifier, Star, DataType, Placeholder, Boolean, Null,
2132            // CurrentDate/Time/Timestamp, RowNumber, Rank, DenseRank, PercentRank,
2133            // CumeDist, Random, Pi, SessionUser, DDL statements, clauses, etc.
2134            _ => {}
2135        }
2136    }
2137}
2138
2139// ---------------------------------------------------------------------------
2140// Tests
2141// ---------------------------------------------------------------------------
2142
2143#[cfg(test)]
2144mod tests {
2145    use super::*;
2146    use crate::dialects::{Dialect, DialectType};
2147    use crate::expressions::DataType;
2148    use crate::optimizer::annotate_types::annotate_types;
2149    use crate::parse_one;
2150    use crate::schema::{MappingSchema, Schema};
2151
2152    fn parse(sql: &str) -> Expression {
2153        let dialect = Dialect::get(DialectType::Generic);
2154        let ast = dialect.parse(sql).unwrap();
2155        ast.into_iter().next().unwrap()
2156    }
2157
2158    #[test]
2159    fn test_simple_lineage() {
2160        let expr = parse("SELECT a FROM t");
2161        let node = lineage("a", &expr, None, false).unwrap();
2162
2163        assert_eq!(node.name, "a");
2164        assert!(!node.downstream.is_empty(), "Should have downstream nodes");
2165        // Should trace to t.a
2166        let names = node.downstream_names();
2167        assert!(
2168            names.iter().any(|n| n == "t.a"),
2169            "Expected t.a in downstream, got: {:?}",
2170            names
2171        );
2172    }
2173
2174    #[test]
2175    fn test_lineage_walk() {
2176        let root = LineageNode {
2177            name: "col_a".to_string(),
2178            expression: Expression::Null(crate::expressions::Null),
2179            source: Expression::Null(crate::expressions::Null),
2180            downstream: vec![LineageNode::new(
2181                "t.a",
2182                Expression::Null(crate::expressions::Null),
2183                Expression::Null(crate::expressions::Null),
2184            )],
2185            source_name: String::new(),
2186            reference_node_name: String::new(),
2187        };
2188
2189        let names: Vec<_> = root.walk().map(|n| n.name.clone()).collect();
2190        assert_eq!(names.len(), 2);
2191        assert_eq!(names[0], "col_a");
2192        assert_eq!(names[1], "t.a");
2193    }
2194
2195    #[test]
2196    fn test_aliased_column() {
2197        let expr = parse("SELECT a + 1 AS b FROM t");
2198        let node = lineage("b", &expr, None, false).unwrap();
2199
2200        assert_eq!(node.name, "b");
2201        // Should trace through the expression to t.a
2202        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2203        assert!(
2204            all_names.iter().any(|n| n.contains("a")),
2205            "Expected to trace to column a, got: {:?}",
2206            all_names
2207        );
2208    }
2209
2210    #[test]
2211    fn test_qualified_column() {
2212        let expr = parse("SELECT t.a FROM t");
2213        let node = lineage("a", &expr, None, false).unwrap();
2214
2215        assert_eq!(node.name, "a");
2216        let names = node.downstream_names();
2217        assert!(
2218            names.iter().any(|n| n == "t.a"),
2219            "Expected t.a, got: {:?}",
2220            names
2221        );
2222    }
2223
2224    #[test]
2225    fn test_unqualified_column() {
2226        let expr = parse("SELECT a FROM t");
2227        let node = lineage("a", &expr, None, false).unwrap();
2228
2229        // Unqualified but single source → resolved to t.a
2230        let names = node.downstream_names();
2231        assert!(
2232            names.iter().any(|n| n == "t.a"),
2233            "Expected t.a, got: {:?}",
2234            names
2235        );
2236    }
2237
2238    #[test]
2239    fn test_lineage_with_schema_qualifies_root_expression_issue_40() {
2240        let query = "SELECT name FROM users";
2241        let dialect = Dialect::get(DialectType::BigQuery);
2242        let expr = dialect
2243            .parse(query)
2244            .unwrap()
2245            .into_iter()
2246            .next()
2247            .expect("expected one expression");
2248
2249        let mut schema = MappingSchema::with_dialect(DialectType::BigQuery);
2250        schema
2251            .add_table("users", &[("name".into(), DataType::Text)], None)
2252            .expect("schema setup");
2253
2254        let node_without_schema = lineage("name", &expr, Some(DialectType::BigQuery), false)
2255            .expect("lineage without schema");
2256        let mut expr_without = node_without_schema.expression.clone();
2257        annotate_types(
2258            &mut expr_without,
2259            Some(&schema),
2260            Some(DialectType::BigQuery),
2261        );
2262        assert_eq!(
2263            expr_without.inferred_type(),
2264            None,
2265            "Expected unresolved root type without schema-aware lineage qualification"
2266        );
2267
2268        let node_with_schema = lineage_with_schema(
2269            "name",
2270            &expr,
2271            Some(&schema),
2272            Some(DialectType::BigQuery),
2273            false,
2274        )
2275        .expect("lineage with schema");
2276        let mut expr_with = node_with_schema.expression.clone();
2277        annotate_types(&mut expr_with, Some(&schema), Some(DialectType::BigQuery));
2278
2279        assert_eq!(expr_with.inferred_type(), Some(&DataType::Text));
2280    }
2281
2282    #[test]
2283    fn test_lineage_with_schema_correlated_scalar_subquery() {
2284        let query = "SELECT id, (SELECT AVG(val) FROM t2 WHERE t2.id = t1.id) AS avg_val FROM t1";
2285        let dialect = Dialect::get(DialectType::BigQuery);
2286        let expr = dialect
2287            .parse(query)
2288            .unwrap()
2289            .into_iter()
2290            .next()
2291            .expect("expected one expression");
2292
2293        let mut schema = MappingSchema::with_dialect(DialectType::BigQuery);
2294        schema
2295            .add_table(
2296                "t1",
2297                &[("id".into(), DataType::BigInt { length: None })],
2298                None,
2299            )
2300            .expect("schema setup");
2301        schema
2302            .add_table(
2303                "t2",
2304                &[
2305                    ("id".into(), DataType::BigInt { length: None }),
2306                    ("val".into(), DataType::BigInt { length: None }),
2307                ],
2308                None,
2309            )
2310            .expect("schema setup");
2311
2312        let node = lineage_with_schema(
2313            "id",
2314            &expr,
2315            Some(&schema),
2316            Some(DialectType::BigQuery),
2317            false,
2318        )
2319        .expect("lineage_with_schema should handle correlated scalar subqueries");
2320
2321        assert_eq!(node.name, "id");
2322    }
2323
2324    #[test]
2325    fn test_lineage_with_schema_join_using() {
2326        let query = "SELECT a FROM t1 JOIN t2 USING(a)";
2327        let dialect = Dialect::get(DialectType::BigQuery);
2328        let expr = dialect
2329            .parse(query)
2330            .unwrap()
2331            .into_iter()
2332            .next()
2333            .expect("expected one expression");
2334
2335        let mut schema = MappingSchema::with_dialect(DialectType::BigQuery);
2336        schema
2337            .add_table(
2338                "t1",
2339                &[("a".into(), DataType::BigInt { length: None })],
2340                None,
2341            )
2342            .expect("schema setup");
2343        schema
2344            .add_table(
2345                "t2",
2346                &[("a".into(), DataType::BigInt { length: None })],
2347                None,
2348            )
2349            .expect("schema setup");
2350
2351        let node = lineage_with_schema(
2352            "a",
2353            &expr,
2354            Some(&schema),
2355            Some(DialectType::BigQuery),
2356            false,
2357        )
2358        .expect("lineage_with_schema should handle JOIN USING");
2359
2360        assert_eq!(node.name, "a");
2361    }
2362
2363    #[test]
2364    fn test_lineage_with_schema_qualified_table_name() {
2365        let query = "SELECT a FROM raw.t1";
2366        let dialect = Dialect::get(DialectType::BigQuery);
2367        let expr = dialect
2368            .parse(query)
2369            .unwrap()
2370            .into_iter()
2371            .next()
2372            .expect("expected one expression");
2373
2374        let mut schema = MappingSchema::with_dialect(DialectType::BigQuery);
2375        schema
2376            .add_table(
2377                "raw.t1",
2378                &[("a".into(), DataType::BigInt { length: None })],
2379                None,
2380            )
2381            .expect("schema setup");
2382
2383        let node = lineage_with_schema(
2384            "a",
2385            &expr,
2386            Some(&schema),
2387            Some(DialectType::BigQuery),
2388            false,
2389        )
2390        .expect("lineage_with_schema should handle dotted schema.table names");
2391
2392        assert_eq!(node.name, "a");
2393    }
2394
2395    #[test]
2396    fn test_lineage_with_schema_none_matches_lineage() {
2397        let expr = parse("SELECT a FROM t");
2398        let baseline = lineage("a", &expr, None, false).expect("lineage baseline");
2399        let with_none =
2400            lineage_with_schema("a", &expr, None, None, false).expect("lineage_with_schema");
2401
2402        assert_eq!(with_none.name, baseline.name);
2403        assert_eq!(with_none.downstream_names(), baseline.downstream_names());
2404    }
2405
2406    #[test]
2407    fn test_lineage_with_schema_bigquery_mixed_case_column_names_issue_60() {
2408        let dialect = Dialect::get(DialectType::BigQuery);
2409        let expr = dialect
2410            .parse("SELECT Name AS name FROM teams")
2411            .unwrap()
2412            .into_iter()
2413            .next()
2414            .expect("expected one expression");
2415
2416        let mut schema = MappingSchema::with_dialect(DialectType::BigQuery);
2417        schema
2418            .add_table(
2419                "teams",
2420                &[("Name".into(), DataType::String { length: None })],
2421                None,
2422            )
2423            .expect("schema setup");
2424
2425        let node = lineage_with_schema(
2426            "name",
2427            &expr,
2428            Some(&schema),
2429            Some(DialectType::BigQuery),
2430            false,
2431        )
2432        .expect("lineage_with_schema should resolve mixed-case BigQuery columns");
2433
2434        let names = node.downstream_names();
2435        assert!(
2436            names.iter().any(|n| n == "teams.Name"),
2437            "Expected teams.Name in downstream, got: {:?}",
2438            names
2439        );
2440    }
2441
2442    #[test]
2443    fn test_lineage_bigquery_mixed_case_alias_lookup() {
2444        let dialect = Dialect::get(DialectType::BigQuery);
2445        let expr = dialect
2446            .parse("SELECT Name AS Name FROM teams")
2447            .unwrap()
2448            .into_iter()
2449            .next()
2450            .expect("expected one expression");
2451
2452        let node = lineage("name", &expr, Some(DialectType::BigQuery), false)
2453            .expect("lineage should resolve mixed-case aliases in BigQuery");
2454
2455        assert_eq!(node.name, "name");
2456    }
2457
2458    #[test]
2459    fn test_lineage_with_schema_snowflake_datediff_date_part_issue_61() {
2460        let expr = parse_one(
2461            "SELECT DATEDIFF(day, date_utc, CURRENT_DATE()) AS recency FROM fact.some_daily_metrics",
2462            DialectType::Snowflake,
2463        )
2464        .expect("parse");
2465
2466        let mut schema = MappingSchema::with_dialect(DialectType::Snowflake);
2467        schema
2468            .add_table(
2469                "fact.some_daily_metrics",
2470                &[("date_utc".to_string(), DataType::Date)],
2471                None,
2472            )
2473            .expect("schema setup");
2474
2475        let node = lineage_with_schema(
2476            "recency",
2477            &expr,
2478            Some(&schema),
2479            Some(DialectType::Snowflake),
2480            false,
2481        )
2482        .expect("lineage_with_schema should not treat date part as a column");
2483
2484        let names = node.downstream_names();
2485        assert!(
2486            names.iter().any(|n| n == "some_daily_metrics.date_utc"),
2487            "Expected some_daily_metrics.date_utc in downstream, got: {:?}",
2488            names
2489        );
2490        assert!(
2491            !names.iter().any(|n| n.ends_with(".day") || n == "day"),
2492            "Did not expect date part to appear as lineage column, got: {:?}",
2493            names
2494        );
2495    }
2496
2497    #[test]
2498    fn test_snowflake_datediff_parses_to_typed_ast() {
2499        let expr = parse_one(
2500            "SELECT DATEDIFF(day, date_utc, CURRENT_DATE()) AS recency FROM fact.some_daily_metrics",
2501            DialectType::Snowflake,
2502        )
2503        .expect("parse");
2504
2505        match expr {
2506            Expression::Select(select) => match &select.expressions[0] {
2507                Expression::Alias(alias) => match &alias.this {
2508                    Expression::DateDiff(f) => {
2509                        assert_eq!(f.unit, Some(crate::expressions::IntervalUnit::Day));
2510                    }
2511                    other => panic!("expected DateDiff, got {other:?}"),
2512                },
2513                other => panic!("expected Alias, got {other:?}"),
2514            },
2515            other => panic!("expected Select, got {other:?}"),
2516        }
2517    }
2518
2519    #[test]
2520    fn test_lineage_with_schema_snowflake_dateadd_date_part_issue_followup() {
2521        let expr = parse_one(
2522            "SELECT DATEADD(day, 1, date_utc) AS next_day FROM fact.some_daily_metrics",
2523            DialectType::Snowflake,
2524        )
2525        .expect("parse");
2526
2527        let mut schema = MappingSchema::with_dialect(DialectType::Snowflake);
2528        schema
2529            .add_table(
2530                "fact.some_daily_metrics",
2531                &[("date_utc".to_string(), DataType::Date)],
2532                None,
2533            )
2534            .expect("schema setup");
2535
2536        let node = lineage_with_schema(
2537            "next_day",
2538            &expr,
2539            Some(&schema),
2540            Some(DialectType::Snowflake),
2541            false,
2542        )
2543        .expect("lineage_with_schema should not treat DATEADD date part as a column");
2544
2545        let names = node.downstream_names();
2546        assert!(
2547            names.iter().any(|n| n == "some_daily_metrics.date_utc"),
2548            "Expected some_daily_metrics.date_utc in downstream, got: {:?}",
2549            names
2550        );
2551        assert!(
2552            !names.iter().any(|n| n.ends_with(".day") || n == "day"),
2553            "Did not expect date part to appear as lineage column, got: {:?}",
2554            names
2555        );
2556    }
2557
2558    #[test]
2559    fn test_lineage_with_schema_snowflake_date_part_identifier_issue_followup() {
2560        let expr = parse_one(
2561            "SELECT DATE_PART(day, date_utc) AS day_part FROM fact.some_daily_metrics",
2562            DialectType::Snowflake,
2563        )
2564        .expect("parse");
2565
2566        let mut schema = MappingSchema::with_dialect(DialectType::Snowflake);
2567        schema
2568            .add_table(
2569                "fact.some_daily_metrics",
2570                &[("date_utc".to_string(), DataType::Date)],
2571                None,
2572            )
2573            .expect("schema setup");
2574
2575        let node = lineage_with_schema(
2576            "day_part",
2577            &expr,
2578            Some(&schema),
2579            Some(DialectType::Snowflake),
2580            false,
2581        )
2582        .expect("lineage_with_schema should not treat DATE_PART identifier as a column");
2583
2584        let names = node.downstream_names();
2585        assert!(
2586            names.iter().any(|n| n == "some_daily_metrics.date_utc"),
2587            "Expected some_daily_metrics.date_utc in downstream, got: {:?}",
2588            names
2589        );
2590        assert!(
2591            !names.iter().any(|n| n.ends_with(".day") || n == "day"),
2592            "Did not expect date part to appear as lineage column, got: {:?}",
2593            names
2594        );
2595    }
2596
2597    #[test]
2598    fn test_lineage_with_schema_snowflake_date_part_string_literal_control() {
2599        let expr = parse_one(
2600            "SELECT DATE_PART('day', date_utc) AS day_part FROM fact.some_daily_metrics",
2601            DialectType::Snowflake,
2602        )
2603        .expect("parse");
2604
2605        let mut schema = MappingSchema::with_dialect(DialectType::Snowflake);
2606        schema
2607            .add_table(
2608                "fact.some_daily_metrics",
2609                &[("date_utc".to_string(), DataType::Date)],
2610                None,
2611            )
2612            .expect("schema setup");
2613
2614        let node = lineage_with_schema(
2615            "day_part",
2616            &expr,
2617            Some(&schema),
2618            Some(DialectType::Snowflake),
2619            false,
2620        )
2621        .expect("quoted DATE_PART should continue to work");
2622
2623        let names = node.downstream_names();
2624        assert!(
2625            names.iter().any(|n| n == "some_daily_metrics.date_utc"),
2626            "Expected some_daily_metrics.date_utc in downstream, got: {:?}",
2627            names
2628        );
2629    }
2630
2631    #[test]
2632    fn test_snowflake_dateadd_date_part_identifier_stays_generic_function() {
2633        let expr = parse_one(
2634            "SELECT DATEADD(day, 1, date_utc) AS next_day FROM fact.some_daily_metrics",
2635            DialectType::Snowflake,
2636        )
2637        .expect("parse");
2638
2639        match expr {
2640            Expression::Select(select) => match &select.expressions[0] {
2641                Expression::Alias(alias) => match &alias.this {
2642                    Expression::Function(f) => {
2643                        assert_eq!(f.name.to_uppercase(), "DATEADD");
2644                        assert!(matches!(&f.args[0], Expression::Var(v) if v.this == "day"));
2645                    }
2646                    other => panic!("expected generic DATEADD function, got {other:?}"),
2647                },
2648                other => panic!("expected Alias, got {other:?}"),
2649            },
2650            other => panic!("expected Select, got {other:?}"),
2651        }
2652    }
2653
2654    #[test]
2655    fn test_snowflake_date_part_identifier_stays_generic_function_with_var_arg() {
2656        let expr = parse_one(
2657            "SELECT DATE_PART(day, date_utc) AS day_part FROM fact.some_daily_metrics",
2658            DialectType::Snowflake,
2659        )
2660        .expect("parse");
2661
2662        match expr {
2663            Expression::Select(select) => match &select.expressions[0] {
2664                Expression::Alias(alias) => match &alias.this {
2665                    Expression::Function(f) => {
2666                        assert_eq!(f.name.to_uppercase(), "DATE_PART");
2667                        assert!(matches!(&f.args[0], Expression::Var(v) if v.this == "day"));
2668                    }
2669                    other => panic!("expected generic DATE_PART function, got {other:?}"),
2670                },
2671                other => panic!("expected Alias, got {other:?}"),
2672            },
2673            other => panic!("expected Select, got {other:?}"),
2674        }
2675    }
2676
2677    #[test]
2678    fn test_snowflake_date_part_string_literal_stays_generic_function() {
2679        let expr = parse_one(
2680            "SELECT DATE_PART('day', date_utc) AS day_part FROM fact.some_daily_metrics",
2681            DialectType::Snowflake,
2682        )
2683        .expect("parse");
2684
2685        match expr {
2686            Expression::Select(select) => match &select.expressions[0] {
2687                Expression::Alias(alias) => match &alias.this {
2688                    Expression::Function(f) => {
2689                        assert_eq!(f.name.to_uppercase(), "DATE_PART");
2690                    }
2691                    other => panic!("expected generic DATE_PART function, got {other:?}"),
2692                },
2693                other => panic!("expected Alias, got {other:?}"),
2694            },
2695            other => panic!("expected Select, got {other:?}"),
2696        }
2697    }
2698
2699    #[test]
2700    fn test_lineage_join() {
2701        let expr = parse("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
2702
2703        let node_a = lineage("a", &expr, None, false).unwrap();
2704        let names_a = node_a.downstream_names();
2705        assert!(
2706            names_a.iter().any(|n| n == "t.a"),
2707            "Expected t.a, got: {:?}",
2708            names_a
2709        );
2710
2711        let node_b = lineage("b", &expr, None, false).unwrap();
2712        let names_b = node_b.downstream_names();
2713        assert!(
2714            names_b.iter().any(|n| n == "s.b"),
2715            "Expected s.b, got: {:?}",
2716            names_b
2717        );
2718    }
2719
2720    #[test]
2721    fn test_lineage_alias_leaf_has_resolved_source_name() {
2722        let expr = parse("SELECT t1.col1 FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id");
2723        let node = lineage("col1", &expr, None, false).unwrap();
2724
2725        // Keep alias in the display lineage edge.
2726        let names = node.downstream_names();
2727        assert!(
2728            names.iter().any(|n| n == "t1.col1"),
2729            "Expected aliased column edge t1.col1, got: {:?}",
2730            names
2731        );
2732
2733        // Leaf should expose the resolved base table for consumers.
2734        let leaf = node
2735            .downstream
2736            .iter()
2737            .find(|n| n.name == "t1.col1")
2738            .expect("Expected t1.col1 leaf");
2739        assert_eq!(leaf.source_name, "table1");
2740        match &leaf.source {
2741            Expression::Table(table) => assert_eq!(table.name.name, "table1"),
2742            _ => panic!("Expected leaf source to be a table expression"),
2743        }
2744    }
2745
2746    #[test]
2747    fn test_lineage_derived_table() {
2748        let expr = parse("SELECT x.a FROM (SELECT a FROM t) AS x");
2749        let node = lineage("a", &expr, None, false).unwrap();
2750
2751        assert_eq!(node.name, "a");
2752        // Should trace through the derived table to t.a
2753        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2754        assert!(
2755            all_names.iter().any(|n| n == "t.a"),
2756            "Expected to trace through derived table to t.a, got: {:?}",
2757            all_names
2758        );
2759    }
2760
2761    #[test]
2762    fn test_lineage_cte() {
2763        let expr = parse("WITH cte AS (SELECT a FROM t) SELECT a FROM cte");
2764        let node = lineage("a", &expr, None, false).unwrap();
2765
2766        assert_eq!(node.name, "a");
2767        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2768        assert!(
2769            all_names.iter().any(|n| n == "t.a"),
2770            "Expected to trace through CTE to t.a, got: {:?}",
2771            all_names
2772        );
2773    }
2774
2775    #[test]
2776    fn test_lineage_union() {
2777        let expr = parse("SELECT a FROM t1 UNION SELECT a FROM t2");
2778        let node = lineage("a", &expr, None, false).unwrap();
2779
2780        assert_eq!(node.name, "a");
2781        // Should have 2 downstream branches
2782        assert_eq!(
2783            node.downstream.len(),
2784            2,
2785            "Expected 2 branches for UNION, got {}",
2786            node.downstream.len()
2787        );
2788    }
2789
2790    #[test]
2791    fn test_lineage_cte_union() {
2792        let expr = parse("WITH cte AS (SELECT a FROM t1 UNION SELECT a FROM t2) SELECT a FROM cte");
2793        let node = lineage("a", &expr, None, false).unwrap();
2794
2795        // Should trace through CTE into both UNION branches
2796        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2797        assert!(
2798            all_names.len() >= 3,
2799            "Expected at least 3 nodes for CTE with UNION, got: {:?}",
2800            all_names
2801        );
2802    }
2803
2804    #[test]
2805    fn test_lineage_star() {
2806        let expr = parse("SELECT * FROM t");
2807        let node = lineage("*", &expr, None, false).unwrap();
2808
2809        assert_eq!(node.name, "*");
2810        // Should have downstream for table t
2811        assert!(
2812            !node.downstream.is_empty(),
2813            "Star should produce downstream nodes"
2814        );
2815    }
2816
2817    #[test]
2818    fn test_lineage_subquery_in_select() {
2819        let expr = parse("SELECT (SELECT MAX(b) FROM s) AS x FROM t");
2820        let node = lineage("x", &expr, None, false).unwrap();
2821
2822        assert_eq!(node.name, "x");
2823        // Should have traced into the scalar subquery
2824        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2825        assert!(
2826            all_names.len() >= 2,
2827            "Expected tracing into scalar subquery, got: {:?}",
2828            all_names
2829        );
2830    }
2831
2832    #[test]
2833    fn test_lineage_multiple_columns() {
2834        let expr = parse("SELECT a, b FROM t");
2835
2836        let node_a = lineage("a", &expr, None, false).unwrap();
2837        let node_b = lineage("b", &expr, None, false).unwrap();
2838
2839        assert_eq!(node_a.name, "a");
2840        assert_eq!(node_b.name, "b");
2841
2842        // Each should trace independently
2843        let names_a = node_a.downstream_names();
2844        let names_b = node_b.downstream_names();
2845        assert!(names_a.iter().any(|n| n == "t.a"));
2846        assert!(names_b.iter().any(|n| n == "t.b"));
2847    }
2848
2849    #[test]
2850    fn test_get_source_tables() {
2851        let expr = parse("SELECT t.a, s.b FROM t JOIN s ON t.id = s.id");
2852        let node = lineage("a", &expr, None, false).unwrap();
2853
2854        let tables = get_source_tables(&node);
2855        assert!(
2856            tables.contains("t"),
2857            "Expected source table 't', got: {:?}",
2858            tables
2859        );
2860    }
2861
2862    #[test]
2863    fn test_lineage_column_not_found() {
2864        let expr = parse("SELECT a FROM t");
2865        let result = lineage("nonexistent", &expr, None, false);
2866        assert!(result.is_err());
2867    }
2868
2869    #[test]
2870    fn test_lineage_nested_cte() {
2871        let expr = parse(
2872            "WITH cte1 AS (SELECT a FROM t), \
2873             cte2 AS (SELECT a FROM cte1) \
2874             SELECT a FROM cte2",
2875        );
2876        let node = lineage("a", &expr, None, false).unwrap();
2877
2878        // Should trace through cte2 → cte1 → t
2879        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2880        assert!(
2881            all_names.len() >= 3,
2882            "Expected to trace through nested CTEs, got: {:?}",
2883            all_names
2884        );
2885    }
2886
2887    #[test]
2888    fn test_trim_selects_true() {
2889        let expr = parse("SELECT a, b, c FROM t");
2890        let node = lineage("a", &expr, None, true).unwrap();
2891
2892        // The source should be trimmed to only include 'a'
2893        if let Expression::Select(select) = &node.source {
2894            assert_eq!(
2895                select.expressions.len(),
2896                1,
2897                "Trimmed source should have 1 expression, got {}",
2898                select.expressions.len()
2899            );
2900        } else {
2901            panic!("Expected Select source");
2902        }
2903    }
2904
2905    #[test]
2906    fn test_trim_selects_false() {
2907        let expr = parse("SELECT a, b, c FROM t");
2908        let node = lineage("a", &expr, None, false).unwrap();
2909
2910        // The source should keep all columns
2911        if let Expression::Select(select) = &node.source {
2912            assert_eq!(
2913                select.expressions.len(),
2914                3,
2915                "Untrimmed source should have 3 expressions"
2916            );
2917        } else {
2918            panic!("Expected Select source");
2919        }
2920    }
2921
2922    #[test]
2923    fn test_lineage_expression_in_select() {
2924        let expr = parse("SELECT a + b AS c FROM t");
2925        let node = lineage("c", &expr, None, false).unwrap();
2926
2927        // Should trace to both a and b from t
2928        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
2929        assert!(
2930            all_names.len() >= 3,
2931            "Expected to trace a + b to both columns, got: {:?}",
2932            all_names
2933        );
2934    }
2935
2936    #[test]
2937    fn test_set_operation_by_index() {
2938        let expr = parse("SELECT a FROM t1 UNION SELECT b FROM t2");
2939
2940        // Trace column "a" which is at index 0
2941        let node = lineage("a", &expr, None, false).unwrap();
2942
2943        // UNION branches should be traced by index
2944        assert_eq!(node.downstream.len(), 2);
2945    }
2946
2947    // --- Tests for column lineage inside function calls (issue #18) ---
2948
2949    fn print_node(node: &LineageNode, indent: usize) {
2950        let pad = "  ".repeat(indent);
2951        println!(
2952            "{pad}name={:?} source_name={:?}",
2953            node.name, node.source_name
2954        );
2955        for child in &node.downstream {
2956            print_node(child, indent + 1);
2957        }
2958    }
2959
2960    #[test]
2961    fn test_issue18_repro() {
2962        // Exact scenario from the issue
2963        let query = "SELECT UPPER(name) as upper_name FROM users";
2964        println!("Query: {query}\n");
2965
2966        let dialect = crate::dialects::Dialect::get(DialectType::BigQuery);
2967        let exprs = dialect.parse(query).unwrap();
2968        let expr = &exprs[0];
2969
2970        let node = lineage("upper_name", expr, Some(DialectType::BigQuery), false).unwrap();
2971        println!("lineage(\"upper_name\"):");
2972        print_node(&node, 1);
2973
2974        let names = node.downstream_names();
2975        assert!(
2976            names.iter().any(|n| n == "users.name"),
2977            "Expected users.name in downstream, got: {:?}",
2978            names
2979        );
2980    }
2981
2982    #[test]
2983    fn test_lineage_upper_function() {
2984        let expr = parse("SELECT UPPER(name) AS upper_name FROM users");
2985        let node = lineage("upper_name", &expr, None, false).unwrap();
2986
2987        let names = node.downstream_names();
2988        assert!(
2989            names.iter().any(|n| n == "users.name"),
2990            "Expected users.name in downstream, got: {:?}",
2991            names
2992        );
2993    }
2994
2995    #[test]
2996    fn test_lineage_round_function() {
2997        let expr = parse("SELECT ROUND(price, 2) AS rounded FROM products");
2998        let node = lineage("rounded", &expr, None, false).unwrap();
2999
3000        let names = node.downstream_names();
3001        assert!(
3002            names.iter().any(|n| n == "products.price"),
3003            "Expected products.price in downstream, got: {:?}",
3004            names
3005        );
3006    }
3007
3008    #[test]
3009    fn test_lineage_coalesce_function() {
3010        let expr = parse("SELECT COALESCE(a, b) AS val FROM t");
3011        let node = lineage("val", &expr, None, false).unwrap();
3012
3013        let names = node.downstream_names();
3014        assert!(
3015            names.iter().any(|n| n == "t.a"),
3016            "Expected t.a in downstream, got: {:?}",
3017            names
3018        );
3019        assert!(
3020            names.iter().any(|n| n == "t.b"),
3021            "Expected t.b in downstream, got: {:?}",
3022            names
3023        );
3024    }
3025
3026    #[test]
3027    fn test_lineage_count_function() {
3028        let expr = parse("SELECT COUNT(id) AS cnt FROM t");
3029        let node = lineage("cnt", &expr, None, false).unwrap();
3030
3031        let names = node.downstream_names();
3032        assert!(
3033            names.iter().any(|n| n == "t.id"),
3034            "Expected t.id in downstream, got: {:?}",
3035            names
3036        );
3037    }
3038
3039    #[test]
3040    fn test_lineage_sum_function() {
3041        let expr = parse("SELECT SUM(amount) AS total FROM t");
3042        let node = lineage("total", &expr, None, false).unwrap();
3043
3044        let names = node.downstream_names();
3045        assert!(
3046            names.iter().any(|n| n == "t.amount"),
3047            "Expected t.amount in downstream, got: {:?}",
3048            names
3049        );
3050    }
3051
3052    #[test]
3053    fn test_lineage_case_with_nested_functions() {
3054        let expr =
3055            parse("SELECT CASE WHEN x > 0 THEN UPPER(name) ELSE LOWER(name) END AS result FROM t");
3056        let node = lineage("result", &expr, None, false).unwrap();
3057
3058        let names = node.downstream_names();
3059        assert!(
3060            names.iter().any(|n| n == "t.x"),
3061            "Expected t.x in downstream, got: {:?}",
3062            names
3063        );
3064        assert!(
3065            names.iter().any(|n| n == "t.name"),
3066            "Expected t.name in downstream, got: {:?}",
3067            names
3068        );
3069    }
3070
3071    #[test]
3072    fn test_lineage_substring_function() {
3073        let expr = parse("SELECT SUBSTRING(name, 1, 3) AS short FROM t");
3074        let node = lineage("short", &expr, None, false).unwrap();
3075
3076        let names = node.downstream_names();
3077        assert!(
3078            names.iter().any(|n| n == "t.name"),
3079            "Expected t.name in downstream, got: {:?}",
3080            names
3081        );
3082    }
3083
3084    // --- CTE + SELECT * tests (ported from sqlglot test_lineage.py) ---
3085
3086    #[test]
3087    fn test_lineage_cte_select_star() {
3088        // Ported from sqlglot: test_lineage_source_with_star
3089        // WITH y AS (SELECT * FROM x) SELECT a FROM y
3090        // After star expansion: SELECT y.a AS a FROM y
3091        let expr = parse("WITH y AS (SELECT * FROM x) SELECT a FROM y");
3092        let node = lineage("a", &expr, None, false).unwrap();
3093
3094        assert_eq!(node.name, "a");
3095        // Should successfully resolve column 'a' through the CTE
3096        // (previously failed with "Cannot find column 'a' in query")
3097        assert!(
3098            !node.downstream.is_empty(),
3099            "Expected downstream nodes tracing through CTE, got none"
3100        );
3101    }
3102
3103    #[test]
3104    fn test_lineage_cte_select_star_renamed_column() {
3105        // dbt standard pattern: CTE with column rename + outer SELECT *
3106        // This is the primary use case for dbt projects (jaffle-shop etc.)
3107        let expr =
3108            parse("WITH renamed AS (SELECT id AS customer_id FROM source) SELECT * FROM renamed");
3109        let node = lineage("customer_id", &expr, None, false).unwrap();
3110
3111        assert_eq!(node.name, "customer_id");
3112        // Should trace customer_id → renamed CTE → source.id
3113        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3114        assert!(
3115            all_names.len() >= 2,
3116            "Expected at least 2 nodes (customer_id → source), got: {:?}",
3117            all_names
3118        );
3119    }
3120
3121    #[test]
3122    fn test_lineage_cte_select_star_multiple_columns() {
3123        // CTE exposes multiple columns, outer SELECT * should resolve each
3124        let expr = parse("WITH cte AS (SELECT a, b, c FROM t) SELECT * FROM cte");
3125
3126        for col in &["a", "b", "c"] {
3127            let node = lineage(col, &expr, None, false).unwrap();
3128            assert_eq!(node.name, *col);
3129            // Verify lineage resolves without error (star expanded to explicit columns)
3130            let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3131            assert!(
3132                all_names.len() >= 2,
3133                "Expected at least 2 nodes for column {}, got: {:?}",
3134                col,
3135                all_names
3136            );
3137        }
3138    }
3139
3140    #[test]
3141    fn test_lineage_nested_cte_select_star() {
3142        // Nested CTE star expansion: cte2 references cte1 via SELECT *
3143        let expr = parse(
3144            "WITH cte1 AS (SELECT a FROM t), \
3145             cte2 AS (SELECT * FROM cte1) \
3146             SELECT * FROM cte2",
3147        );
3148        let node = lineage("a", &expr, None, false).unwrap();
3149
3150        assert_eq!(node.name, "a");
3151        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3152        assert!(
3153            all_names.len() >= 3,
3154            "Expected at least 3 nodes (a → cte2 → cte1 → t.a), got: {:?}",
3155            all_names
3156        );
3157    }
3158
3159    #[test]
3160    fn test_lineage_three_level_nested_cte_star() {
3161        // Three-level nested CTE: cte3 → cte2 → cte1 → t
3162        let expr = parse(
3163            "WITH cte1 AS (SELECT x FROM t), \
3164             cte2 AS (SELECT * FROM cte1), \
3165             cte3 AS (SELECT * FROM cte2) \
3166             SELECT * FROM cte3",
3167        );
3168        let node = lineage("x", &expr, None, false).unwrap();
3169
3170        assert_eq!(node.name, "x");
3171        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3172        assert!(
3173            all_names.len() >= 4,
3174            "Expected at least 4 nodes through 3-level CTE chain, got: {:?}",
3175            all_names
3176        );
3177    }
3178
3179    #[test]
3180    fn test_lineage_cte_union_star() {
3181        // CTE with UNION body, outer SELECT * should resolve from left branch
3182        let expr = parse(
3183            "WITH cte AS (SELECT a, b FROM t1 UNION ALL SELECT a, b FROM t2) \
3184             SELECT * FROM cte",
3185        );
3186        let node = lineage("a", &expr, None, false).unwrap();
3187
3188        assert_eq!(node.name, "a");
3189        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3190        assert!(
3191            all_names.len() >= 2,
3192            "Expected at least 2 nodes for CTE union star, got: {:?}",
3193            all_names
3194        );
3195    }
3196
3197    #[test]
3198    fn test_lineage_cte_star_unknown_table() {
3199        // When CTE references an unknown table, star expansion is skipped gracefully
3200        // and lineage falls back to normal resolution (which may fail)
3201        let expr = parse(
3202            "WITH cte AS (SELECT * FROM unknown_table) \
3203             SELECT * FROM cte",
3204        );
3205        // This should not panic — it may succeed or fail depending on resolution,
3206        // but should not crash
3207        let _result = lineage("x", &expr, None, false);
3208    }
3209
3210    #[test]
3211    fn test_lineage_cte_explicit_columns() {
3212        // CTE with explicit column list: cte(x, y) AS (SELECT a, b FROM t)
3213        let expr = parse(
3214            "WITH cte(x, y) AS (SELECT a, b FROM t) \
3215             SELECT * FROM cte",
3216        );
3217        let node = lineage("x", &expr, None, false).unwrap();
3218        assert_eq!(node.name, "x");
3219    }
3220
3221    #[test]
3222    fn test_lineage_cte_qualified_star() {
3223        // Qualified star: SELECT cte.* FROM cte
3224        let expr = parse(
3225            "WITH cte AS (SELECT a, b FROM t) \
3226             SELECT cte.* FROM cte",
3227        );
3228        for col in &["a", "b"] {
3229            let node = lineage(col, &expr, None, false).unwrap();
3230            assert_eq!(node.name, *col);
3231            let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3232            assert!(
3233                all_names.len() >= 2,
3234                "Expected at least 2 nodes for qualified star column {}, got: {:?}",
3235                col,
3236                all_names
3237            );
3238        }
3239    }
3240
3241    #[test]
3242    fn test_lineage_subquery_select_star() {
3243        // Ported from sqlglot: test_select_star
3244        // SELECT x FROM (SELECT * FROM table_a)
3245        let expr = parse("SELECT x FROM (SELECT * FROM table_a)");
3246        let node = lineage("x", &expr, None, false).unwrap();
3247
3248        assert_eq!(node.name, "x");
3249        assert!(
3250            !node.downstream.is_empty(),
3251            "Expected downstream nodes for subquery with SELECT *, got none"
3252        );
3253    }
3254
3255    #[test]
3256    fn test_lineage_cte_star_with_schema_external_table() {
3257        // CTE references an external table via SELECT * — schema enables expansion
3258        let sql = r#"WITH orders AS (SELECT * FROM stg_orders)
3259SELECT * FROM orders"#;
3260        let expr = parse(sql);
3261
3262        let mut schema = MappingSchema::new();
3263        let cols = vec![
3264            ("order_id".to_string(), DataType::Unknown),
3265            ("customer_id".to_string(), DataType::Unknown),
3266            ("amount".to_string(), DataType::Unknown),
3267        ];
3268        schema.add_table("stg_orders", &cols, None).unwrap();
3269
3270        let node =
3271            lineage_with_schema("order_id", &expr, Some(&schema as &dyn Schema), None, false)
3272                .unwrap();
3273        assert_eq!(node.name, "order_id");
3274    }
3275
3276    #[test]
3277    fn test_lineage_cte_star_with_schema_three_part_name() {
3278        // CTE references an external table with fully-qualified 3-part name
3279        let sql = r#"WITH orders AS (SELECT * FROM "db"."schema"."stg_orders")
3280SELECT * FROM orders"#;
3281        let expr = parse(sql);
3282
3283        let mut schema = MappingSchema::new();
3284        let cols = vec![
3285            ("order_id".to_string(), DataType::Unknown),
3286            ("customer_id".to_string(), DataType::Unknown),
3287        ];
3288        schema
3289            .add_table("db.schema.stg_orders", &cols, None)
3290            .unwrap();
3291
3292        let node = lineage_with_schema(
3293            "customer_id",
3294            &expr,
3295            Some(&schema as &dyn Schema),
3296            None,
3297            false,
3298        )
3299        .unwrap();
3300        assert_eq!(node.name, "customer_id");
3301    }
3302
3303    #[test]
3304    fn test_lineage_cte_star_with_schema_nested() {
3305        // Nested CTEs: outer CTE references inner CTE with SELECT *,
3306        // inner CTE references external table with SELECT *
3307        let sql = r#"WITH
3308            raw AS (SELECT * FROM external_table),
3309            enriched AS (SELECT * FROM raw)
3310        SELECT * FROM enriched"#;
3311        let expr = parse(sql);
3312
3313        let mut schema = MappingSchema::new();
3314        let cols = vec![
3315            ("id".to_string(), DataType::Unknown),
3316            ("name".to_string(), DataType::Unknown),
3317        ];
3318        schema.add_table("external_table", &cols, None).unwrap();
3319
3320        let node =
3321            lineage_with_schema("name", &expr, Some(&schema as &dyn Schema), None, false).unwrap();
3322        assert_eq!(node.name, "name");
3323    }
3324
3325    #[test]
3326    fn test_lineage_cte_qualified_star_with_schema() {
3327        // CTE uses qualified star (orders.*) from a CTE whose columns
3328        // come from an external table via SELECT *
3329        let sql = r#"WITH
3330            orders AS (SELECT * FROM stg_orders),
3331            enriched AS (
3332                SELECT orders.*, 'extra' AS extra
3333                FROM orders
3334            )
3335        SELECT * FROM enriched"#;
3336        let expr = parse(sql);
3337
3338        let mut schema = MappingSchema::new();
3339        let cols = vec![
3340            ("order_id".to_string(), DataType::Unknown),
3341            ("total".to_string(), DataType::Unknown),
3342        ];
3343        schema.add_table("stg_orders", &cols, None).unwrap();
3344
3345        let node =
3346            lineage_with_schema("order_id", &expr, Some(&schema as &dyn Schema), None, false)
3347                .unwrap();
3348        assert_eq!(node.name, "order_id");
3349
3350        // Also verify the extra column works
3351        let extra =
3352            lineage_with_schema("extra", &expr, Some(&schema as &dyn Schema), None, false).unwrap();
3353        assert_eq!(extra.name, "extra");
3354    }
3355
3356    #[test]
3357    fn test_lineage_cte_star_without_schema_still_works() {
3358        // Without schema, CTE-to-CTE star expansion still works
3359        let sql = r#"WITH
3360            cte1 AS (SELECT id, name FROM raw_table),
3361            cte2 AS (SELECT * FROM cte1)
3362        SELECT * FROM cte2"#;
3363        let expr = parse(sql);
3364
3365        // No schema — should still resolve through CTE chain
3366        let node = lineage("id", &expr, None, false).unwrap();
3367        assert_eq!(node.name, "id");
3368    }
3369
3370    #[test]
3371    fn test_lineage_nested_cte_star_with_join_and_schema() {
3372        // Reproduces dbt pattern: CTE chain with qualified star and JOIN
3373        // base_orders -> with_payments (JOIN) -> final -> outer SELECT
3374        let sql = r#"WITH
3375base_orders AS (
3376    SELECT * FROM stg_orders
3377),
3378with_payments AS (
3379    SELECT
3380        base_orders.*,
3381        p.amount
3382    FROM base_orders
3383    LEFT JOIN stg_payments p ON base_orders.order_id = p.order_id
3384),
3385final_cte AS (
3386    SELECT * FROM with_payments
3387)
3388SELECT * FROM final_cte"#;
3389        let expr = parse(sql);
3390
3391        let mut schema = MappingSchema::new();
3392        let order_cols = vec![
3393            (
3394                "order_id".to_string(),
3395                crate::expressions::DataType::Unknown,
3396            ),
3397            (
3398                "customer_id".to_string(),
3399                crate::expressions::DataType::Unknown,
3400            ),
3401            ("status".to_string(), crate::expressions::DataType::Unknown),
3402        ];
3403        let pay_cols = vec![
3404            (
3405                "payment_id".to_string(),
3406                crate::expressions::DataType::Unknown,
3407            ),
3408            (
3409                "order_id".to_string(),
3410                crate::expressions::DataType::Unknown,
3411            ),
3412            ("amount".to_string(), crate::expressions::DataType::Unknown),
3413        ];
3414        schema.add_table("stg_orders", &order_cols, None).unwrap();
3415        schema.add_table("stg_payments", &pay_cols, None).unwrap();
3416
3417        // order_id should trace back to stg_orders
3418        let node =
3419            lineage_with_schema("order_id", &expr, Some(&schema as &dyn Schema), None, false)
3420                .unwrap();
3421        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3422
3423        // The leaf should be "stg_orders.order_id" (not just "order_id")
3424        let has_table_qualified = all_names
3425            .iter()
3426            .any(|n| n.contains('.') && n.contains("order_id"));
3427        assert!(
3428            has_table_qualified,
3429            "Expected table-qualified leaf like 'stg_orders.order_id', got: {:?}",
3430            all_names
3431        );
3432
3433        // amount should trace back to stg_payments
3434        let node = lineage_with_schema("amount", &expr, Some(&schema as &dyn Schema), None, false)
3435            .unwrap();
3436        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3437
3438        let has_table_qualified = all_names
3439            .iter()
3440            .any(|n| n.contains('.') && n.contains("amount"));
3441        assert!(
3442            has_table_qualified,
3443            "Expected table-qualified leaf like 'stg_payments.amount', got: {:?}",
3444            all_names
3445        );
3446    }
3447
3448    #[test]
3449    fn test_lineage_cte_alias_resolution() {
3450        // FROM cte_name AS alias pattern: alias should resolve through CTE to source table
3451        let sql = r#"WITH import_stg_items AS (
3452    SELECT item_id, name, status FROM stg_items
3453)
3454SELECT base.item_id, base.status
3455FROM import_stg_items AS base"#;
3456        let expr = parse(sql);
3457
3458        let node = lineage("item_id", &expr, None, false).unwrap();
3459        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3460        // Should trace through alias "base" → CTE "import_stg_items" → "stg_items.item_id"
3461        assert!(
3462            all_names.iter().any(|n| n == "stg_items.item_id"),
3463            "Expected leaf 'stg_items.item_id', got: {:?}",
3464            all_names
3465        );
3466    }
3467
3468    #[test]
3469    fn test_lineage_cte_alias_with_schema_and_star() {
3470        // CTE alias + SELECT * expansion: FROM cte AS alias with star in CTE body
3471        let sql = r#"WITH import_stg AS (
3472    SELECT * FROM stg_items
3473)
3474SELECT base.item_id, base.status
3475FROM import_stg AS base"#;
3476        let expr = parse(sql);
3477
3478        let mut schema = MappingSchema::new();
3479        schema
3480            .add_table(
3481                "stg_items",
3482                &[
3483                    ("item_id".to_string(), DataType::Unknown),
3484                    ("name".to_string(), DataType::Unknown),
3485                    ("status".to_string(), DataType::Unknown),
3486                ],
3487                None,
3488            )
3489            .unwrap();
3490
3491        let node = lineage_with_schema("item_id", &expr, Some(&schema as &dyn Schema), None, false)
3492            .unwrap();
3493        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3494        assert!(
3495            all_names.iter().any(|n| n == "stg_items.item_id"),
3496            "Expected leaf 'stg_items.item_id', got: {:?}",
3497            all_names
3498        );
3499    }
3500
3501    #[test]
3502    fn test_lineage_cte_alias_with_join() {
3503        // Multiple CTE aliases in a JOIN: each should resolve independently
3504        let sql = r#"WITH
3505    import_users AS (SELECT id, name FROM users),
3506    import_orders AS (SELECT id, user_id, amount FROM orders)
3507SELECT u.name, o.amount
3508FROM import_users AS u
3509LEFT JOIN import_orders AS o ON u.id = o.user_id"#;
3510        let expr = parse(sql);
3511
3512        let node = lineage("name", &expr, None, false).unwrap();
3513        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3514        assert!(
3515            all_names.iter().any(|n| n == "users.name"),
3516            "Expected leaf 'users.name', got: {:?}",
3517            all_names
3518        );
3519
3520        let node = lineage("amount", &expr, None, false).unwrap();
3521        let all_names: Vec<_> = node.walk().map(|n| n.name.clone()).collect();
3522        assert!(
3523            all_names.iter().any(|n| n == "orders.amount"),
3524            "Expected leaf 'orders.amount', got: {:?}",
3525            all_names
3526        );
3527    }
3528
3529    // -----------------------------------------------------------------------
3530    // Quoted CTE name tests — verifying SQL identifier case semantics
3531    // -----------------------------------------------------------------------
3532
3533    #[test]
3534    fn test_lineage_unquoted_cte_case_insensitive() {
3535        // Unquoted CTE names are case-insensitive (both normalized to lowercase).
3536        // MyCte and MYCTE should match.
3537        let expr = parse("WITH MyCte AS (SELECT id AS col FROM source) SELECT * FROM MYCTE");
3538        let node = lineage("col", &expr, None, false).unwrap();
3539        assert_eq!(node.name, "col");
3540        assert!(
3541            !node.downstream.is_empty(),
3542            "Unquoted CTE should resolve case-insensitively"
3543        );
3544    }
3545
3546    #[test]
3547    fn test_lineage_quoted_cte_case_preserved() {
3548        // Quoted CTE name preserves case. "MyCte" referenced as "MyCte" should match.
3549        let expr = parse(r#"WITH "MyCte" AS (SELECT id AS col FROM source) SELECT * FROM "MyCte""#);
3550        let node = lineage("col", &expr, None, false).unwrap();
3551        assert_eq!(node.name, "col");
3552        assert!(
3553            !node.downstream.is_empty(),
3554            "Quoted CTE with matching case should resolve"
3555        );
3556    }
3557
3558    #[test]
3559    fn test_lineage_quoted_cte_case_mismatch_no_expansion() {
3560        // Quoted CTE "MyCte" referenced as "mycte" — case mismatch.
3561        // sqlglot treats this as a table reference, not a CTE match.
3562        // Star expansion should NOT resolve through the CTE.
3563        let expr = parse(r#"WITH "MyCte" AS (SELECT id AS col FROM source) SELECT * FROM "mycte""#);
3564        // lineage("col", ...) should fail because "mycte" is treated as an external
3565        // table (not matching CTE "MyCte"), and SELECT * cannot be expanded.
3566        let result = lineage("col", &expr, None, false);
3567        assert!(
3568            result.is_err(),
3569            "Quoted CTE with case mismatch should not expand star: {:?}",
3570            result
3571        );
3572    }
3573
3574    #[test]
3575    fn test_lineage_mixed_quoted_unquoted_cte() {
3576        // Mix of unquoted and quoted CTEs in a nested chain.
3577        let expr = parse(
3578            r#"WITH unquoted AS (SELECT 1 AS a FROM t), "Quoted" AS (SELECT a FROM unquoted) SELECT * FROM "Quoted""#,
3579        );
3580        let node = lineage("a", &expr, None, false).unwrap();
3581        assert_eq!(node.name, "a");
3582        assert!(
3583            !node.downstream.is_empty(),
3584            "Mixed quoted/unquoted CTE chain should resolve"
3585        );
3586    }
3587
3588    // -----------------------------------------------------------------------
3589    // Known bugs: quoted CTE case sensitivity in scope/lineage tracing paths
3590    // -----------------------------------------------------------------------
3591    //
3592    // expand_cte_stars correctly handles quoted vs unquoted CTE names via
3593    // normalize_cte_name(). However, the scope system (scope.rs add_table_to_scope)
3594    // and the lineage tracing path (to_node_inner) use eq_ignore_ascii_case or
3595    // direct string comparison for CTE name matching, ignoring the quoted status.
3596    //
3597    // sqlglot's normalize_identifiers treats quoted identifiers as case-sensitive
3598    // and unquoted as case-insensitive. The scope system should do the same.
3599    //
3600    // Fixing these requires changes across scope.rs and lineage.rs CTE resolution,
3601    // which is broader than the star expansion scope of this PR.
3602
3603    #[test]
3604    fn test_lineage_quoted_cte_case_mismatch_non_star_known_bug() {
3605        // Known bug: scope.rs add_table_to_scope uses eq_ignore_ascii_case for
3606        // all identifiers including quoted ones, so quoted CTE "MyCte" referenced
3607        // as "mycte" incorrectly resolves to the CTE.
3608        //
3609        // Per SQL semantics (and sqlglot behavior), quoted identifiers are
3610        // case-sensitive: "mycte" should NOT match CTE "MyCte".
3611        //
3612        // This test asserts the CURRENT BUGGY behavior. When the bug is fixed,
3613        // this test should fail — update the assertion to match correct behavior:
3614        //   child.source_name should be "" (table ref), not "MyCte" (CTE ref).
3615        let expr = parse(r#"WITH "MyCte" AS (SELECT 1 AS col) SELECT col FROM "mycte""#);
3616        let node = lineage("col", &expr, None, false).unwrap();
3617        assert!(!node.downstream.is_empty());
3618        let child = &node.downstream[0];
3619        // BUG: "mycte" incorrectly resolves to CTE "MyCte"
3620        assert_eq!(
3621            child.source_name, "MyCte",
3622            "Known bug: quoted CTE case mismatch should NOT resolve, but currently does. \
3623             If this fails, the bug may be fixed — update to assert source_name != \"MyCte\""
3624        );
3625    }
3626
3627    #[test]
3628    fn test_lineage_quoted_cte_case_mismatch_qualified_col_known_bug() {
3629        // Known bug: same as above but with qualified column reference ("mycte".col).
3630        // scope.rs resolves "mycte" to CTE "MyCte" case-insensitively even for
3631        // quoted identifiers, so "mycte".col incorrectly traces through CTE "MyCte".
3632        //
3633        // This test asserts the CURRENT BUGGY behavior. When the bug is fixed,
3634        // this test should fail — update to assert source_name != "MyCte".
3635        let expr = parse(r#"WITH "MyCte" AS (SELECT 1 AS col) SELECT "mycte".col FROM "mycte""#);
3636        let node = lineage("col", &expr, None, false).unwrap();
3637        assert!(!node.downstream.is_empty());
3638        let child = &node.downstream[0];
3639        // BUG: "mycte".col incorrectly resolves through CTE "MyCte"
3640        assert_eq!(
3641            child.source_name, "MyCte",
3642            "Known bug: quoted CTE case mismatch should NOT resolve, but currently does. \
3643             If this fails, the bug may be fixed — update to assert source_name != \"MyCte\""
3644        );
3645    }
3646
3647    // --- Comment handling tests (ported from sqlglot test_lineage.py) ---
3648
3649    /// sqlglot: test_node_name_doesnt_contain_comment
3650    /// Comments in column expressions should not affect lineage resolution.
3651    /// NOTE: This test uses SELECT * from a derived table, which is a separate
3652    /// known limitation in polyglot-sql (star expansion in subqueries).
3653    #[test]
3654    #[ignore = "requires derived table star expansion (separate issue)"]
3655    fn test_node_name_doesnt_contain_comment() {
3656        let expr = parse("SELECT * FROM (SELECT x /* c */ FROM t1) AS t2");
3657        let node = lineage("x", &expr, None, false).unwrap();
3658
3659        assert_eq!(node.name, "x");
3660        assert!(!node.downstream.is_empty());
3661    }
3662
3663    /// A line comment between SELECT and the first column wraps the column
3664    /// in an Annotated node. Lineage must unwrap it to find the column name.
3665    /// Verify that commented and uncommented queries produce identical lineage.
3666    #[test]
3667    fn test_comment_before_first_column_in_cte() {
3668        let sql_with_comment = "with t as (select 1 as a) select\n  -- comment\n  a from t";
3669        let sql_without_comment = "with t as (select 1 as a) select a from t";
3670
3671        // Without comment — baseline
3672        let expr_ok = parse(sql_without_comment);
3673        let node_ok = lineage("a", &expr_ok, None, false).expect("without comment should succeed");
3674
3675        // With comment — should produce identical lineage
3676        let expr_comment = parse(sql_with_comment);
3677        let node_comment = lineage("a", &expr_comment, None, false)
3678            .expect("with comment before first column should succeed");
3679
3680        assert_eq!(node_ok.name, node_comment.name, "node names should match");
3681        assert_eq!(
3682            node_ok.downstream_names(),
3683            node_comment.downstream_names(),
3684            "downstream lineage should be identical with or without comment"
3685        );
3686    }
3687
3688    /// Block comment between SELECT and first column.
3689    #[test]
3690    fn test_block_comment_before_first_column() {
3691        let sql = "with t as (select 1 as a) select /* section */ a from t";
3692        let expr = parse(sql);
3693        let node = lineage("a", &expr, None, false)
3694            .expect("block comment before first column should succeed");
3695        assert_eq!(node.name, "a");
3696        assert!(
3697            !node.downstream.is_empty(),
3698            "should have downstream lineage"
3699        );
3700    }
3701
3702    /// Comment before first column should not affect second column resolution.
3703    #[test]
3704    fn test_comment_before_first_column_second_col_ok() {
3705        let sql = "with t as (select 1 as a, 2 as b) select\n  -- comment\n  a, b from t";
3706        let expr = parse(sql);
3707
3708        let node_a =
3709            lineage("a", &expr, None, false).expect("column a with comment should succeed");
3710        assert_eq!(node_a.name, "a");
3711
3712        let node_b =
3713            lineage("b", &expr, None, false).expect("column b with comment should succeed");
3714        assert_eq!(node_b.name, "b");
3715    }
3716
3717    /// Aliased column with preceding comment.
3718    #[test]
3719    fn test_comment_before_aliased_column() {
3720        let sql = "with t as (select 1 as x) select\n  -- renamed\n  x as y from t";
3721        let expr = parse(sql);
3722        let node =
3723            lineage("y", &expr, None, false).expect("aliased column with comment should succeed");
3724        assert_eq!(node.name, "y");
3725        assert!(
3726            !node.downstream.is_empty(),
3727            "aliased column should have downstream lineage"
3728        );
3729    }
3730}