diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index c0936eb929b37..160258217ea47 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -14,7 +14,9 @@ use datafusion::datasource::source::DataSourceExec; use datafusion::prelude::{ParquetReadOptions, SessionContext}; use datafusion_common::config::{ConfigOptions, CsvOptions}; use datafusion_common::metadata::FieldMetadata; -use datafusion_common::{JoinSide, JoinType, NullEquality, Result, ScalarValue}; +use datafusion_common::{ + JoinSide, JoinType, NullEquality, Result, ScalarValue, assert_batches_eq, +}; use datafusion_datasource::TableSchemaBuilder; use datafusion_datasource::file_scan_config::FileScanConfigBuilder; use datafusion_execution::object_store::ObjectStoreUrl; @@ -35,6 +37,7 @@ use datafusion_physical_expr_common::sort_expr::{ use datafusion_physical_optimizer::PhysicalOptimizerRule; use datafusion_physical_optimizer::output_requirements::OutputRequirementExec; use datafusion_physical_optimizer::projection_pushdown::ProjectionPushdown; +use datafusion_physical_plan::buffer::BufferExec; use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; use datafusion_physical_plan::coop::CooperativeExec; use datafusion_physical_plan::filter::{FilterExec, FilterExecBuilder}; @@ -43,15 +46,18 @@ use datafusion_physical_plan::joins::{ HashJoinExec, NestedLoopJoinExec, PartitionMode, SortMergeJoinExec, StreamJoinPartitionMode, SymmetricHashJoinExec, }; +use datafusion_physical_plan::limit::GlobalLimitExec; use datafusion_physical_plan::projection::{ProjectionExec, ProjectionExpr, update_expr}; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::sorts::sort::SortExec; use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec}; use datafusion_physical_plan::union::UnionExec; -use datafusion_physical_plan::{ExecutionPlan, displayable}; +use datafusion_physical_plan::{ExecutionPlan, collect, displayable}; use insta::assert_snapshot; + +use crate::physical_optimizer::test_utils::OptimizationTest; use itertools::Itertools; /// Mocked UDF @@ -1973,16 +1979,10 @@ async fn split_declines_hash_repartition() -> Result<()> { true, ), ])); - let config = FileScanConfigBuilder::new( - ObjectStoreUrl::parse("test:///").unwrap(), - Arc::new(ParquetSource::new(Arc::clone(&schema))), - ) - .with_file(PartitionedFile::new("x".to_string(), 100)) - .build(); // Parquet absorbs a leaf projection, so the split would commit here if the // partitioning check did not stop it first. let hash = Arc::new(RepartitionExec::try_new( - DataSourceExec::from_data_source(config), + parquet_scan(&schema), Partitioning::Hash(vec![col("id", &schema)?], 4), )?); @@ -2035,3 +2035,233 @@ async fn split_declines_hash_repartition() -> Result<()> { ); Ok(()) } + +fn parquet_scan(schema: &SchemaRef) -> Arc { + let config = FileScanConfigBuilder::new( + ObjectStoreUrl::parse("test:///").unwrap(), + Arc::new(ParquetSource::new(Arc::clone(schema))), + ) + .with_file(PartitionedFile::new("x".to_string(), 100)) + .build(); + DataSourceExec::from_data_source(config) +} + +fn limit_split_exprs(schema: &SchemaRef) -> Result> { + let leaf: Arc = Arc::new(ScalarFunctionExpr::new( + "get_field", + datafusion_functions::core::get_field(), + vec![ + col("s", schema)?, + Arc::new(Literal::new(ScalarValue::from("value"))), + ], + Arc::new(Field::new("v", DataType::Int64, true)), + Arc::new(ConfigOptions::default()), + )); + Ok(vec![ + ProjectionExpr { + expr: leaf, + alias: "v".to_string(), + }, + ProjectionExpr { + expr: binary( + col("id", schema)?, + Operator::Plus, + Arc::new(Literal::new(ScalarValue::Int64(Some(1)))), + schema, + )?, + alias: "w".to_string(), + }, + ]) +} + +/// A real five-row Parquet file and the scan the planner builds over it, so a +/// hand-built chain above it can be *run*, not only formatted. +async fn five_row_parquet( + dir: &tempfile::TempDir, +) -> Result<(SessionContext, Arc)> { + let path = dir.path().join("leaf_split_rows.parquet"); + let path = path.to_str().expect("temp path is not utf-8"); + let ctx = SessionContext::new(); + ctx.sql(&format!( + "COPY (SELECT column1 AS id, column2 AS s FROM VALUES \ + (1, {{value: 100}}), (2, {{value: 200}}), (3, {{value: 150}}), \ + (4, {{value: 300}}), (5, {{value: 250}})) \ + TO '{path}' STORED AS PARQUET" + )) + .await? + .collect() + .await?; + ctx.register_parquet("t", path, ParquetReadOptions::default()) + .await?; + let scan = ctx.table("t").await?.create_physical_plan().await?; + Ok((ctx, scan)) +} + +/// The marker from #27494: `invoke_with_args` is an `exec_err!`, so it returns +/// rows only if the split put it inside the scan. +fn marker_exprs() -> Vec { + vec![ProjectionExpr { + expr: Arc::new(ScalarFunctionExpr::new( + "file_row_index", + datafusion_functions::core::file_row_index(), + vec![], + Arc::new(Field::new("r", DataType::Int64, true)), + Arc::new(ConfigOptions::default()), + )), + alias: "r".to_string(), + }] +} + +/// Each node in the chain keeps its own `skip` and `fetch` across the rebuild. +/// A lost `skip` comes back as the wrong rows; a lost `fetch` on the +/// `CoalescePartitionsExec` only costs it an early stop, which no row can +/// show, so that one is read back off the rebuilt node instead. +/// +/// Neither shape is reachable from SQL: an `OFFSET` with no `LIMIT` is absorbed +/// by the scan before any limit exists, and the fetch on a +/// `CoalescePartitionsExec` is put there by `LimitPushdown`, which runs after +/// this rule's first pass. +#[tokio::test] +async fn split_keeps_each_chain_node_fetch() -> Result<()> { + let dir = tempfile::tempdir()?; + let (ctx, scan) = five_row_parquet(&dir).await?; + let limit: Arc = + Arc::new(GlobalLimitExec::new(Arc::clone(&scan), 2, None)); + let projection: Arc = + Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); + let optimized = + ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?; + assert_batches_eq!( + [ + "+---+", "| r |", "+---+", "| 2 |", "| 3 |", "| 4 |", "+---+" + ], + &collect(optimized, ctx.task_ctx()).await? + ); + + // The same leaf two nodes down, so one pass has to walk the whole chain. + let coalesce: Arc = + Arc::new(CoalescePartitionsExec::new(scan).with_fetch(Some(4))); + let limit: Arc = + Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); + let optimized = + ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?; + + assert_batches_eq!( + [ + "+---+", "| r |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+" + ], + &collect(Arc::clone(&optimized), ctx.task_ctx()).await? + ); + + // Dropping the coalesce's own fetch costs it an early stop and nothing + // else, so no row above can show it: read it back off the rebuilt node. + let rebuilt_limit = Arc::clone(optimized.children()[0]); + let rebuilt_coalesce = Arc::clone(rebuilt_limit.children()[0]); + let rebuilt_limit = rebuilt_limit + .downcast_ref::() + .expect("the rebuild keeps the node itself, not only its numbers"); + assert_eq!((rebuilt_limit.skip(), rebuilt_limit.fetch()), (1, Some(3))); + assert_eq!(rebuilt_coalesce.fetch(), Some(4)); + Ok(()) +} + +/// A `BufferExec` is not a chain node, but as the *bottom* of the chain it +/// delegates the swap to its own input, so the leaf still reaches the scan in +/// one pass. Both of its inserters run after this rule's first pass — +/// `HashJoinBuffering` before the second, `PushdownSort` after it — and no +/// query in the suite leaves a leaf above one. +#[tokio::test] +async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> { + let dir = tempfile::tempdir()?; + let (ctx, scan) = five_row_parquet(&dir).await?; + let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); + let limit: Arc = + Arc::new(GlobalLimitExec::new(buffer, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); + let optimized = + ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?; + assert_batches_eq!( + [ + "+---+", "| r |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+" + ], + &collect(optimized, ctx.task_ctx()).await? + ); + Ok(()) +} + +/// A `FilterExec` at the bottom of the chain takes the lower projection by +/// holding it over its own input, so the leaf reaches the scan only on this +/// rule's second run. Plain SQL does not reach this: the logical optimizer +/// extracts the leaf first, leaving none on the filter. The shape needs +/// `get_field`'s narrowing, and a `get_field` leaf returns the same rows either +/// way, so unlike the two tests above this one can only pin the plan. +#[tokio::test] +async fn leaf_reaches_the_scan_below_a_filter() -> Result<()> { + // Three columns so the lower projection narrows; with two it does not, and + // `FilterExec` declines before reaching the branch this test is about. + let schema: SchemaRef = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new( + "s", + DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()), + true, + ), + Field::new("k", DataType::Int64, true), + ])); + let predicate = binary( + col("id", &schema)?, + Operator::Gt, + Arc::new(Literal::new(ScalarValue::Int64(Some(0)))), + &schema, + )?; + let filter: Arc = + Arc::new(FilterExec::try_new(predicate, parquet_scan(&schema))?); + let limit: Arc = + Arc::new(GlobalLimitExec::new(filter, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + let first = ProjectionPushdown::new() + .optimize(Arc::clone(&projection), &ConfigOptions::default())?; + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - ProjectionExec: expr=[id@0 as id, get_field(s@1, value) as __datafusion_leaf_0] + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet + " + ); + + assert_snapshot!( + OptimizationTest::new(first, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - ProjectionExec: expr=[id@0 as id, get_field(s@1, value) as __datafusion_leaf_0] + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index a792b4131d43e..155009f7e38a8 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -23,8 +23,10 @@ use datafusion_physical_expr::expressions::{Column, LambdaExpr, LambdaVariable}; use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::{conjunction, split_conjunction}; use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile}; +use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; use datafusion_physical_plan::joins::NestedLoopJoinExec; use datafusion_physical_plan::joins::utils::{ColumnIndex, JoinFilter}; +use datafusion_physical_plan::limit::GlobalLimitExec; use datafusion_physical_plan::projection::{ ProjectionExec, remove_unnecessary_projections, }; @@ -68,11 +70,9 @@ impl PhysicalOptimizerRule for ProjectionPushdown { .map(|t| t.data)?; // Push what can already descend, then split the projections that are - // stuck above a `RepartitionExec`. The split needs no cleanup pass of - // its own: the outer projection it leaves either keeps every expression - // a plain column, and is then no narrower than the widened child, or it - // narrows and holds a computed one. `RepartitionExec` declines both, it - // is not removable because it renames, and nothing else moved. + // stuck above a node that will not take a whole projection. The split + // runs no cleanup pass: an outer projection it leaves narrowing is + // pushed below the host on this rule's second run. let plan = plan.transform_down(remove_unnecessary_projections).data()?; plan.transform_down(|plan| { Ok(match try_split_leaf_projection(&plan)? { @@ -507,6 +507,59 @@ fn leaf_column_name(index: usize) -> String { format!("{LEAF_COLUMN_PREFIX}_{index}") } +/// Returns the input of `node` if the split may place the leaf projection +/// below it. +/// +/// The split gives `node` an input with different columns, so `node` must not +/// reference its input's columns and must output them unchanged, or the outer +/// projection's column indices would point at the wrong columns. The arms are +/// an allowlist: satisfying that is necessary, not sufficient. +/// `LocalLimitExec` satisfies it too but is deliberately not an arm: it is only +/// there before `LimitPushdown` folds its fetch into the scan, and no query in +/// the suite leaves a leaf above one by then. +fn split_host_child(node: &Arc) -> Option<&Arc> { + if let Some(repartition) = node.downcast_ref::() { + // Hash and Range partitioning reference columns by index, which would + // have to be remapped against the rewritten child schema. Round robin + // carries no column references. + if !matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) { + return None; + } + Some(repartition.input()) + } else if let Some(limit) = node.downcast_ref::() { + // A skip pushed into the source wraps the scan in this. + Some(limit.input()) + } else if let Some(coalesce) = node.downcast_ref::() { + // Two or more file groups put this under that limit. + Some(coalesce.input()) + } else { + None + } +} + +/// The hosts between a projection and the child the split places the leaf +/// projection on. +struct SplitHostChain<'a> { + /// Outermost first, so the rebuild walks this in reverse. + hosts: Vec<&'a Arc>, + child: &'a Arc, +} + +/// Walks down from `node` for as long as [`split_host_child`] allows, so that +/// stacked hosts are descended in one go rather than one per pass. +fn split_host_chain(node: &Arc) -> Option> { + let mut hosts = vec![]; + let mut current = node; + while let Some(child) = split_host_child(current) { + hosts.push(current); + current = child; + } + (!hosts.is_empty()).then_some(SplitHostChain { + hosts, + child: current, + }) +} + /// Splits a `ProjectionExec` that mixes leaf expressions with ones that must /// stay in place, moving the leaves into a projection the source absorbs. /// @@ -515,21 +568,23 @@ fn leaf_column_name(index: usize) -> String { /// and stops that projection descending past it, so a `MoveTowardsLeafNodes` /// expression sharing it never reaches the source. Splitting leaves the /// computation above the repartition, still parallelised. +/// +/// A source that pushes a skip down strands those leaves the same way: it wraps +/// its scan in a `GlobalLimitExec` for the skip, which has no +/// `try_swapping_with_projection` override, so no projection descends past it. +/// With more than one file group a `CoalescePartitionsExec` sits under that +/// limit too, so the split walks a chain of such nodes rather than a single +/// one. fn try_split_leaf_projection( plan: &Arc, ) -> Result>> { let Some(projection) = plan.downcast_ref::() else { return Ok(None); }; - let Some(repartition) = projection.input().downcast_ref::() else { + let Some(SplitHostChain { hosts, child }) = split_host_chain(projection.input()) + else { return Ok(None); }; - // Hash and Range partitioning reference columns by index, which would have - // to be remapped against the rewritten child schema. Round robin carries no - // column references, and is what `EnsureRequirements` inserts here. - if !matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) { - return Ok(None); - } let leaves = collect_leaf_exprs(projection.expr())?; if leaves.is_empty() { @@ -540,7 +595,6 @@ fn try_split_leaf_projection( // column used *only* inside an extracted leaf must be dropped, otherwise the // source keeps reading it: for `s['a'] + 1` that would read the whole struct // alongside the extracted field, which is worse than not splitting at all. - let child = repartition.input(); let child_schema = child.schema(); let passthrough_indices = collect_outer_columns(projection.expr(), &leaves)?; let mut lower_exprs = passthrough_indices @@ -561,8 +615,9 @@ fn try_split_leaf_projection( } let lower_projection = ProjectionExec::try_new(lower_exprs, Arc::clone(child))?; - // Only commit the split if the child really absorbs the leaf projection. - // Otherwise this would just add a projection that helps nobody. + // Commit only if the child takes the lower projection. A `Some` does not + // always mean the source absorbed it: `FilterExec` takes it by holding it + // over its own input, so the scan narrows on this rule's second run. let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else { return Ok(None); }; @@ -583,18 +638,21 @@ fn try_split_leaf_projection( }) .collect::>>()?; - // The child gained the leaf columns, so the repartition's properties have to - // be recomputed rather than carried over. - let new_repartition = Arc::clone(projection.input()).replace_children( - vec![new_child], - ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), - )?; + // The child gained the leaf columns, so every host's properties have to be + // recomputed rather than carried over. Innermost host first. + let mut new_host = new_child; + for host in hosts.iter().rev() { + new_host = Arc::clone(host).replace_children( + vec![new_host], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } // `try_new` would derive the output schema from the expressions alone and // drop the metadata the planner set, which `schema_check` then rejects. Ok(Some(Arc::new( ProjectionExec::try_new_with_schema_metadata( new_exprs, - new_repartition, + new_host, projection.schema().as_ref(), )?, ))) diff --git a/datafusion/sqllogictest/test_files/file_row_index.slt b/datafusion/sqllogictest/test_files/file_row_index.slt index 45ccb38a8fbde..d059a23ad651e 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -314,6 +314,208 @@ SELECT file_row_index() + 1, column1 FROM parquet_table ORDER BY column1 # `RESET` restores the global default rather than the harness value, which the # harness rejects as leftover configuration. +# A leaf expression must also reach the scan when the source pushes an +# `OFFSET` down. Every value query below errors out without that. + +# Every `OFFSET` below sets a skip that differs from the fetch, so swapped +# numbers would show. + +# The marker is BARE here, and alone in its projection. +query I +SELECT r FROM (SELECT file_row_index() AS r FROM parquet_table OFFSET 1 LIMIT 3) +ORDER BY r +---- +1 +2 +3 + +# The marker wrapped in arithmetic. +query I +SELECT r FROM (SELECT file_row_index() + 1 AS r FROM parquet_table OFFSET 1 LIMIT 3) +ORDER BY r +---- +2 +3 +4 + +# A computed sibling in the same projection, which stays above the limit. +query II +SELECT r, w FROM ( + SELECT file_row_index() AS r, column1 + 1 AS w FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY r +---- +1 21 +2 31 +3 41 + +# The sibling marker behaves the same way. Compared against a predicate rather +# than printed, so the expectation does not depend on the absolute file path. +query B +SELECT n FROM ( + SELECT length(input_file_name()) > 0 AS n FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY n +---- +true +true +true + +# Not specific to arithmetic: any enclosing expression has the same effect. +query T +SELECT t FROM ( + SELECT arrow_typeof(file_row_index()) AS t FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY t +---- +Int64 +Int64 +Int64 + +# The plan behind the values above: the marker is rewritten inside the scan and +# the limit keeps both of its numbers, in that order. +query TT +EXPLAIN SELECT file_row_index() AS r FROM parquet_table OFFSET 1 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1 +04)------TableScan: parquet_table projection=[], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as r] +02)--GlobalLimitExec: skip=1, fetch=3 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], limit=4, file_type=parquet + +# `OFFSET 0` is the control: with no skip there is nothing to push down, so +# this shape never depended on the split. +query TT +EXPLAIN SELECT file_row_index() AS r FROM parquet_table OFFSET 0 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1 +04)------TableScan: parquet_table projection=[], fetch=3 +physical_plan DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as r], limit=3, file_type=parquet + +# `OFFSET` with no `LIMIT` is the other control: the scan absorbs the +# projection before any limit exists, so the split is never consulted. +query TT +EXPLAIN SELECT file_row_index() AS r FROM parquet_table OFFSET 2 +---- +logical_plan +01)Limit: skip=2, fetch=None +02)--Projection: file_row_index() AS r +03)----TableScan: parquet_table projection=[] +physical_plan +01)GlobalLimitExec: skip=2, fetch=None +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as r], file_type=parquet + +# A repartition above the limit must not disturb the split: the outer +# projection keeps a `KeepInPlace` expression, so a `RepartitionExec` is +# inserted beneath it, and the extracted leaf sits below that with the limit +# still between it and the scan. `batch_size` is below the row count again, for +# the reason given above. + +statement ok +SET datafusion.execution.batch_size = 2; + +query II +SELECT r, w FROM ( + SELECT file_row_index() AS r, column1 + 1 AS w FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY r +---- +1 21 +2 31 +3 41 + +query TT +EXPLAIN SELECT file_row_index() AS r, column1 + 1 AS w FROM parquet_table OFFSET 1 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r, CAST(parquet_table.column1 AS Int64) + Int64(1) AS w +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1, parquet_table.column1 +04)------TableScan: parquet_table projection=[column1], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_extracted_1@0 as r, CAST(column1@1 AS Int64) + 1 as w] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----ProjectionExec: expr=[__datafusion_leaf_0@1 as __datafusion_extracted_1, column1@0 as column1] +04)------GlobalLimitExec: skip=1, fetch=3 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[column1, CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], limit=4, file_type=parquet + +statement ok +SET datafusion.execution.batch_size = 8192; + +# More than one file group puts a second node between the limit and the scan, +# so the leaf has to descend past two rather than one. + +statement ok +COPY (VALUES (10), (20), (30)) +TO 'test_files/scratch/file_row_index/offset_two_files/a.parquet' +STORED AS PARQUET; + +statement ok +COPY (VALUES (40), (50), (60)) +TO 'test_files/scratch/file_row_index/offset_two_files/b.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE offset_two_files(column1 int) +STORED AS PARQUET +LOCATION 'test_files/scratch/file_row_index/offset_two_files/'; + +query TT +EXPLAIN SELECT file_row_index() AS r FROM offset_two_files OFFSET 1 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1 +04)------TableScan: offset_two_files projection=[], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as r] +02)--GlobalLimitExec: skip=1, fetch=3 +03)----CoalescePartitionsExec: fetch=4 +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/offset_two_files/a.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/offset_two_files/b.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], limit=4, file_type=parquet + +# Which rows survive the skip depends on the partition merge order, which is +# not guaranteed, so this counts them instead of listing them. `count(r)` and +# not `count(*)`, which would let `r` be dropped and never evaluated. +query I +SELECT count(r) FROM ( + SELECT file_row_index() AS r FROM offset_two_files OFFSET 1 LIMIT 3 +) +---- +3 + +statement ok +DROP TABLE offset_two_files; + +# Not a parquet-only defect: any listing format strands the leaf the same way, +# and every other query in this file is parquet. `file_row_index()` is itself +# parquet-only, so this uses `input_file_name()`, which errors before the fix. + +statement ok +COPY (VALUES (10), (20), (30), (40), (50)) +TO 'test_files/scratch/file_row_index/offset_json/data.json' +STORED AS JSON; + +statement ok +CREATE EXTERNAL TABLE offset_json(column1 int) +STORED AS JSON +LOCATION 'test_files/scratch/file_row_index/offset_json/'; + +query B +SELECT n FROM ( + SELECT length(input_file_name()) > 0 AS n FROM offset_json OFFSET 1 LIMIT 3 +) ORDER BY n +---- +true +true +true + +statement ok +DROP TABLE offset_json; + statement ok DROP TABLE parquet_table;