From 36d3597b3530e209ab9884bb9c282d5ee397f553 Mon Sep 17 00:00:00 2001 From: William Horel <80535383+IL-William@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:10:16 +0100 Subject: [PATCH] fix(core): read a scalar subquery in a select list A subquery in a select list was never analyzed: only the item's column references were read, and those skip a subquery. With no source, the output column got a relation-level edge from the FROM table, carrying the subquery's text. SELECT b.book_id, (SELECT max(r.stars) FROM reviews AS r WHERE r.book_id = b.book_id) AS best_stars FROM books AS b best_stars came out fed by the books table, and reviews appeared nowhere. Each scalar subquery an item reads as a value, alone or inside a function, a CASE, a cast or an operator, is now analyzed into a (subquery) node of its own, as a predicate subquery already is, and its column feeds the item. Its columns are registered in the enclosing select's scope under the subquery's own key, so a later item reading the alias reaches them, but never as a relation of that select: unqualified names, wildcards, items with no source and the implied schema are as before. The enclosing select's grouping is saved and restored around any subquery it analyzes. EXISTS, IN and the subquery of ANY or ALL in a select list are left as they were. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018LDZwk297SKdJXXLpTFZEh --- crates/flowscope-core/src/analyzer/context.rs | 24 ++ .../flowscope-core/src/analyzer/expression.rs | 313 +++++++++++++++++- .../src/analyzer/select_analyzer.rs | 27 +- crates/flowscope-core/tests/lineage_engine.rs | 285 ++++++++++++++++ 4 files changed, 642 insertions(+), 7 deletions(-) diff --git a/crates/flowscope-core/src/analyzer/context.rs b/crates/flowscope-core/src/analyzer/context.rs index fe03f9dd..af61a889 100644 --- a/crates/flowscope-core/src/analyzer/context.rs +++ b/crates/flowscope-core/src/analyzer/context.rs @@ -754,6 +754,30 @@ impl StatementContext { } } + /// Register a scalar subquery of a select list under its unique key, so a + /// column qualified with the key resolves to the subquery's own column node. + /// + /// Unlike a derived table it is not a relation of the scope: it has no + /// `alias_instances` or `tables` entry, so it neither joins the relations an + /// unqualified column may belong to nor becomes a base relation the + /// source-less projections draw an edge from. + pub(crate) fn register_scalar_subquery_in_scope( + &mut self, + key: String, + node_id: Arc, + columns: Vec, + ) { + // Also a subquery alias, so the implied schema leaves it out the way it + // does a derived table, however a reference to it travels (a lateral + // alias carries it into a later item's sources). + self.subquery_aliases.insert(key.clone()); + self.table_node_ids.insert(key.clone(), node_id); + if let Some(scope) = self.current_scope_mut() { + scope.aliases.insert(key.clone(), key.clone()); + } + self.register_subquery_columns_in_scope(key, columns); + } + /// Returns true when the current scope already materialized columns for `name`. pub(crate) fn has_subquery_columns_in_current_scope(&self, name: &str) -> bool { self.current_scope() diff --git a/crates/flowscope-core/src/analyzer/expression.rs b/crates/flowscope-core/src/analyzer/expression.rs index e912741b..259fbbd0 100644 --- a/crates/flowscope-core/src/analyzer/expression.rs +++ b/crates/flowscope-core/src/analyzer/expression.rs @@ -11,7 +11,7 @@ //! The analyzer works with the parent `Analyzer` to build column-level lineage graphs //! by identifying data flow from source columns through expressions to output columns. -use super::context::{ColumnRef, StatementContext}; +use super::context::{ColumnRef, OutputColumn, StatementContext}; use super::functions; use super::helpers::{check_expr_types, generate_statement_scoped_node_id}; use super::Analyzer; @@ -148,6 +148,35 @@ impl<'a, 'b> ExpressionAnalyzer<'a, 'b> { /// select targets, the statement's output at the top, as if the query /// returned them, and would join the column list of an enclosing CTE. fn analyze_predicate_subquery(&mut self, query: &ast::Query) { + self.analyze_subquery_node(query); + } + + /// Analyzes a subquery a select list reads as a value, `(select max(x) ...)`, + /// and returns one reference per column it projects, qualified with the key + /// of its node. The output column that reads the value then draws its edge + /// from the subquery's column, which carries what the subquery reads, and + /// not from the relations of the enclosing select: the subquery's text + /// names its own tables' columns, which the enclosing select does not own. + pub(crate) fn analyze_scalar_subquery(&mut self, query: &ast::Query) -> Vec { + let (key, node_id, columns) = self.analyze_subquery_node(query); + let refs = columns + .iter() + .map(|column| ColumnRef { + table: Some(key.clone()), + column: column.name.clone(), + }) + .collect(); + self.ctx + .register_scalar_subquery_in_scope(key, node_id, columns); + refs + } + + /// Analyzes `query` against a `(subquery)` node of its own, keyed uniquely + /// within the statement, and takes its output columns back. + fn analyze_subquery_node( + &mut self, + query: &ast::Query, + ) -> (String, Arc, Vec) { let checkpoint = self.ctx.projection_checkpoint(); self.ctx.predicate_subqueries += 1; let key = format!("{PREDICATE_SUBQUERY}#{}", self.ctx.predicate_subqueries); @@ -158,8 +187,288 @@ impl<'a, 'b> ExpressionAnalyzer<'a, 'b> { qualified_name: Some(PREDICATE_SUBQUERY.into()), ..Default::default() }); + // The subquery's own select clears the grouping the enclosing select + // set up, and the items after it still need it to tell a key from an + // aggregate. + let grouping_columns = self.ctx.grouping_columns.clone(); + let has_group_by = self.ctx.has_group_by; self.analyzer.analyze_query(self.ctx, query, Some(&node_id)); - self.ctx.take_output_columns_since(checkpoint); + self.ctx.grouping_columns = grouping_columns; + self.ctx.has_group_by = has_group_by; + let columns = self.ctx.take_output_columns_since(checkpoint); + (key, node_id, columns) + } + + /// Analyzes each subquery a select item reads as a value and returns the + /// references to the columns they project. `EXISTS` and `IN (subquery)` test + /// rows rather than carry a column, and a subquery inside another query is + /// that query's own to analyze, so neither is visited. + pub(crate) fn analyze_scalar_subqueries(&mut self, expr: &Expr) -> Vec { + let mut queries = Vec::new(); + if Self::collect_scalar_subqueries(expr, &mut queries, 0) { + self.analyzer + .emit_depth_limit_warning(self.ctx.statement_index); + } + queries + .into_iter() + .flat_map(|query| self.analyze_scalar_subquery(query)) + .collect() + } + + /// Collects the subqueries `expr` reads in a value position, left to right, + /// and reports whether the depth limit cut the walk short. + /// + /// It must stay in step with `collect_column_refs`: a form that one reads + /// operands of and the other does not leaves a subquery read by the text + /// only, which the enclosing relation then gets credited with. Forms that + /// test rows (`EXISTS`, `IN (subquery)`) or open a scope of their own + /// (a lambda) are not walked into. + fn collect_scalar_subqueries<'e>( + expr: &'e Expr, + queries: &mut Vec<&'e ast::Query>, + depth: usize, + ) -> bool { + if depth > MAX_RECURSION_DEPTH { + return true; + } + let next_depth = depth + 1; + let mut depth_limited = false; + let mut walk = |e: &'e Expr, queries: &mut Vec<&'e ast::Query>| { + depth_limited |= Self::collect_scalar_subqueries(e, queries, next_depth); + }; + + match expr { + Expr::Subquery(query) => queries.push(query), + Expr::BinaryOp { .. } => { + for operand in binary_op_operands(expr) { + walk(operand, queries); + } + } + Expr::UnaryOp { expr, .. } + | Expr::Nested(expr) + | Expr::Cast { expr, .. } + | Expr::Extract { expr, .. } + | Expr::IsNull(expr) + | Expr::IsNotNull(expr) + | Expr::IsTrue(expr) + | Expr::IsNotTrue(expr) + | Expr::IsFalse(expr) + | Expr::IsNotFalse(expr) + | Expr::IsUnknown(expr) + | Expr::IsNotUnknown(expr) + | Expr::IsNormalized { expr, .. } + | Expr::Ceil { expr, .. } + | Expr::Floor { expr, .. } + | Expr::Collate { expr, .. } + | Expr::Prefixed { value: expr, .. } + | Expr::Named { expr, .. } + | Expr::OuterJoin(expr) + | Expr::Prior(expr) + | Expr::InSubquery { expr, .. } => walk(expr, queries), + Expr::Interval(interval) => walk(&interval.value, queries), + Expr::Function(func) => { + if let ast::FunctionArguments::List(args) = &func.args { + for arg in &args.args { + match arg { + FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) + | FunctionArg::Named { + arg: FunctionArgExpr::Expr(e), + .. + } + | FunctionArg::ExprNamed { + arg: FunctionArgExpr::Expr(e), + .. + } => walk(e, queries), + _ => {} + } + } + } + } + Expr::Case { + operand, + conditions, + else_result, + .. + } => { + if let Some(op) = operand { + walk(op, queries); + } + for case_when in conditions { + walk(&case_when.condition, queries); + walk(&case_when.result, queries); + } + if let Some(el) = else_result { + walk(el, queries); + } + } + Expr::InList { expr, list, .. } => { + walk(expr, queries); + for item in list { + walk(item, queries); + } + } + Expr::Between { + expr, low, high, .. + } => { + walk(expr, queries); + walk(low, queries); + walk(high, queries); + } + Expr::Like { expr, pattern, .. } | Expr::ILike { expr, pattern, .. } => { + walk(expr, queries); + walk(pattern, queries); + } + Expr::IsDistinctFrom(left, right) + | Expr::IsNotDistinctFrom(left, right) + | Expr::SimilarTo { + expr: left, + pattern: right, + .. + } + | Expr::RLike { + expr: left, + pattern: right, + .. + } + | Expr::Position { + expr: left, + r#in: right, + } + | Expr::AtTimeZone { + timestamp: left, + time_zone: right, + } + | Expr::InUnnest { + expr: left, + array_expr: right, + .. + } => { + walk(left, queries); + walk(right, queries); + } + // `= ANY (subquery)` tests rows as `IN (subquery)` does; only the + // value compared is read. + Expr::AnyOp { left, right, .. } | Expr::AllOp { left, right, .. } => { + walk(left, queries); + if !matches!(**right, Expr::Subquery(_)) { + walk(right, queries); + } + } + Expr::MemberOf(member_of) => { + walk(&member_of.value, queries); + walk(&member_of.array, queries); + } + Expr::Tuple(exprs) + | Expr::Struct { values: exprs, .. } + | Expr::Array(ast::Array { elem: exprs, .. }) => { + for e in exprs { + walk(e, queries); + } + } + Expr::Trim { + expr, + trim_what, + trim_characters, + .. + } => { + walk(expr, queries); + if let Some(what) = trim_what { + walk(what, queries); + } + for characters in trim_characters.iter().flatten() { + walk(characters, queries); + } + } + Expr::Substring { + expr, + substring_from, + substring_for, + .. + } => { + walk(expr, queries); + for bound in [substring_from, substring_for].into_iter().flatten() { + walk(bound, queries); + } + } + Expr::Overlay { + expr, + overlay_what, + overlay_from, + overlay_for, + } => { + walk(expr, queries); + walk(overlay_what, queries); + walk(overlay_from, queries); + if let Some(length) = overlay_for { + walk(length, queries); + } + } + Expr::Convert { expr, styles, .. } => { + walk(expr, queries); + for style in styles { + walk(style, queries); + } + } + Expr::JsonAccess { value, path } => { + walk(value, queries); + for elem in &path.path { + if let ast::JsonPathElem::Bracket { key } = elem { + walk(key, queries); + } + } + } + Expr::CompoundFieldAccess { root, access_chain } => { + walk(root, queries); + for access in access_chain { + match access { + ast::AccessExpr::Dot(_) => {} + ast::AccessExpr::Subscript(ast::Subscript::Index { index }) => { + walk(index, queries); + } + ast::AccessExpr::Subscript(ast::Subscript::Slice { + lower_bound, + upper_bound, + stride, + }) => { + for bound in [lower_bound, upper_bound, stride].into_iter().flatten() { + walk(bound, queries); + } + } + } + } + } + Expr::Dictionary(fields) => { + for field in fields { + walk(&field.value, queries); + } + } + Expr::Map(map) => { + for entry in &map.entries { + walk(&entry.key, queries); + walk(&entry.value, queries); + } + } + Expr::GroupingSets(sets) | Expr::Cube(sets) | Expr::Rollup(sets) => { + for e in sets.iter().flatten() { + walk(e, queries); + } + } + // Listed rather than caught by `_`, as in `collect_column_refs`, so + // a variant added to sqlparser is a compile error here too. None of + // these reads a value a subquery could stand in for: names, literals, + // row-testing forms, and a lambda, whose body has its own parameters. + Expr::Identifier(_) + | Expr::CompoundIdentifier(_) + | Expr::Exists { .. } + | Expr::Lambda(_) + | Expr::MatchAgainst { .. } + | Expr::Value(_) + | Expr::TypedString(_) + | Expr::Wildcard(_) + | Expr::QualifiedWildcard(..) => {} + } + + depth_limited } /// Recursively visits an expression to find and analyze subqueries. diff --git a/crates/flowscope-core/src/analyzer/select_analyzer.rs b/crates/flowscope-core/src/analyzer/select_analyzer.rs index d9145e9a..5431e311 100644 --- a/crates/flowscope-core/src/analyzer/select_analyzer.rs +++ b/crates/flowscope-core/src/analyzer/select_analyzer.rs @@ -118,13 +118,14 @@ impl<'a, 'b> SelectAnalyzer<'a, 'b> { // Check for lateral column alias usage self.check_lateral_column_alias(expr, &defined_aliases); - let (mut sources, name, aggregation) = { + let (mut sources, name, aggregation, scalar_refs) = { let mut ea = ExpressionAnalyzer::new(self.analyzer, self.ctx); let column_refs = ea.extract_column_refs_with_warning(expr); ( column_refs, ea.derive_column_name(expr, idx), ea.detect_aggregation(expr), + ea.analyze_scalar_subqueries(expr), ) }; @@ -137,6 +138,12 @@ impl<'a, 'b> SelectAnalyzer<'a, 'b> { ); } + // What a scalar subquery reads reaches the item through the + // subquery's own columns. They are not columns of a relation + // of this select, so they are left out of the implied schema. + let outer_sources = sources.len(); + sources.extend(scalar_refs); + let is_simple_ref = is_simple_column_ref(expr); let expr_text = if is_simple_ref { None @@ -154,7 +161,7 @@ impl<'a, 'b> SelectAnalyzer<'a, 'b> { // functions, arithmetic), we only record the column existence without // a type since the expression output type differs from source column type. let source_type = if is_simple_ref { &data_type } else { &None }; - self.record_source_columns_with_type(&sources, source_type); + self.record_source_columns_with_type(&sources[..outer_sources], source_type); self.analyzer.add_output_column_with_aggregation( self.ctx, @@ -173,10 +180,14 @@ impl<'a, 'b> SelectAnalyzer<'a, 'b> { // Check for lateral column alias usage self.check_lateral_column_alias(expr, &defined_aliases); - let (mut sources, aggregation) = { + let (mut sources, aggregation, scalar_refs) = { let mut ea = ExpressionAnalyzer::new(self.analyzer, self.ctx); let column_refs = ea.extract_column_refs_with_warning(expr); - (column_refs, ea.detect_aggregation(expr)) + ( + column_refs, + ea.detect_aggregation(expr), + ea.analyze_scalar_subqueries(expr), + ) }; // Resolve lateral alias references if dialect supports them @@ -188,6 +199,12 @@ impl<'a, 'b> SelectAnalyzer<'a, 'b> { ); } + // What a scalar subquery reads reaches the item through the + // subquery's own columns. They are not columns of a relation + // of this select, so they are left out of the implied schema. + let outer_sources = sources.len(); + sources.extend(scalar_refs); + let name = alias.value.clone(); let is_simple_ref = is_simple_column_ref(expr); let expr_text = if is_simple_ref { @@ -206,7 +223,7 @@ impl<'a, 'b> SelectAnalyzer<'a, 'b> { // functions, arithmetic), we only record the column existence without // a type since the expression output type differs from source column type. let source_type = if is_simple_ref { &data_type } else { &None }; - self.record_source_columns_with_type(&sources, source_type); + self.record_source_columns_with_type(&sources[..outer_sources], source_type); // Record this alias for subsequent lateral column alias checking let normalized_alias = self.analyzer.normalize_identifier(&name); diff --git a/crates/flowscope-core/tests/lineage_engine.rs b/crates/flowscope-core/tests/lineage_engine.rs index 4529c226..f3c93f55 100644 --- a/crates/flowscope-core/tests/lineage_engine.rs +++ b/crates/flowscope-core/tests/lineage_engine.rs @@ -13643,3 +13643,288 @@ fn a_column_wins_over_an_earlier_alias_of_its_name() { } } } + +fn shelf_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("SHELF"), + "BOOKS", + &["book_id", "title", "tags", "genre_code"], + ), + schema_table( + Some("LAB"), + Some("RAW"), + "REVIEWS", + &["review_id", "book_id", "stars", "written_at"], + ), + ], + } +} + +/// True when an edge of any type runs from the table node `table` to the +/// column node labelled `output` (compared without case). +fn table_feeds_column(stmt: &StmtView<'_>, table: &str, output: &str) -> bool { + let table = find_table_node(stmt, table).unwrap_or_else(|| panic!("table {table} not found")); + stmt.nodes + .iter() + .filter(|node| { + node.node_type == NodeType::Column && node.label.eq_ignore_ascii_case(output) + }) + .any(|column| { + stmt.edges + .iter() + .any(|edge| edge.from == table.id && edge.to == column.id) + }) +} + +#[test] +fn scalar_subquery_in_a_select_list_feeds_its_column() { + let sql = r#" + SELECT + b.book_id, + (SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r WHERE r.book_id = b.book_id) AS best_stars, + (SELECT MAX(r.written_at) FROM LAB.RAW.REVIEWS AS r) AS last_review_at + FROM LAB.SHELF.BOOKS AS b + "#; + + let result = run_analysis(sql, Dialect::Snowflake, Some(shelf_schema())); + let stmt = first_statement(&result); + + // The output column is drawn from the subquery's own column, which reads + // the table the subquery names. + assert_eq!( + source_columns_of(&stmt, "best_stars"), + expected_sources(&["(subquery).max"]) + ); + assert_eq!( + base_sources_of(&stmt, "best_stars"), + expected_sources(&["reviews.stars"]) + ); + assert_eq!( + source_columns_of(&stmt, "last_review_at"), + expected_sources(&["(subquery).max"]) + ); + assert_eq!( + base_sources_of(&stmt, "last_review_at"), + expected_sources(&["reviews.written_at"]) + ); + assert_eq!( + base_sources_of(&stmt, "book_id"), + expected_sources(&["books.book_id"]) + ); + + // The enclosing table no longer stands in for what the subquery reads. + assert!(!table_feeds_column(&stmt, "BOOKS", "best_stars")); + assert!(!table_feeds_column(&stmt, "BOOKS", "last_review_at")); + assert_eq!( + returned_columns(&stmt), + vec!["best_stars", "book_id", "last_review_at"] + ); +} + +#[test] +fn correlated_scalar_subquery_filters_itself_and_resolves_the_outer_alias() { + // The engine keeps a predicate that spans two relations out of the filters + // (it is a correlation, not a restriction of either), so the literal one + // shows where the subquery's WHERE lands: on REVIEWS, never on BOOKS. + let sql = r#" + SELECT + b.book_id, + (SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r WHERE r.book_id = b.book_id AND r.stars > 2) AS best_stars + FROM LAB.SHELF.BOOKS AS b + "#; + + let result = run_analysis(sql, Dialect::Snowflake, Some(shelf_schema())); + let stmt = first_statement(&result); + + let reviews = find_table_node(&stmt, "REVIEWS").expect("REVIEWS table not found"); + let books = find_table_node(&stmt, "BOOKS").expect("BOOKS table not found"); + assert_eq!( + reviews + .filters + .iter() + .map(|filter| filter.expression.as_str()) + .collect::>(), + ["r.stars > 2"] + ); + assert!(books.filters.is_empty(), "books: {:?}", books.filters); + assert!(result.issues.is_empty(), "issues: {:?}", result.issues); +} + +#[test] +fn scalar_subquery_inside_a_function_or_case_feeds_beside_the_outer_column() { + for (sql, output, sources) in [ + ( + "SELECT COALESCE((SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r WHERE r.book_id = b.book_id), b.genre_code) AS best \ + FROM LAB.SHELF.BOOKS AS b", + "best", + vec!["reviews.stars", "books.genre_code"], + ), + ( + "SELECT CASE WHEN b.genre_code = 'x' THEN (SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r) ELSE b.title END AS best \ + FROM LAB.SHELF.BOOKS AS b", + "best", + vec!["reviews.stars", "books.title", "books.genre_code"], + ), + ( + "SELECT CAST((SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r) AS VARCHAR) || b.title AS best \ + FROM LAB.SHELF.BOOKS AS b", + "best", + vec!["reviews.stars", "books.title"], + ), + ] { + let result = run_analysis(sql, Dialect::Snowflake, Some(shelf_schema())); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, output), + expected_sources(&sources), + "{sql}" + ); + assert!(result.issues.is_empty(), "{sql}: {:?}", result.issues); + } +} + +#[test] +fn exists_in_a_select_list_is_left_as_it_was() { + // EXISTS tests rows, it carries no column: the output column reads + // nothing from the subquery's table. + let sql = "SELECT EXISTS (SELECT 1 FROM LAB.RAW.REVIEWS AS r WHERE r.book_id = b.book_id) AS reviewed \ + FROM LAB.SHELF.BOOKS AS b"; + + let result = run_analysis(sql, Dialect::Snowflake, Some(shelf_schema())); + let stmt = first_statement(&result); + assert!(base_sources_of(&stmt, "reviewed") + .iter() + .all(|source| !source.starts_with("reviews."))); +} + +#[test] +fn scalar_subquery_leaves_the_grouping_of_the_enclosing_select_alone() { + // The subquery's own select clears the grouping it finds; the items after + // it must still tell a grouping key from an aggregate. + let grouped = "COUNT(*) AS n FROM LAB.SHELF.BOOKS AS b GROUP BY b.genre_code"; + let plain = format!("SELECT b.genre_code, {grouped}"); + let with_subquery = format!( + "SELECT (SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r) AS m, b.genre_code, {grouped}" + ); + + // Whether the `genre_code` columns of the graph carry an aggregation entry + // that marks them as a grouping key. + let grouping_keys = |sql: &str| { + let result = run_analysis(sql, Dialect::Snowflake, Some(shelf_schema())); + let stmt = first_statement(&result); + stmt.nodes + .iter() + .filter(|n| { + n.node_type == NodeType::Column && n.label.eq_ignore_ascii_case("genre_code") + }) + .map(|n| n.aggregation.as_ref().is_some_and(|a| a.is_grouping_key)) + .collect::>() + }; + assert_eq!(grouping_keys(&with_subquery), grouping_keys(&plain)); + assert!( + grouping_keys(&with_subquery).contains(&true), + "genre_code stays a grouping key" + ); +} + +#[test] +fn scalar_subquery_in_a_cte_body_feeds_the_cte_column() { + let sql = r#" + WITH rated AS ( + SELECT + b.book_id, + (SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r WHERE r.book_id = b.book_id) AS best_stars + FROM LAB.SHELF.BOOKS AS b + ) + SELECT book_id, best_stars FROM rated + "#; + + let result = run_analysis(sql, Dialect::Snowflake, Some(shelf_schema())); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, "best_stars"), + expected_sources(&["reviews.stars"]) + ); + assert!(!table_feeds_column(&stmt, "BOOKS", "best_stars")); + assert_eq!( + returned_columns(&stmt), + vec!["best_stars", "book_id"], + "the subquery's column is not a column of the CTE" + ); +} + +#[test] +fn scalar_subquery_inside_more_function_forms_feeds_the_column() { + for sql in [ + "SELECT TRIM((SELECT MAX(r.written_at) FROM LAB.RAW.REVIEWS AS r)) AS v FROM LAB.SHELF.BOOKS AS b", + "SELECT SUBSTRING((SELECT MAX(r.written_at) FROM LAB.RAW.REVIEWS AS r) FROM 1 FOR 4) AS v FROM LAB.SHELF.BOOKS AS b", + "SELECT (SELECT MAX(r.written_at) FROM LAB.RAW.REVIEWS AS r) AT TIME ZONE 'UTC' AS v FROM LAB.SHELF.BOOKS AS b", + ] { + let result = run_analysis(sql, Dialect::Postgres, Some(shelf_schema())); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, "v"), + expected_sources(&["reviews.written_at"]), + "{sql}" + ); + assert!(!table_feeds_column(&stmt, "books", "v"), "{sql}"); + } +} + +#[test] +fn scalar_subquery_through_a_lateral_alias_stays_out_of_the_implied_schema() { + // `m1` reads the subquery through the lateral alias `m`. The key the + // subquery is registered under must not become an implied table, which a + // later statement's own subquery would then be checked against. + let sql = "SELECT (SELECT MAX(r.stars) FROM LAB.RAW.REVIEWS AS r) AS m, m + 1 AS m1 FROM LAB.SHELF.BOOKS AS b;\n\ + SELECT (SELECT MIN(r.written_at) AS first_at FROM LAB.RAW.REVIEWS AS r) AS f FROM LAB.SHELF.BOOKS AS b;"; + let mut schema = shelf_schema(); + schema.allow_implied = true; + + let result = run_analysis(sql, Dialect::Snowflake, Some(schema)); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, "m1"), + expected_sources(&["reviews.stars"]) + ); + let resolved = result.resolved_schema.as_ref().expect("resolved schema"); + assert!( + resolved + .tables + .iter() + .all(|table| !table.name.contains("(subquery)")), + "tables: {:?}", + resolved.tables.iter().map(|t| &t.name).collect::>() + ); + assert!( + !issue_codes_list(&result).contains(&issue_codes::UNKNOWN_COLUMN.to_string()), + "issues: {:?}", + result.issues + ); +} + +#[test] +fn any_and_all_subqueries_in_a_select_list_test_rows_like_in() { + // Only the value compared is read, as with IN (subquery). + for op in ["ANY", "ALL"] { + let sql = format!( + "SELECT b.book_id = {op} (SELECT r.book_id FROM LAB.RAW.REVIEWS AS r) AS listed \ + FROM LAB.SHELF.BOOKS AS b" + ); + let result = run_analysis(&sql, Dialect::Postgres, Some(shelf_schema())); + let stmt = first_statement(&result); + assert_eq!( + base_sources_of(&stmt, "listed"), + expected_sources(&["books.book_id"]), + "{sql}" + ); + } +}