diff --git a/crates/flowscope-core/src/analyzer/context.rs b/crates/flowscope-core/src/analyzer/context.rs index af61a889..523c9431 100644 --- a/crates/flowscope-core/src/analyzer/context.rs +++ b/crates/flowscope-core/src/analyzer/context.rs @@ -54,8 +54,14 @@ pub(crate) struct Scope { /// name (e.g., `"employees"`) and the fully-qualified canonical name /// (e.g., `"public.employees"`) are registered so that either form resolves. pub(crate) alias_instances: HashMap, - /// Subquery aliases in this scope + /// Subquery aliases in this scope, normalized as identifiers are folded pub(crate) subquery_aliases: HashSet, + /// Normalized bare name -> canonical name of the tables and CTEs this + /// scope's FROM reads without an alias, so `reviews.book_id` finds + /// `LAB.RAW.REVIEWS` in this scope before an enclosing scope's alias of the + /// same name. `None` marks a name two different relations of the scope + /// share: it resolves to neither, and the search goes no further out. + pub(crate) bare_tables: HashMap>, /// Scope-local output columns for subquery/CTE aliases materialized in this scope. /// These shadow statement-global CTE definitions when alias names are reused. pub(crate) subquery_columns: HashMap>, @@ -656,12 +662,29 @@ impl StatementContext { /// Resolve an alias to its relation instance (canonical name + node_id). /// /// Searches the scope stack from innermost to outermost scope. Returns `None` - /// if the alias is not registered as an instance in any scope. - pub(crate) fn resolve_alias_instance(&self, alias: &str) -> Option<&RelationInstance> { + /// if the alias is not registered as an instance in any scope. A scope that + /// reads a table without an alias under the bare name `normalized` (the + /// qualifier, normalized as the dialect folds identifiers), or defines the + /// name with no table behind it, answers before an enclosing scope's alias. + pub(crate) fn resolve_alias_instance( + &self, + alias: &str, + normalized: &str, + ) -> Option<&RelationInstance> { for scope in self.scope_stack.iter().rev() { if let Some(instance) = scope.alias_instances.get(alias) { return Some(instance); } + if let Some(known) = scope.bare_tables.get(normalized) { + return known.as_ref().and_then(|canonical| { + scope + .alias_instances + .get(&super::helpers::extract_simple_name(canonical)) + }); + } + if scope.subquery_aliases.contains(normalized) { + return None; + } } None } @@ -692,14 +715,43 @@ impl StatementContext { .count() } - /// Register a subquery alias in the current scope - pub(crate) fn register_subquery_alias_in_scope(&mut self, alias: String) { + /// Register a subquery alias in the current scope. + /// + /// The global set keeps the alias as written; the scope's is keyed by + /// `normalized`, the alias as the dialect folds identifiers, which is how + /// `resolve_table_alias` and `resolve_alias_instance` look a qualifier up. + pub(crate) fn register_subquery_alias_in_scope(&mut self, alias: String, normalized: String) { // Register globally - self.subquery_aliases.insert(alias.clone()); + self.subquery_aliases.insert(alias); // Also register in current scope if let Some(scope) = self.current_scope_mut() { - scope.subquery_aliases.insert(alias); + scope.subquery_aliases.insert(normalized); + } + } + + /// Register a table read without an alias under its bare name, so a + /// qualifier spelled that way resolves here and not to an enclosing alias. + pub(crate) fn register_bare_table_in_scope(&mut self, bare_name: String, canonical: String) { + if let Some(scope) = self.current_scope_mut() { + scope + .bare_tables + .entry(bare_name) + .and_modify(|known| { + if known.as_deref() != Some(canonical.as_str()) { + *known = None; + } + }) + .or_insert(Some(canonical)); + } + } + + /// Register a name the current scope defines but no table owns, such as a + /// lateral view's, so it shadows an enclosing alias of the same name. The + /// name is stored normalized, as the keys of `bare_tables` are. + pub(crate) fn register_opaque_name_in_scope(&mut self, name: String) { + if let Some(scope) = self.current_scope_mut() { + scope.subquery_aliases.insert(name); } } diff --git a/crates/flowscope-core/src/analyzer/query.rs b/crates/flowscope-core/src/analyzer/query.rs index d5595cc8..6b2d2c8c 100644 --- a/crates/flowscope-core/src/analyzer/query.rs +++ b/crates/flowscope-core/src/analyzer/query.rs @@ -792,11 +792,24 @@ impl<'a> Analyzer<'a> { ) -> Option { match qualifier { Some(q) => { + // Bare names are stored normalized, so `reviews` finds + // `LAB.RAW.REVIEWS` where the dialect folds to upper case. + let key = self.normalize_identifier(q); // Check scopes in reverse order (innermost first) for correct shadowing for scope in ctx.scope_stack.iter().rev() { if let Some(canonical) = scope.aliases.get(q) { return Some(canonical.clone()); } + // A table read without an alias is named by its bare name, + // which shadows an enclosing scope's alias of that name. + if let Some(known) = scope.bare_tables.get(&key) { + // `None`: two relations of the scope share the name. + return known.clone(); + } + // A name the scope defines with no table behind it. + if scope.subquery_aliases.contains(&key) { + return None; + } } // Fallback to global map (legacy/loose scoping) @@ -828,7 +841,8 @@ impl<'a> Analyzer<'a> { qualifier: &str, ) -> Option> { // Try instance-aware lookup first - if let Some(instance) = ctx.resolve_alias_instance(qualifier) { + let key = self.normalize_identifier(qualifier); + if let Some(instance) = ctx.resolve_alias_instance(qualifier, &key) { return Some(instance.node_id.clone()); } // Fallback: resolve alias to canonical, then look up in table_node_ids diff --git a/crates/flowscope-core/src/analyzer/visitor.rs b/crates/flowscope-core/src/analyzer/visitor.rs index 7e060a64..f2755630 100644 --- a/crates/flowscope-core/src/analyzer/visitor.rs +++ b/crates/flowscope-core/src/analyzer/visitor.rs @@ -285,6 +285,13 @@ impl<'a, 'b> LineageVisitor<'a, 'b> { .add_source_table(self.ctx, table_name, self.target_node.as_deref(), None) } + /// Registers the alias of a relation no table owns (a table function, an + /// UNNEST, a PIVOT) in the current scope, keyed as qualifiers are looked up. + fn register_subquery_alias(&mut self, alias: String) { + let normalized = self.analyzer.normalize_identifier(&alias); + self.ctx.register_subquery_alias_in_scope(alias, normalized); + } + pub fn add_source_table_with_alias( &mut self, table_name: &str, @@ -487,8 +494,7 @@ impl<'a, 'b> LineageVisitor<'a, 'b> { let alias_name = alias.map_or_else(|| name.to_string(), |a| a.name.to_string()); // What is read through the alias belongs to no table, so it stays out // of the implied schema, as a derived table's columns do. - self.ctx - .register_subquery_alias_in_scope(alias_name.clone()); + self.register_subquery_alias(alias_name.clone()); // At table level the input is a column of a relation already in the // FROM clause: a FLATTEN node would have nothing to connect to. if !self.analyzer.column_lineage_enabled { @@ -799,6 +805,14 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { for table_with_joins in &select.from { self.visit_table_with_joins(table_with_joins); } + // A lateral view names a relation of this select that no table owns: + // its name must not resolve to an enclosing query's alias. + for lateral_view in &select.lateral_views { + let name = self + .analyzer + .normalize_identifier(&lateral_view.lateral_view_name.to_string()); + self.ctx.register_opaque_name_in_scope(name); + } if self.analyzer.column_lineage_enabled { let sink_node = self.ctx.sink_node_id().map(|node_id| node_id.to_string()); let target_node = self.target_node.clone().or(sink_node); @@ -837,9 +851,23 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { let table_name = name.to_string(); let alias_str = alias.as_ref().map(|a| a.name.to_string()); let canonical = self.add_source_table_with_alias(&table_name, alias_str.as_deref()); - if let (Some(a), Some(canonical_name)) = (&alias_str, &canonical) { - self.ctx - .register_alias_in_scope(a.clone(), canonical_name.clone()); + match (&alias_str, &canonical) { + (Some(a), Some(canonical_name)) => { + self.ctx + .register_alias_in_scope(a.clone(), canonical_name.clone()); + } + // A CTE too: its name must not resolve to an enclosing + // alias of the same name either. + (None, Some(canonical_name)) => { + let bare = crate::analyzer::helpers::extract_simple_name(canonical_name); + // Normalized as a qualifier is, so a quoted upper-case + // name still meets `reviews` where identifiers match + // without regard to case. + let key = self.analyzer.normalize_identifier(&bare); + self.ctx + .register_bare_table_in_scope(key, canonical_name.clone()); + } + _ => {} } } TableFactor::Derived { @@ -938,8 +966,7 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { self.ctx.mark_table_function_in_scope(); } if let Some(a) = alias { - self.ctx - .register_subquery_alias_in_scope(a.name.to_string()); + self.register_subquery_alias(a.name.to_string()); } self.analyzer.issues.push( Issue::info( @@ -964,8 +991,7 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { self.ctx.mark_table_function_in_scope(); } if let Some(a) = alias { - self.ctx - .register_subquery_alias_in_scope(a.name.to_string()); + self.register_subquery_alias(a.name.to_string()); } self.analyzer.issues.push( Issue::info( @@ -1004,8 +1030,7 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { } } if let Some(a) = alias { - self.ctx - .register_subquery_alias_in_scope(a.name.to_string()); + self.register_subquery_alias(a.name.to_string()); } self.analyzer.issues.push( Issue::warning( @@ -1026,8 +1051,7 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { self.extract_identifiers_from_expr(&col.expr); } if let Some(a) = alias { - self.ctx - .register_subquery_alias_in_scope(a.name.to_string()); + self.register_subquery_alias(a.name.to_string()); } self.analyzer.issues.push( Issue::warning( @@ -1057,8 +1081,7 @@ impl<'a, 'b> Visitor for LineageVisitor<'a, 'b> { } } if let Some(a) = alias { - self.ctx - .register_subquery_alias_in_scope(a.name.to_string()); + self.register_subquery_alias(a.name.to_string()); } } _ => {} diff --git a/crates/flowscope-core/tests/lineage_engine.rs b/crates/flowscope-core/tests/lineage_engine.rs index f3c93f55..628bb327 100644 --- a/crates/flowscope-core/tests/lineage_engine.rs +++ b/crates/flowscope-core/tests/lineage_engine.rs @@ -13928,3 +13928,211 @@ fn any_and_all_subqueries_in_a_select_list_test_rows_like_in() { ); } } + +fn unaliased_scope_schema() -> SchemaMetadata { + SchemaMetadata { + allow_implied: false, + default_catalog: None, + default_schema: None, + search_path: None, + case_sensitivity: None, + tables: vec![ + schema_table( + Some("LAB"), + Some("RAW"), + "EVENTS", + &["id", "book_id", "tags"], + ), + schema_table( + Some("LAB"), + Some("RAW"), + "REVIEWS", + &["id", "book_id", "stars", "tags"], + ), + schema_table( + Some("LAB"), + Some("ARCHIVE"), + "REVIEWS", + &["id", "book_id", "stars", "tags"], + ), + schema_table( + Some("LAB"), + Some("SHELF"), + "LOANS_ENRICHED", + &["loan_id", "book_id"], + ), + schema_table(Some("LAB"), Some("SHELF"), "BOOKS", &["book_id", "title"]), + ], + } +} + +fn filters_of(stmt: &StmtView<'_>, table: &str) -> Vec { + stmt.nodes + .iter() + .find(|node| node.node_type == NodeType::Table && node.label.eq_ignore_ascii_case(table)) + .unwrap_or_else(|| panic!("table {table} not found")) + .filters + .iter() + .map(|filter| filter.expression.clone()) + .collect() +} + +#[test] +fn an_unaliased_table_shadows_an_outer_alias_of_its_name() { + // Under the outer alias `reviews` for EVENTS, the subquery's own table is + // REVIEWS, spelled bare, and its filter belongs to it. + // DuckDB matches identifiers without regard to case, quoted or not, so the + // quoted upper-case spelling must shadow the lower-case qualifier too. + for (dialect, inner, label) in [ + (Dialect::Snowflake, "LAB.RAW.REVIEWS", "unquoted"), + (Dialect::Snowflake, r#""LAB"."RAW"."REVIEWS""#, "quoted"), + (Dialect::Duckdb, "LAB.RAW.REVIEWS", "duckdb unquoted"), + (Dialect::Duckdb, r#""LAB"."RAW"."REVIEWS""#, "duckdb quoted"), + ] { + for (sql, what) in [ + ( + format!( + "SELECT reviews.id FROM LAB.RAW.EVENTS AS reviews \ + WHERE EXISTS (SELECT 1 FROM {inner} WHERE reviews.book_id = 1)" + ), + "EXISTS", + ), + ( + format!( + "SELECT reviews.id, \ + (SELECT MAX(stars) FROM {inner} WHERE reviews.book_id = 1) AS best \ + FROM LAB.RAW.EVENTS AS reviews" + ), + "select list", + ), + ] { + let result = run_analysis(&sql, dialect, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert_eq!( + filters_of(&stmt, "reviews"), + ["reviews.book_id = 1"], + "{label} {what}: {sql}" + ); + assert!( + filters_of(&stmt, "events").is_empty(), + "{label} {what}: {sql}" + ); + } + } +} + +#[test] +fn an_outer_unaliased_table_is_still_read_through_its_bare_name() { + let sql = "SELECT reviews.id, reviews.stars FROM LAB.RAW.REVIEWS WHERE reviews.book_id = 1"; + for dialect in [Dialect::Snowflake, Dialect::Duckdb] { + let result = run_analysis(sql, dialect, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, "stars"), + expected_sources(&["reviews.stars"]), + "{dialect:?}" + ); + assert_eq!( + filters_of(&stmt, "reviews"), + ["reviews.book_id = 1"], + "{dialect:?}" + ); + } +} + +#[test] +fn a_lateral_view_name_shadows_an_outer_alias() { + // The view's name is compared as identifiers are, so `E` shadows `e`. + for view in ["e", "E"] { + let sql = format!( + "SELECT e.id FROM LAB.RAW.EVENTS AS e \ + WHERE EXISTS (SELECT 1 FROM LAB.RAW.REVIEWS AS r \ + LATERAL VIEW explode(r.tags) {view} AS value WHERE e.value = 1)" + ); + let result = run_analysis(&sql, Dialect::Databricks, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert!( + filters_of(&stmt, "EVENTS").is_empty(), + "{view}: EVENTS: {:?}", + filters_of(&stmt, "EVENTS") + ); + } +} + +#[test] +fn an_unaliased_cte_shadows_an_outer_alias_of_its_name() { + let sql = "WITH reviews AS (SELECT id, stars FROM LAB.RAW.REVIEWS) \ + SELECT reviews.id, (SELECT MAX(reviews.stars) FROM reviews) AS best \ + FROM LAB.RAW.EVENTS AS reviews"; + let result = run_analysis(sql, Dialect::Snowflake, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert!(result.issues.is_empty(), "issues: {:?}", result.issues); + // The value comes through the CTE from REVIEWS, not from EVENTS. + assert_eq!( + base_sources_of(&stmt, "best"), + expected_sources(&["reviews.stars"]) + ); + assert!(!table_feeds_column(&stmt, "EVENTS", "best")); +} + +#[test] +fn a_bare_name_two_unaliased_tables_share_resolves_to_neither() { + let sql = "SELECT reviews.stars FROM LAB.RAW.REVIEWS CROSS JOIN LAB.ARCHIVE.REVIEWS"; + let result = run_analysis(sql, Dialect::Snowflake, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert!( + base_sources_of(&stmt, "stars").is_empty(), + "sources: {:?}", + base_sources_of(&stmt, "stars") + ); +} + +#[test] +fn columns_qualified_with_the_bare_name_of_unaliased_tables_are_read() { + let sql = "SELECT loans_enriched.loan_id, books.title \ + FROM LAB.SHELF.LOANS_ENRICHED \ + INNER JOIN LAB.SHELF.BOOKS ON loans_enriched.book_id = books.book_id"; + for dialect in [Dialect::Snowflake, Dialect::Duckdb] { + let result = run_analysis(sql, dialect, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, "loan_id"), + expected_sources(&["loans_enriched.loan_id"]), + "{dialect:?}" + ); + assert_eq!( + base_sources_of(&stmt, "title"), + expected_sources(&["books.title"]), + "{dialect:?}" + ); + } +} + +#[test] +fn a_table_function_alias_shadows_an_outer_alias_of_its_name() { + // `g` names the generator in the subquery; the filter on it is not EVENTS's. + let sql = "SELECT g.id FROM LAB.RAW.EVENTS AS g \ + WHERE EXISTS (SELECT 1 FROM TABLE(GENERATOR(ROWCOUNT => 3)) AS g WHERE g.id = 1)"; + let result = run_analysis(sql, Dialect::Snowflake, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert!( + filters_of(&stmt, "EVENTS").is_empty(), + "EVENTS: {:?}", + filters_of(&stmt, "EVENTS") + ); +} + +#[test] +fn an_upper_case_unnest_alias_shadows_a_lower_case_outer_alias() { + // Postgres folds `U` and `u` to one name; an UNNEST alias is stored as the + // dialect folds it, so the filter on `u.id` is the subquery's, not EVENTS's. + let sql = "SELECT u.id FROM LAB.RAW.EVENTS AS u \ + WHERE EXISTS (SELECT 1 FROM UNNEST(ARRAY[1, 2]) AS U(id) WHERE u.id = 1)"; + let result = run_analysis(sql, Dialect::Postgres, Some(unaliased_scope_schema())); + let stmt = first_statement(&result); + assert!( + filters_of(&stmt, "events").is_empty(), + "events: {:?}", + filters_of(&stmt, "events") + ); +}