From a8d5031b26c5492558f9683a525f3f65e279d0b0 Mon Sep 17 00:00:00 2001 From: mattsu Date: Fri, 27 Nov 2026 07:42:13 +0900 Subject: [PATCH 1/3] fix: validate canonical IDs when seeding alias generator Require extracted alias suffixes parsed by `advance_generator_past_existing` to be canonical positive decimal integers in `1..usize::MAX` without leading zeros or signs. This prevents invalid suffixes (`_0`, `_01`, `_+1`, etc.) from advancing the counter and prevents `usize::MAX` from overflowing when `update_min_id` increments it. --- .../optimizer/src/extract_leaf_expressions.rs | 64 +++++++++++++++++-- 1 file changed, 59 insertions(+), 5 deletions(-) diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rs index 3ed0880feb432..4390186086af6 100644 --- a/datafusion/optimizer/src/extract_leaf_expressions.rs +++ b/datafusion/optimizer/src/extract_leaf_expressions.rs @@ -77,6 +77,21 @@ use crate::{OptimizerConfig, OptimizerRule}; /// in user queries. const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted"; +/// Recognizes canonical positive decimal IDs (`1..usize::MAX` without leading +/// zeros) for seeding [`AliasGenerator`] in [`advance_generator_past_existing`]. +fn extracted_expr_id(name: &str) -> Option { + let suffix = name + .strip_prefix(EXTRACTED_EXPR_PREFIX)? + .strip_prefix('_')?; + // Integer parsing alone also accepts leading zeros and a leading '+'. + if suffix.starts_with('0') || !suffix.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let id = suffix.parse::().ok()?; + // update_min_id adds one, so the maximum value has no usable successor. + (id < usize::MAX).then_some(id) +} + /// Returns `true` if any sub-expression in `exprs` has /// [`ExpressionPlacement::MoveTowardsLeafNodes`] placement. /// @@ -235,11 +250,7 @@ fn advance_generator_past_existing( plan.apply_expressions(|expr| { expr.apply(|e| { if let Expr::Alias(alias) = e - && let Some(id) = alias - .name - .strip_prefix(EXTRACTED_EXPR_PREFIX) - .and_then(|s| s.strip_prefix('_')) - .and_then(|s| s.parse().ok()) + && let Some(id) = extracted_expr_id(&alias.name) { alias_generator.update_min_id(id); } @@ -3778,6 +3789,49 @@ mod tests { Ok(()) } + #[test] + fn test_extracted_expr_id_boundaries() { + for id in [1, 42, usize::MAX - 1] { + let name = format!("{EXTRACTED_EXPR_PREFIX}_{id}"); + assert_eq!(extracted_expr_id(&name), Some(id), "{name}"); + } + + assert_eq!(extracted_expr_id(EXTRACTED_EXPR_PREFIX), None); + let invalid_suffixes = + ["", "0", "01", "0001", "+1", "-1", "1x", " 1", "1 ", "1"] + .map(str::to_owned); + for suffix in invalid_suffixes + .into_iter() + .chain([usize::MAX.to_string(), format!("{}0", usize::MAX)]) + { + let name = format!("{EXTRACTED_EXPR_PREFIX}_{suffix}"); + assert_eq!(extracted_expr_id(&name), None, "{name}"); + } + } + + #[test] + fn test_advance_generator_ignores_invalid_extraction_ids() -> Result<()> { + let exprs = [ + "0".to_owned(), + "01".to_owned(), + usize::MAX.to_string(), + format!("{}0", usize::MAX), + ] + .into_iter() + .map(|suffix| lit(1).alias(format!("{EXTRACTED_EXPR_PREFIX}_{suffix}"))) + .collect::>(); + let plan = LogicalPlanBuilder::from(test_table_scan_with_struct()?) + .project(exprs)? + .build()?; + let alias_generator = AliasGenerator::new(); + advance_generator_past_existing(&plan, &alias_generator)?; + assert_eq!( + alias_generator.next(EXTRACTED_EXPR_PREFIX), + "__datafusion_extracted_1" + ); + Ok(()) + } + /// Pre-existing `__datafusion_extracted_N` aliases must advance the alias /// generator even when they live inside a subquery plan, since extraction /// descends into subqueries and would otherwise reuse the same alias. From 76acab81b140276972e672105a2bc5f57806e225 Mon Sep 17 00:00:00 2001 From: mattsu Date: Fri, 27 Nov 2026 07:44:16 +0900 Subject: [PATCH 2/3] fix: classify leaf extraction aliases by placement Classify an alias as an extraction alias only when its name starts with `__datafusion_extracted` and its inner expression is eligible for leaf pushdown (`ExpressionPlacement::should_push_to_leaves`). This prevents user-defined aliases with canonical names such as `10 / id AS __datafusion_extracted_1` from being hoisted below filters, while still accepting optimizer-generated `usize::MAX` and wrapped `_0` aliases. Numeric suffix parsing remains reserved for generator seeding. --- .../optimizer/src/extract_leaf_expressions.rs | 169 ++++++++++++++++-- .../test_files/projection_pushdown.slt | 98 ++++++++++ 2 files changed, 252 insertions(+), 15 deletions(-) diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rs index 4390186086af6..e72d23efeaf40 100644 --- a/datafusion/optimizer/src/extract_leaf_expressions.rs +++ b/datafusion/optimizer/src/extract_leaf_expressions.rs @@ -61,6 +61,7 @@ use std::sync::Arc; use datafusion_common::alias::AliasGenerator; use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion_common::{Column, DFSchema, Result, qualified_name}; +use datafusion_expr::expr::Alias; use datafusion_expr::logical_plan::LogicalPlan; use datafusion_expr::{Expr, ExpressionPlacement, Projection}; @@ -71,14 +72,20 @@ use crate::{OptimizerConfig, OptimizerRule}; /// Prefix for aliases generated by the extraction optimizer passes. /// -/// This prefix is **reserved for internal optimizer use**. User-defined aliases -/// starting with this prefix may be misidentified as optimizer-generated -/// extraction aliases, leading to unexpected behavior. Do not use this prefix -/// in user queries. +/// Aliases starting with this prefix are classified as extraction aliases when +/// their inner expression is eligible for leaf pushdown +/// ([`ExpressionPlacement::should_push_to_leaves`]). Canonical positive decimal +/// suffixes (`1..usize::MAX`, without leading zeros) are parsed solely to seed +/// [`AliasGenerator`]; user aliases with this prefix that wrap pushable +/// expressions may still be treated as extraction aliases. const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted"; /// Recognizes canonical positive decimal IDs (`1..usize::MAX` without leading /// zeros) for seeding [`AliasGenerator`] in [`advance_generator_past_existing`]. +/// +/// Extraction alias classification uses [`is_extracted_alias`] instead so +/// generated `usize::MAX` (and wrapped `0`) aliases are accepted while +/// non-pushable user aliases with canonical names are rejected. fn extracted_expr_id(name: &str) -> Option { let suffix = name .strip_prefix(EXTRACTED_EXPR_PREFIX)? @@ -92,6 +99,18 @@ fn extracted_expr_id(name: &str) -> Option { (id < usize::MAX).then_some(id) } +/// Returns `true` if `alias` carries the extraction prefix and wraps an +/// expression eligible for leaf pushdown (`MoveTowardsLeafNodes` or `Column`). +/// +/// Checking expression placement prevents user-defined aliases with canonical +/// names (such as `10 / id AS __datafusion_extracted_1`) from being hoisted +/// below filters, while accepting optimizer-generated aliases regardless of +/// counter wraparound at `usize::MAX`. +fn is_extracted_alias(alias: &Alias) -> bool { + alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && alias.expr.placement().should_push_to_leaves() +} + /// Returns `true` if any sub-expression in `exprs` has /// [`ExpressionPlacement::MoveTowardsLeafNodes`] placement. /// @@ -404,9 +423,9 @@ fn routing_extract( input_column_sets: &[std::collections::HashSet], ) -> Result> { expr.transform_down(|e| { - // Skip expressions already aliased with extracted expression pattern + // Skip expressions already aliased as extraction expressions. if let Expr::Alias(alias) = &e - && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && is_extracted_alias(alias) { return Ok(Transformed { data: e, @@ -723,7 +742,7 @@ fn build_extraction_projection_impl( .iter() .filter_map(|e| { if let Expr::Alias(alias) = e - && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && is_extracted_alias(alias) { return Some((*alias.expr.clone(), alias.name.clone())); } @@ -1016,9 +1035,10 @@ fn split_and_push_projection( ) -> Result> { // Fast pre-check: skip if there are no pre-existing extracted aliases // and no new extractable expressions. - let has_existing_extracted = proj.expr.iter().any(|e| { - matches!(e, Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX)) - }); + let has_existing_extracted = proj + .expr + .iter() + .any(|e| matches!(e, Expr::Alias(alias) if is_extracted_alias(alias))); if !has_existing_extracted && !has_extractable_expr(&proj.expr) { return Ok(None); } @@ -1060,7 +1080,7 @@ fn split_and_push_projection( recovery_exprs.push(expr.clone()); proj_exprs_captured += 1; } else if let Expr::Alias(alias) = expr - && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && is_extracted_alias(alias) { // Insert the full Alias expression as the key so that // distinct alias names don't collide in the IndexMap. @@ -1249,8 +1269,15 @@ fn split_and_push_projection( } /// Returns true if `exprs` are the expressions of a *pure extraction -/// projection*: every expression is either `Alias(EXTRACTED_EXPR_PREFIX, ...)` -/// or a bare `Column`, and there is at least one extraction alias. +/// projection*: every expression is either an extraction alias (matching +/// [`EXTRACTED_EXPR_PREFIX`] with a pushdown-eligible inner expression via +/// [`ExpressionPlacement::should_push_to_leaves`]) or a bare `Column`, and +/// there is at least one extraction alias. +/// +/// Numeric suffix validation is reserved for generator seeding in +/// [`advance_generator_past_existing`]; classification relies on prefix and +/// expression placement so generated `usize::MAX` (and wrapped `0`) aliases +/// are accepted while non-pushable user aliases are rejected. /// /// Such projections can safely be pushed further without re-extraction. /// @@ -1261,7 +1288,7 @@ pub(crate) fn is_pure_extraction_projection(exprs: &[Expr]) -> bool { let mut has_extraction = false; for expr in exprs { match expr { - Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX) => { + Expr::Alias(alias) if is_extracted_alias(alias) => { has_extraction = true; } Expr::Column(_) => {} @@ -3832,6 +3859,70 @@ mod tests { Ok(()) } + fn inexact_table_scan_with_struct() -> Result { + #[derive(Debug)] + struct InexactStructTable(arrow::datatypes::SchemaRef); + + impl datafusion_expr::TableSource for InexactStructTable { + fn schema(&self) -> arrow::datatypes::SchemaRef { + Arc::clone(&self.0) + } + fn table_type(&self) -> datafusion_expr::TableType { + datafusion_expr::TableType::Base + } + fn supports_filters_pushdown( + &self, + filters: &[&Expr], + ) -> Result> { + Ok(vec![ + datafusion_expr::TableProviderFilterPushDown::Inexact; + filters.len() + ]) + } + } + + let schema = Arc::new(arrow::datatypes::Schema::new( + test_table_scan_with_struct_fields(), + )); + LogicalPlanBuilder::scan("test", Arc::new(InexactStructTable(schema)), None)? + .build() + } + + #[test] + fn test_canonical_user_alias_not_pushed_below_filter() -> Result<()> { + let table_scan = inexact_table_scan_with_struct()?; + let guarded_div = datafusion_expr::binary_expr( + lit(10u32), + datafusion_expr::Operator::Divide, + col("id"), + ) + .alias(format!("{EXTRACTED_EXPR_PREFIX}_1")); + let plan = LogicalPlanBuilder::from(table_scan) + .filter( + col("id") + .gt(lit(0u32)) + .and(leaf_udf(col("user"), "status").eq(lit("active"))), + )? + .project(vec![guarded_div])? + .build()?; + + let ctx = OptimizerContext::new(); + let optimizer = Optimizer::with_rules(vec![ + Arc::new(crate::push_down_filter::PushDownFilter::new()), + Arc::new(ExtractLeafExpressions::new()), + Arc::new(PushDownLeafProjections::new()), + Arc::new(OptimizeProjections::new()), + ]); + let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?; + insta::assert_snapshot!(format!("{optimized}"), @r#" + Projection: UInt32(10) / test.id AS __datafusion_extracted_1 + Filter: test.id > UInt32(0) AND __datafusion_extracted_2 = Utf8("active") + Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id + TableScan: test projection=[id, user], partial_filters=[test.id > UInt32(0), leaf_udf(test.user, Utf8("status")) = Utf8("active")] + "#); + Ok(()) + } + /// Pre-existing `__datafusion_extracted_N` aliases must advance the alias /// generator even when they live inside a subquery plan, since extraction /// descends into subqueries and would otherwise reuse the same alias. @@ -4023,11 +4114,59 @@ mod tests { assert!(!is_pure_extraction_projection(&common_expr.expressions())); // A bare expression is never allowed. - let bare_expr = LogicalPlanBuilder::from(scan) + let bare_expr = LogicalPlanBuilder::from(scan.clone()) .project(vec![leaf_udf(col("user"), "status"), col("id")])? .build()?; assert!(!is_pure_extraction_projection(&bare_expr.expressions())); + // Generated boundary IDs (usize::MAX and wrapped 0) remain valid when + // wrapping a pushdown-eligible expression. + let max_id_expr = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + leaf_udf(col("user"), "status") + .alias(format!("{EXTRACTED_EXPR_PREFIX}_{}", usize::MAX)), + col("id"), + ])? + .build()?; + assert!(is_pure_extraction_projection(&max_id_expr.expressions())); + + let zero_id_expr = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + leaf_udf(col("user"), "status") + .alias(format!("{EXTRACTED_EXPR_PREFIX}_0")), + col("id"), + ])? + .build()?; + assert!(is_pure_extraction_projection(&zero_id_expr.expressions())); + + // Column-backed extraction aliases (e.g. after CSE or SubqueryAlias) + // are pushdown-eligible too. + let column_alias = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + col("user").alias(format!("{EXTRACTED_EXPR_PREFIX}_1")), + col("id"), + ])? + .build()?; + assert!(is_pure_extraction_projection(&column_alias.expressions())); + + // Canonical user aliases wrapping KeepInPlace or Literal expressions + // must not be classified as extraction aliases. + let non_pushable = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + (col("id") + lit(1u32)).alias(format!("{EXTRACTED_EXPR_PREFIX}_1")), + col("id"), + ])? + .build()?; + assert!(!is_pure_extraction_projection(&non_pushable.expressions())); + + let literal_alias = LogicalPlanBuilder::from(scan) + .project(vec![ + lit(1u32).alias(format!("{EXTRACTED_EXPR_PREFIX}_1")), + col("id"), + ])? + .build()?; + assert!(!is_pure_extraction_projection(&literal_alias.expressions())); + Ok(()) } diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..a722ae7b3e311 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -1949,6 +1949,104 @@ ORDER BY simple_struct.id; # (https://github.com/apache/datafusion/issues/20430) # ========================================================================= +# A prefix alone does not make an alias an extraction. In particular, moving +# this division below the filter would evaluate it on the zero row as well. +statement ok +CREATE TABLE extracted_alias_names AS +SELECT * FROM (VALUES (0), (1)) AS v(id); + +query I +SELECT 10 / id AS __datafusion_extracted_manual +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_1x +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS "__datafusion_extracted_+1" +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_0 +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_01 +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_1 +FROM extracted_alias_names WHERE id > 0; +---- +10 + +statement ok +DROP TABLE extracted_alias_names; + +# Combine id > 0 with a struct-field extraction predicate where both rows match +# s['a'] = 1: leaf extraction pushes get_field(s, 'a') below the filter while +# keeping guarded division above it for both canonical and manual aliases. +statement ok +COPY ( + SELECT column1 AS id, column2 AS s + FROM VALUES (0, {a: 1}), (1, {a: 1}) +) TO 'test_files/scratch/projection_pushdown/extracted_alias_names_struct.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE extracted_alias_names_struct +STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/extracted_alias_names_struct.parquet'; + +query TT +EXPLAIN SELECT 10 / id AS __datafusion_extracted_1 +FROM extracted_alias_names_struct +WHERE id > 0 AND s['a'] = 1; +---- +logical_plan +01)Projection: Int64(10) / extracted_alias_names_struct.id AS __datafusion_extracted_1 +02)--Filter: extracted_alias_names_struct.id > Int64(0) AND __datafusion_extracted_2 = Int64(1) +03)----Projection: get_field(extracted_alias_names_struct.s, Utf8("a")) AS __datafusion_extracted_2, extracted_alias_names_struct.id +04)------TableScan: extracted_alias_names_struct projection=[id, s], partial_filters=[extracted_alias_names_struct.id > Int64(0), get_field(extracted_alias_names_struct.s, Utf8("a")) = Int64(1)] +physical_plan +01)ProjectionExec: expr=[10 / id@0 as __datafusion_extracted_1] +02)--FilterExec: id@1 > 0 AND __datafusion_extracted_2@0 = 1, projection=[id@1] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/extracted_alias_names_struct.parquet]]}, projection=[get_field(s@1, a) as __datafusion_extracted_2, id], file_type=parquet, predicate=id@0 > 0 AND get_field(s@1, a) = 1, pruning_predicate=id_null_count@1 != row_count@2 AND id_max@0 > 0, required_guarantees=[] + +query I +SELECT 10 / id AS __datafusion_extracted_1 +FROM extracted_alias_names_struct +WHERE id > 0 AND s['a'] = 1; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_manual +FROM extracted_alias_names_struct +WHERE id > 0 AND s['a'] = 1; +---- +10 + +statement ok +DROP TABLE extracted_alias_names_struct; + statement ok COPY ( select {f1: 1, f2: 2} as s ) TO 'test_files/scratch/projection_pushdown/test.parquet' From 24dad032d2a6fdb5dcabe0e2ca8e8d8e78c96e30 Mon Sep 17 00:00:00 2001 From: mattsu Date: Thu, 3 Dec 2026 19:13:04 +0900 Subject: [PATCH 3/3] fix: restore alias generator seeding for non-canonical numeric suffixes --- .../optimizer/src/extract_leaf_expressions.rs | 57 ++++++++++++------- .../test_files/projection_pushdown.slt | 17 ++++++ 2 files changed, 55 insertions(+), 19 deletions(-) diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rs index e72d23efeaf40..253651feeb50e 100644 --- a/datafusion/optimizer/src/extract_leaf_expressions.rs +++ b/datafusion/optimizer/src/extract_leaf_expressions.rs @@ -74,27 +74,24 @@ use crate::{OptimizerConfig, OptimizerRule}; /// /// Aliases starting with this prefix are classified as extraction aliases when /// their inner expression is eligible for leaf pushdown -/// ([`ExpressionPlacement::should_push_to_leaves`]). Canonical positive decimal -/// suffixes (`1..usize::MAX`, without leading zeros) are parsed solely to seed -/// [`AliasGenerator`]; user aliases with this prefix that wrap pushable -/// expressions may still be treated as extraction aliases. +/// ([`ExpressionPlacement::should_push_to_leaves`]). Numeric suffixes below +/// `usize::MAX` are parsed solely to seed [`AliasGenerator`]; user aliases with +/// this prefix that wrap pushable expressions may still be treated as +/// extraction aliases. const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted"; -/// Recognizes canonical positive decimal IDs (`1..usize::MAX` without leading -/// zeros) for seeding [`AliasGenerator`] in [`advance_generator_past_existing`]. +/// Parses numeric IDs (`0..usize::MAX`) for seeding [`AliasGenerator`] in +/// [`advance_generator_past_existing`]. /// /// Extraction alias classification uses [`is_extracted_alias`] instead so /// generated `usize::MAX` (and wrapped `0`) aliases are accepted while -/// non-pushable user aliases with canonical names are rejected. +/// non-pushable user aliases with numeric suffixes are rejected. fn extracted_expr_id(name: &str) -> Option { - let suffix = name + let id = name .strip_prefix(EXTRACTED_EXPR_PREFIX)? - .strip_prefix('_')?; - // Integer parsing alone also accepts leading zeros and a leading '+'. - if suffix.starts_with('0') || !suffix.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - let id = suffix.parse::().ok()?; + .strip_prefix('_')? + .parse::() + .ok()?; // update_min_id adds one, so the maximum value has no usable successor. (id < usize::MAX).then_some(id) } @@ -3818,15 +3815,17 @@ mod tests { #[test] fn test_extracted_expr_id_boundaries() { - for id in [1, 42, usize::MAX - 1] { + for id in [0, 1, 42, usize::MAX - 1] { let name = format!("{EXTRACTED_EXPR_PREFIX}_{id}"); assert_eq!(extracted_expr_id(&name), Some(id), "{name}"); } + for (suffix, expected) in [("01", 1), ("0001", 1), ("+1", 1)] { + let name = format!("{EXTRACTED_EXPR_PREFIX}_{suffix}"); + assert_eq!(extracted_expr_id(&name), Some(expected), "{name}"); + } assert_eq!(extracted_expr_id(EXTRACTED_EXPR_PREFIX), None); - let invalid_suffixes = - ["", "0", "01", "0001", "+1", "-1", "1x", " 1", "1 ", "1"] - .map(str::to_owned); + let invalid_suffixes = ["", "-1", "1x", " 1", "1 ", "1"].map(str::to_owned); for suffix in invalid_suffixes .into_iter() .chain([usize::MAX.to_string(), format!("{}0", usize::MAX)]) @@ -3840,7 +3839,8 @@ mod tests { fn test_advance_generator_ignores_invalid_extraction_ids() -> Result<()> { let exprs = [ "0".to_owned(), - "01".to_owned(), + "-1".to_owned(), + "1x".to_owned(), usize::MAX.to_string(), format!("{}0", usize::MAX), ] @@ -3859,6 +3859,25 @@ mod tests { Ok(()) } + #[test] + fn test_advance_generator_seeds_leading_zero_and_plus_ids() -> Result<()> { + for suffix in ["01", "+1"] { + let plan = LogicalPlanBuilder::from(test_table_scan_with_struct()?) + .project(vec![ + lit(99).alias(format!("{EXTRACTED_EXPR_PREFIX}_{suffix}")), + ])? + .build()?; + let alias_generator = AliasGenerator::new(); + advance_generator_past_existing(&plan, &alias_generator)?; + assert_eq!( + alias_generator.next(EXTRACTED_EXPR_PREFIX), + "__datafusion_extracted_2", + "suffix={suffix}" + ); + } + Ok(()) + } + fn inexact_table_scan_with_struct() -> Result { #[derive(Debug)] struct InexactStructTable(arrow::datatypes::SchemaRef); diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index a722ae7b3e311..5b8c8a0bff83a 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2047,6 +2047,23 @@ WHERE id > 0 AND s['a'] = 1; statement ok DROP TABLE extracted_alias_names_struct; +# Leading-zero suffixes like _01 still seed the alias generator past 1, +# avoiding a collision with an existing scan column named __datafusion_extracted_1. +statement ok +CREATE TABLE extracted_alias_seed AS +SELECT column1 AS __datafusion_extracted_1, column2 AS s +FROM VALUES (0, {a: 10}), (1, {a: 20}); + +query I +SELECT 99 AS __datafusion_extracted_01 +FROM extracted_alias_seed +WHERE __datafusion_extracted_1 > 0 AND s['a'] = 20; +---- +99 + +statement ok +DROP TABLE extracted_alias_seed; + statement ok COPY ( select {f1: 1, f2: 2} as s ) TO 'test_files/scratch/projection_pushdown/test.parquet'