diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index a792b4131d43e..a217571bcfe57 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -8,6 +8,7 @@ //! projection reaches a source, it can even disappear from the plan entirely. use crate::PhysicalOptimizerRule; +use crate::output_requirements::OutputRequirementExec; use arrow::datatypes::{Fields, Schema, SchemaRef}; use datafusion_common::alias::AliasGenerator; use std::collections::HashSet; @@ -21,16 +22,24 @@ use datafusion_common::{JoinSide, JoinType, Result, internal_datafusion_err}; use datafusion_expr::ExpressionPlacement; use datafusion_physical_expr::expressions::{Column, LambdaExpr, LambdaVariable}; use datafusion_physical_expr::projection::ProjectionExpr; +use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_expr::{conjunction, split_conjunction}; use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile}; -use datafusion_physical_plan::joins::NestedLoopJoinExec; +use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; +use datafusion_physical_plan::filter::FilterExec; use datafusion_physical_plan::joins::utils::{ColumnIndex, JoinFilter}; +use datafusion_physical_plan::joins::{HashJoinExec, NestedLoopJoinExec}; +use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; use datafusion_physical_plan::projection::{ ProjectionExec, remove_unnecessary_projections, }; 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::union::UnionExec; use datafusion_physical_plan::{ - ChildrenPropertiesMode, ExecutionPlan, Partitioning, ReplaceChildrenOptions, + ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties, Partitioning, + ReplaceChildrenOptions, }; /// This rule inspects `ProjectionExec`'s in the given physical plan and tries to @@ -68,19 +77,16 @@ 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 `RepartitionExec`. This needs no cleanup pass + // after it: a split that only prunes settles the subtree it changes. The + // outer projection that a split leaves either keeps every expression a + // plain column, and is then no narrower than the new child, or it narrows + // and holds a computed one. `RepartitionExec` declines both. let plan = plan.transform_down(remove_unnecessary_projections).data()?; - plan.transform_down(|plan| { - Ok(match try_split_leaf_projection(&plan)? { - Some(new_plan) => Transformed::yes(new_plan), - None => Transformed::no(plan), - }) - }) - .data() + // `OutputRequirementExec` declares the ordering that the query needs. Without + // one at the root, the caller may rely on any ordering of the output. + let order_matters = !plan.is::(); + split_projections(plan, order_matters) } fn name(&self) -> &str { @@ -507,16 +513,82 @@ fn leaf_column_name(index: usize) -> String { format!("{LEAF_COLUMN_PREFIX}_{index}") } -/// Splits a `ProjectionExec` that mixes leaf expressions with ones that must -/// stay in place, moving the leaves into a projection the source absorbs. +/// Calls [`try_split_projection`] on each node of `plan`, from the root down. +/// +/// `order_matters` is true if something above `plan` can rely on its ordering. +#[cfg_attr(feature = "recursive_protection", recursive::recursive)] +fn split_projections( + plan: Arc, + order_matters: bool, +) -> Result> { + let plan = try_split_projection(&plan, order_matters)?.unwrap_or(plan); + + let required = plan.required_input_ordering(); + let only_declared = relies_only_on_declared_ordering(&plan); + let mut changed = false; + let mut children = vec![]; + for (child, required) in plan.children().into_iter().zip(required) { + let order_matters = order_matters || required.is_some() || !only_declared; + // A sort replaces the ordering of its input, unless the input is sorted. + let order_matters = match plan.downcast_ref::() { + Some(sort) => { + order_matters + && child + .equivalence_properties() + .ordering_satisfy(sort.expr().clone())? + } + None => order_matters, + }; + let new_child = split_projections(Arc::clone(child), order_matters)?; + changed |= !Arc::ptr_eq(child, &new_child); + children.push(new_child); + } + if !changed { + return Ok(plan); + } + plan.replace_children( + children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) +} + +/// Returns true for operators known to need no ordering of their input beyond +/// `required_input_ordering`. +/// +/// Any other operator can need one that it does not declare. `PartialSortExec` +/// does, and `AggregateExec` chooses its mode from the ordering of its input. +/// Nothing detects the wrong rows that a lost ordering then gives. +fn relies_only_on_declared_ordering(plan: &Arc) -> bool { + plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() +} + +/// Splits a `ProjectionExec` that a round robin `RepartitionExec` keeps away +/// from its source. The lower part extracts the leaf expressions and prunes the +/// columns that nothing above reads. The upper part keeps the computation. /// /// `benefits_from_input_partitioning` is true as soon as any expression is /// `KeepInPlace`, which both inserts a `RepartitionExec` below the projection /// 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. -fn try_split_leaf_projection( +/// expression sharing it never reaches the source. The same projection can leave +/// a column unread that only a predicate the source absorbed still needs. +/// Splitting leaves the computation above the repartition, still parallelised. +/// +/// The child of the repartition may decline the lower part. A lower part that +/// only prunes then stays below the repartition as a `ProjectionExec`. +fn try_split_projection( plan: &Arc, + order_matters: bool, ) -> Result>> { let Some(projection) = plan.downcast_ref::() else { return Ok(None); @@ -532,17 +604,96 @@ fn try_split_leaf_projection( } let leaves = collect_leaf_exprs(projection.expr())?; - if leaves.is_empty() { + + let child = repartition.input(); + let passthrough_indices = + choose_passthrough(plan, projection, child, &leaves, order_matters)?; + // The lower projection would extract nothing and prune nothing. The result + // would be the same plan with an identity projection added. + if leaves.is_empty() && passthrough_indices.len() == child.schema().fields().len() { return Ok(None); } + let lower_projection = lower_projection(child, &leaves, &passthrough_indices)?; + + let new_child = match child.try_swapping_with_projection(&lower_projection)? { + Some(new_child) => new_child, + // A sort or a window declines a projection that drops its key, but the key + // need not cross the repartition. Dropping a column costs almost nothing. + None if leaves.is_empty() => Arc::new(lower_projection), + // A leaf extracted here would no longer run in parallel. + None => return Ok(None), + }; + let new_child = if leaves.is_empty() { + new_child + .transform_down(remove_unnecessary_projections) + .data()? + } else { + new_child + }; + let split = + rebuild_split(projection, &leaves, &passthrough_indices, child, new_child)?; + // The columns were chosen before the lower projection moved, and the operator + // that absorbs it recomputes its own properties. + Ok((keeps_equivalences(plan, &split)? + && (!order_matters || keeps_orderings(plan, &split)?)) + .then_some(split)) +} + +/// Returns the sorted indices of the `child` columns that a split passes through. +fn choose_passthrough( + plan: &Arc, + projection: &ProjectionExec, + child: &Arc, + leaves: &[Arc], + order_matters: bool, +) -> Result> { // Pass through only the child columns the outer expressions still need. A // 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 mut indices = collect_outer_columns(projection.expr(), leaves)?; + let properties = plan.equivalence_properties(); + let has_ordering = order_matters && !properties.oeq_class().is_empty(); + if !has_ordering && properties.eq_group().is_empty() { + return Ok(indices); + } + let lower_projection = Arc::new(lower_projection(child, leaves, &indices)?); + let split = rebuild_split(projection, leaves, &indices, child, lower_projection)?; + + // A property of the output can depend on a column that no expression reads. + // With `c = a + b`, input sorted by `c` sorts `a + b`, and a constant `c` makes + // `a + b` constant. An ancestor may rely on either, so also pass through the + // columns that the lost property can come from. + let child_properties = child.equivalence_properties(); + let mut add_columns = |expr: &Arc| { + indices.extend(collect_columns(expr).iter().map(|column| column.index())); + }; + if !keeps_equivalences(plan, &split)? { + for class in child_properties.eq_group().iter() { + class.iter().for_each(&mut add_columns); + } + } + if order_matters && !keeps_orderings(plan, &split)? { + for ordering in child_properties.oeq_class().iter() { + for sort_expr in ordering.iter() { + add_columns(&sort_expr.expr); + } + } + } + indices.sort_unstable(); + indices.dedup(); + Ok(indices) +} + +/// Returns the lower part of a split, which outputs the `child` columns at +/// `passthrough_indices` and then `leaves`. +fn lower_projection( + child: &Arc, + leaves: &[Arc], + passthrough_indices: &[usize], +) -> Result { let child_schema = child.schema(); - let passthrough_indices = collect_outer_columns(projection.expr(), &leaves)?; let mut lower_exprs = passthrough_indices .iter() .map(|&idx| { @@ -559,14 +710,19 @@ fn try_split_leaf_projection( alias: leaf_column_name(index), }); } - 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. - let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else { - return Ok(None); - }; + ProjectionExec::try_new(lower_exprs, Arc::clone(child)) +} +/// Returns `projection` over its repartition of `new_child`, which outputs what +/// [`lower_projection`] of `child` does. +fn rebuild_split( + projection: &ProjectionExec, + leaves: &[Arc], + passthrough_indices: &[usize], + child: &Arc, + new_child: Arc, +) -> Result> { + let child_schema = child.schema(); let new_exprs = projection .expr() .iter() @@ -574,8 +730,8 @@ fn try_split_leaf_projection( Ok(ProjectionExpr { expr: rewrite_outer_expr( Arc::clone(&proj_expr.expr), - &leaves, - &passthrough_indices, + leaves, + passthrough_indices, child_schema.fields().len(), )?, alias: proj_expr.alias.clone(), @@ -583,7 +739,7 @@ fn try_split_leaf_projection( }) .collect::>>()?; - // The child gained the leaf columns, so the repartition's properties have to + // The child's columns changed, 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], @@ -591,13 +747,62 @@ fn try_split_leaf_projection( )?; // `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, - projection.schema().as_ref(), - )?, - ))) + Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata( + new_exprs, + new_repartition, + projection.schema().as_ref(), + )?)) +} + +/// Returns true if every constant and every equality that `old_plan` knows about +/// its output also holds for `new_plan`. +/// +/// Sorts and repartitions keep both, so an ancestor can rely on them even across +/// an operator that destroys the ordering. Expressions that hold a leaf are not +/// compared: `s['v'] + 1 AS v, s` equates `v` with `s['v'] + 1`, and no split that +/// extracts `s['v']` can keep that. +fn keeps_equivalences( + old_plan: &Arc, + new_plan: &Arc, +) -> Result { + let old_group = old_plan.equivalence_properties().eq_group(); + let new_group = new_plan.equivalence_properties().eq_group(); + for class in old_group.iter() { + let mut first = None; + for expr in class.iter() { + let holds_leaf = expr.exists(|node| { + Ok(node.placement() == ExpressionPlacement::MoveTowardsLeafNodes) + })?; + if holds_leaf { + continue; + } + let first = first.get_or_insert(expr); + let constant = old_group.is_expr_constant(expr); + if !new_group.exprs_equal(first, expr) + || (constant.is_some() && new_group.is_expr_constant(expr) != constant) + { + return Ok(false); + } + } + } + Ok(true) +} + +/// Returns true if `new_plan` satisfies every output ordering of `old_plan`. +/// +/// `RepartitionExec::preserve_order` is not enough to decide this, because a +/// repartition of a single input partition keeps the order without it. +fn keeps_orderings( + old_plan: &Arc, + new_plan: &Arc, +) -> Result { + let new_properties = new_plan.equivalence_properties(); + for ordering in old_plan.equivalence_properties().oeq_class().iter() { + if !new_properties.ordering_satisfy(ordering.iter().cloned())? { + return Ok(false); + } + } + Ok(true) } /// Collects the distinct outermost [`ExpressionPlacement::MoveTowardsLeafNodes`] @@ -686,7 +891,7 @@ fn rewrite_outer_expr( return Ok(Transformed::yes(Arc::new(remapped) as Arc)); } } - // The split widens the input, which moves the lambda parameters indexed + // The split changes the input width, which moves the lambda parameters indexed // after it; see `remap_filter_expr`. if let Some(variable) = node.downcast_ref::() && old_input_len != new_input_len @@ -704,15 +909,144 @@ mod test { use super::*; use arrow::datatypes::{DataType, Field, FieldRef, Schema}; use datafusion_expr_common::operator::Operator; + use datafusion_functions::core::get_field; use datafusion_functions::math::random; - use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::{binary, lit}; + use datafusion_physical_expr::{Distribution, ScalarFunctionExpr}; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; + use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr; use datafusion_physical_plan::displayable; use datafusion_physical_plan::empty::EmptyExec; + use datafusion_physical_plan::sorts::partial_sort::PartialSortExec; use insta::assert_snapshot; use std::sync::Arc; + // Unit tests, because no SQL is known that plans these two shapes. + fn split_over( + child: impl FnOnce(Arc) -> Arc, + partitioning: Partitioning, + ) -> Result { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::Int32, false), + ])); + let expr = binary( + Arc::new(Column::new("b", 1)), + Operator::Plus, + lit(1), + &schema, + )?; + let source = child(Arc::new(EmptyExec::new(schema).with_partitions(2))); + let repartition = Arc::new(RepartitionExec::try_new(source, partitioning)?); + let plan = Arc::new(ProjectionExec::try_new([(expr, "v".into())], repartition)?); + let plan = ProjectionPushdown::new().optimize(plan, &ConfigOptions::default())?; + Ok(displayable(plan.as_ref()).indent(false).to_string()) + } + + #[test] + fn split_prunes_below_coalesce() -> Result<()> { + let plan = split_over( + |input| Arc::new(CoalescePartitionsExec::new(input)), + Partitioning::RoundRobinBatch(4), + )?; + assert_snapshot!(plan, @r" + ProjectionExec: expr=[b@0 + 1 as v] + RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 + CoalescePartitionsExec + ProjectionExec: expr=[b@1 as b] + EmptyExec + "); + Ok(()) + } + + #[test] + fn split_does_not_cross_hash_repartition() -> Result<()> { + // The inner projection would absorb the pruning one. + let plan = split_over( + |input| { + let columns = + [("b", 1, "a"), ("a", 0, "b")].map(|(name, index, alias)| { + let expr: Arc = + Arc::new(Column::new(name, index)); + (expr, alias.to_string()) + }); + Arc::new(ProjectionExec::try_new(columns, input).unwrap()) + }, + Partitioning::Hash(vec![Arc::new(Column::new("a", 0))], 4), + )?; + assert_snapshot!(plan, @r" + ProjectionExec: expr=[b@1 + 1 as v] + RepartitionExec: partitioning=Hash([a@0], 4), input_partitions=2 + ProjectionExec: expr=[b@1 as a, a@0 as b] + EmptyExec + "); + Ok(()) + } + + /// `PartialSortExec` relies on the order of its input, but does not declare it. + #[test] + fn split_keeps_undeclared_ordering() -> Result<()> { + let v = Field::new("v", DataType::Int32, false); + let schema = Arc::new(Schema::new(vec![ + Field::new("c", DataType::Int32, false), + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::Int32, false), + Field::new_struct("s", vec![v], false), + ])); + let column = |name: &str, index| -> Arc { + Arc::new(Column::new(name, index)) + }; + let sum = binary(column("a", 1), Operator::Plus, column("b", 2), &schema)?; + let predicate = binary(column("c", 0), Operator::Eq, Arc::clone(&sum), &schema)?; + let get_v = Arc::new(ScalarFunctionExpr::try_new( + get_field(), + vec![column("s", 3), lit("v")], + &schema, + Arc::new(ConfigOptions::default()), + )?); + let leaf = binary(get_v, Operator::Plus, lit(1), &schema)?; + + let sort_c = [PhysicalSortExpr::new_default(column("c", 0))].into(); + let plan = Arc::new(SortExec::new(sort_c, Arc::new(EmptyExec::new(schema)))); + let plan = Arc::new(FilterExec::try_new(predicate, plan)?); + // Absorbs the lower part of the split. The rename keeps it from being removed. + let exprs = [("c", "c2"), ("a", "a"), ("b", "b"), ("s", "s")] + .into_iter() + .enumerate() + .map(|(index, (name, alias))| (column(name, index), alias.to_string())); + let plan = Arc::new(ProjectionExec::try_new(exprs, plan)?); + let partitioning = Partitioning::RoundRobinBatch(4); + let plan = Arc::new(RepartitionExec::try_new(plan, partitioning)?); + let exprs = [(sum, "k"), (column("a", 1), "a"), (leaf, "v")] + .map(|(expr, alias)| (expr, alias.to_string())); + let plan = Arc::new(ProjectionExec::try_new(exprs, plan)?); + let sort_k = [("k", 0), ("a", 1)] + .map(|(name, index)| PhysicalSortExpr::new_default(column(name, index))); + let plan = + PartialSortExec::new(sort_k.into(), plan, 1).with_preserve_partitioning(true); + + // The query needs no ordering, so only the `PartialSortExec` can protect it. + let plan = OutputRequirementExec::new( + Arc::new(plan), + None, + Distribution::UnspecifiedDistribution, + None, + ); + let plan = ProjectionPushdown::new() + .optimize(Arc::new(plan), &ConfigOptions::default())?; + assert_snapshot!(displayable(plan.as_ref()).indent(false), @r" + OutputRequirementExec: order_by=[], dist_by=Unspecified + PartialSortExec: expr=[k@0 ASC, a@1 ASC], common_prefix_length=[1] + ProjectionExec: expr=[a@1 + b@2 as k, a@1 as a, __datafusion_leaf_0@3 + 1 as v] + RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true + ProjectionExec: expr=[c@0 as c2, a@1 as a, b@2 as b, get_field(s@3, v) as __datafusion_leaf_0] + FilterExec: c@0 = a@1 + b@2 + SortExec: expr=[c@0 ASC], preserve_partitioning=[false] + EmptyExec + "); + Ok(()) + } + #[tokio::test] async fn no_computation_does_not_project() -> Result<()> { let (left_schema, right_schema) = create_simple_schemas(); diff --git a/datafusion/sqllogictest/test_files/file_row_index.slt b/datafusion/sqllogictest/test_files/file_row_index.slt index 45ccb38a8fbde..13656362b2da7 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -152,7 +152,7 @@ statement ok DROP TABLE parquet_two_files; # A leaf expression must still reach the scan when its projection also holds a -# `KeepInPlace` one; see `try_split_leaf_projection` in +# `KeepInPlace` one; see `try_split_projection` in # `datafusion/physical-optimizer/src/projection_pushdown.rs`. These need a # repartition, so `batch_size` is below the row count: do not raise it and do # not add a bare `LIMIT`, or the queries pass against broken code. diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..f631d8962b36d 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2676,7 +2676,7 @@ statement ok DROP TABLE duplicate_alias; # A leaf expression must still reach the scan when its projection also holds a -# `KeepInPlace` expression. See `try_split_leaf_projection` in +# `KeepInPlace` expression. See `try_split_projection` in # `datafusion/physical-optimizer/src/projection_pushdown.rs` for why that used # to be impossible. # @@ -2864,6 +2864,848 @@ physical_plan statement ok DROP TABLE leaf_split_mem; +# A scan must not output the columns that only its pushed-down predicate reads. +# The `RepartitionExec` below a computed projection must not keep them alive. +# https://github.com/apache/datafusion/issues/27776 +# This query and its plan come from https://github.com/apache/datafusion/pull/27777. +query TT +EXPLAIN SELECT s['value'] + 1 AS v FROM leaf_split WHERE id > 2; +---- +logical_plan +01)Projection: __datafusion_extracted_1 + Int64(1) AS v +02)--Filter: leaf_split.id > Int64(2) +03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1, leaf_split.id +04)------TableScan: leaf_split projection=[id, s], partial_filters=[leaf_split.id > Int64(2)] +physical_plan +01)ProjectionExec: expr=[__datafusion_extracted_1@0 + 1 as v] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1], file_type=parquet, predicate=id@0 > 2, pruning_predicate=id_null_count@1 != row_count@2 AND id_max@0 > 2, required_guarantees=[] + +query I rowsort +SELECT s['value'] + 1 AS v FROM leaf_split WHERE id > 2; +---- +151 +251 +301 + +statement ok +COPY ( + SELECT value AS timestamp, value * 3 AS period, value * 7 AS val, + named_struct('name', 'namespace', 'unused', value) AS attrs + FROM range(0, 6) +) TO 'test_files/scratch/projection_pushdown/predicate_only.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE predicate_only STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/predicate_only.parquet'; + +query TT +EXPLAIN SELECT val * period AS result FROM predicate_only +WHERE timestamp >= 0 AND lower(attrs['name']) = 'namespace'; +---- +logical_plan +01)Projection: predicate_only.val * predicate_only.period AS result +02)--Filter: predicate_only.timestamp >= Int64(0) AND lower(__datafusion_extracted_1) = Utf8("namespace") +03)----Projection: get_field(predicate_only.attrs, Utf8("name")) AS __datafusion_extracted_1, predicate_only.timestamp, predicate_only.period, predicate_only.val +04)------TableScan: predicate_only projection=[timestamp, period, val, attrs], partial_filters=[predicate_only.timestamp >= Int64(0), lower(get_field(predicate_only.attrs, Utf8("name"))) = Utf8("namespace")] +physical_plan +01)ProjectionExec: expr=[val@1 * period@0 as result] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/predicate_only.parquet]]}, projection=[period, val], file_type=parquet, predicate=timestamp@0 >= 0 AND lower(get_field(attrs@3, name)) = namespace, pruning_predicate=timestamp_null_count@1 != row_count@2 AND timestamp_max@0 >= 0, required_guarantees=[] + +query I rowsort +SELECT val * period AS result FROM predicate_only +WHERE timestamp >= 0 AND lower(attrs['name']) = 'namespace'; +---- +0 +189 +21 +336 +525 +84 + +# The same without a struct. +query TT +EXPLAIN SELECT val * period AS result FROM predicate_only WHERE timestamp >= 2; +---- +logical_plan +01)Projection: predicate_only.val * predicate_only.period AS result +02)--Filter: predicate_only.timestamp >= Int64(2) +03)----TableScan: predicate_only projection=[timestamp, period, val], partial_filters=[predicate_only.timestamp >= Int64(2)] +physical_plan +01)ProjectionExec: expr=[val@1 * period@0 as result] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/predicate_only.parquet]]}, projection=[period, val], file_type=parquet, predicate=timestamp@0 >= 2, pruning_predicate=timestamp_null_count@1 != row_count@2 AND timestamp_max@0 >= 2, required_guarantees=[] + +query I rowsort +SELECT val * period AS result FROM predicate_only WHERE timestamp >= 2; +---- +189 +336 +525 +84 + +# A projection as wide as its input can still leave an input column unread. +query TT +EXPLAIN SELECT val, val AS val2, period + 1 AS p FROM predicate_only WHERE timestamp >= 2; +---- +logical_plan +01)Projection: predicate_only.val, predicate_only.val AS val2, predicate_only.period + Int64(1) AS p +02)--Filter: predicate_only.timestamp >= Int64(2) +03)----TableScan: predicate_only projection=[timestamp, period, val], partial_filters=[predicate_only.timestamp >= Int64(2)] +physical_plan +01)ProjectionExec: expr=[val@1 as val, val@1 as val2, period@0 + 1 as p] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/predicate_only.parquet]]}, projection=[period, val], file_type=parquet, predicate=timestamp@0 >= 2, pruning_predicate=timestamp_null_count@1 != row_count@2 AND timestamp_max@0 >= 2, required_guarantees=[] + +query III rowsort +SELECT val, val AS val2, period + 1 AS p FROM predicate_only WHERE timestamp >= 2; +---- +14 14 7 +21 21 10 +28 28 13 +35 35 16 + +# A filter that the scan absorbs only in part. `FilterExec` keeps its own input, +# so `timestamp`, which only the absorbed conjunct reads, still crosses the +# repartition. +query TT +EXPLAIN SELECT val * period AS k FROM predicate_only WHERE timestamp >= 2 AND attrs IS DISTINCT FROM named_struct('name', 'x', 'unused', 1); +---- +logical_plan +01)Projection: predicate_only.val * predicate_only.period AS k +02)--Filter: predicate_only.timestamp >= Int64(2) AND predicate_only.attrs IS DISTINCT FROM Struct({name:x,unused:1}) +03)----TableScan: predicate_only projection=[timestamp, period, val, attrs], partial_filters=[predicate_only.timestamp >= Int64(2), predicate_only.attrs IS DISTINCT FROM Struct({name:x,unused:1})] +physical_plan +01)ProjectionExec: expr=[val@0 * period@1 as k] +02)--FilterExec: attrs@3 IS DISTINCT FROM {name:x,unused:1}, projection=[val@2, period@1] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/predicate_only.parquet]]}, projection=[timestamp, period, val, attrs], file_type=parquet, predicate=timestamp@0 >= 2, pruning_predicate=timestamp_null_count@1 != row_count@2 AND timestamp_max@0 >= 2, required_guarantees=[] + +query I rowsort +SELECT val * period AS k FROM predicate_only WHERE timestamp >= 2 AND attrs IS DISTINCT FROM named_struct('name', 'x', 'unused', 1); +---- +189 +336 +525 +84 + +# The input is sorted by two columns and the output only by the first. `val` can +# still be pruned, because the output keeps its ordering without it. +statement ok +COPY (SELECT * FROM predicate_only ORDER BY timestamp, val) +TO 'test_files/scratch/projection_pushdown/two_keys.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE two_keys STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/two_keys.parquet' +WITH ORDER (timestamp ASC, val ASC); + +query TT +EXPLAIN SELECT timestamp, timestamp + period AS k FROM two_keys WHERE val > 1 ORDER BY timestamp; +---- +logical_plan +01)Sort: two_keys.timestamp ASC NULLS LAST +02)--Projection: two_keys.timestamp, two_keys.timestamp + two_keys.period AS k +03)----Filter: two_keys.val > Int64(1) +04)------TableScan: two_keys projection=[timestamp, period, val], partial_filters=[two_keys.val > Int64(1)] +physical_plan +01)SortPreservingMergeExec: [timestamp@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[timestamp@0 as timestamp, timestamp@0 + period@1 as k] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/two_keys.parquet]]}, projection=[timestamp, period], output_ordering=[timestamp@0 ASC NULLS LAST], file_type=parquet, predicate=val@2 > 1, pruning_predicate=val_null_count@1 != row_count@2 AND val_max@0 > 1, required_guarantees=[] + +query II +SELECT timestamp, timestamp + period AS k FROM two_keys WHERE val > 1 ORDER BY timestamp; +---- +1 4 +2 8 +3 12 +4 16 +5 20 + +statement ok +DROP TABLE two_keys; + +# No input column is read. The scan must still output the matching row count. +query TT +EXPLAIN SELECT random() >= 0 AS b FROM predicate_only WHERE timestamp >= 2; +---- +logical_plan +01)Projection: random() >= Float64(0) AS b +02)--Filter: predicate_only.timestamp >= Int64(2) +03)----TableScan: predicate_only projection=[timestamp], partial_filters=[predicate_only.timestamp >= Int64(2)] +physical_plan +01)ProjectionExec: expr=[random() >= 0 as b] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/predicate_only.parquet]]}, file_type=parquet, predicate=timestamp@0 >= 2, pruning_predicate=timestamp_null_count@1 != row_count@2 AND timestamp_max@0 >= 2, required_guarantees=[] + +query B +SELECT random() >= 0 AS b FROM predicate_only WHERE timestamp >= 2; +---- +true +true +true +true + +# Every column is read, so there is nothing to prune. +query TT +EXPLAIN SELECT timestamp + val * period AS result FROM predicate_only WHERE timestamp >= 2; +---- +logical_plan +01)Projection: predicate_only.timestamp + predicate_only.val * predicate_only.period AS result +02)--Filter: predicate_only.timestamp >= Int64(2) +03)----TableScan: predicate_only projection=[timestamp, period, val], partial_filters=[predicate_only.timestamp >= Int64(2)] +physical_plan +01)ProjectionExec: expr=[timestamp@0 + val@2 * period@1 as result] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/predicate_only.parquet]]}, projection=[timestamp, period, val], file_type=parquet, predicate=timestamp@0 >= 2, pruning_predicate=timestamp_null_count@1 != row_count@2 AND timestamp_max@0 >= 2, required_guarantees=[] + +statement ok +DROP TABLE predicate_only; + +# A window does not absorb a pruning projection. The projection stays between the +# window and the repartition, so `a` does not cross it. +statement ok +CREATE TABLE window_mm AS SELECT value AS a FROM range(0, 10); + +query TT +EXPLAIN SELECT rn * 2 FROM (SELECT a, row_number() OVER (ORDER BY a) AS rn FROM window_mm); +---- +logical_plan +01)Projection: CAST(row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS Decimal128(20, 0)) * Decimal128(2,20,0) AS rn * Int64(2) +02)--WindowAggr: windowExpr=[[row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]] +03)----TableScan: window_mm projection=[a] +physical_plan +01)ProjectionExec: expr=[CAST(row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@0 AS Decimal128(20, 0)) * 2 as rn * Int64(2)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +03)----ProjectionExec: expr=[row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@1 as row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW] +04)------BoundedWindowAggExec: wdw=[row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { "row_number() ORDER BY [window_mm.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW": UInt64 }, frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], mode=[Sorted] +05)--------SortPreservingMergeExec: [a@0 ASC NULLS LAST] +06)----------SortExec: expr=[a@0 ASC NULLS LAST], preserve_partitioning=[true] +07)------------DataSourceExec: partitions=4, partition_sizes=[2, 1, 1, 1] + +query R rowsort +SELECT rn * 2 FROM (SELECT a, row_number() OVER (ORDER BY a) AS rn FROM window_mm); +---- +10 +12 +14 +16 +18 +2 +20 +4 +6 +8 + +statement ok +DROP TABLE window_mm; + +# The same with a wide sort key. +statement ok +CREATE TABLE window_url AS SELECT repeat(chr(CAST(97 + value AS BIGINT)), 40) AS url FROM range(0, 10); + +query TT +EXPLAIN SELECT rn * 2 FROM (SELECT url, row_number() OVER (ORDER BY url) AS rn FROM window_url); +---- +logical_plan +01)Projection: CAST(row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS Decimal128(20, 0)) * Decimal128(2,20,0) AS rn * Int64(2) +02)--WindowAggr: windowExpr=[[row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]] +03)----TableScan: window_url projection=[url] +physical_plan +01)ProjectionExec: expr=[CAST(row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@0 AS Decimal128(20, 0)) * 2 as rn * Int64(2)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +03)----ProjectionExec: expr=[row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@1 as row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW] +04)------BoundedWindowAggExec: wdw=[row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { "row_number() ORDER BY [window_url.url ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW": UInt64 }, frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], mode=[Sorted] +05)--------SortPreservingMergeExec: [url@0 ASC NULLS LAST] +06)----------SortExec: expr=[url@0 ASC NULLS LAST], preserve_partitioning=[true] +07)------------DataSourceExec: partitions=4, partition_sizes=[2, 1, 1, 1] + +# Nothing above the sort reads a column. Every row must still cross the repartition. +query TT +EXPLAIN SELECT random() >= 0 AS b FROM (SELECT url FROM window_url ORDER BY url LIMIT 7); +---- +logical_plan +01)Projection: random() >= Float64(0) AS b +02)--Sort: window_url.url ASC NULLS LAST, fetch=7 +03)----TableScan: window_url projection=[url] +physical_plan +01)ProjectionExec: expr=[random() >= 0 as b] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----ProjectionExec: expr=[] +04)------SortPreservingMergeExec: [url@0 ASC NULLS LAST], fetch=7 +05)--------SortExec: TopK(fetch=7), expr=[url@0 ASC NULLS LAST], preserve_partitioning=[true] +06)----------DataSourceExec: partitions=4, partition_sizes=[2, 1, 1, 1] + +query B +SELECT random() >= 0 AS b FROM (SELECT url FROM window_url ORDER BY url LIMIT 7); +---- +true +true +true +true +true +true +true + +statement ok +DROP TABLE window_url; + +# `get_field` must stay above the repartition, where it runs in parallel. +statement ok +CREATE TABLE window_m AS +SELECT value AS id, value AS x, named_struct('value', value, 'o', 1) AS s FROM range(0, 10); + +query TT +EXPLAIN SELECT s['value'], id+1, rn +FROM (SELECT s, id, x, row_number() OVER (ORDER BY x) rn FROM window_m); +---- +logical_plan +01)Projection: get_field(window_m.s, Utf8("value")), window_m.id + Int64(1), row_number() ORDER BY [window_m.x ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS rn +02)--WindowAggr: windowExpr=[[row_number() ORDER BY [window_m.x ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]] +03)----TableScan: window_m projection=[id, x, s] +physical_plan +01)ProjectionExec: expr=[get_field(s@2, value) as window_m.s[value], id@0 + 1 as window_m.id + Int64(1), row_number() ORDER BY [window_m.x ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@3 as rn] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +03)----BoundedWindowAggExec: wdw=[row_number() ORDER BY [window_m.x ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { "row_number() ORDER BY [window_m.x ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW": UInt64 }, frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], mode=[Sorted] +04)------SortPreservingMergeExec: [x@1 ASC NULLS LAST] +05)--------SortExec: expr=[x@1 ASC NULLS LAST], preserve_partitioning=[true] +06)----------DataSourceExec: partitions=4, partition_sizes=[2, 1, 1, 1] + +query III rowsort +SELECT s['value'], id+1, rn +FROM (SELECT s, id, x, row_number() OVER (ORDER BY x) rn FROM window_m); +---- +0 1 1 +1 2 2 +2 3 3 +3 4 4 +4 5 5 +5 6 6 +6 7 7 +7 8 8 +8 9 9 +9 10 10 + +statement ok +DROP TABLE window_m; + +# The sort key `c` is read only by the predicate, but the predicate makes the +# order of `c` the order of `a + b`. Pruning `c` would lose the order that the +# `SortPreservingMergeExec` requires. +statement ok +SET datafusion.execution.target_partitions = 1; + +query I +COPY (SELECT value * 2 AS c, value AS a, value AS b, named_struct('v', value) AS s + FROM range(0, 6) ORDER BY c) +TO 'test_files/scratch/projection_pushdown/ordered/1.parquet' STORED AS PARQUET; +---- +6 + +query I +COPY (SELECT value * 2 AS c, value AS a, value AS b, named_struct('v', value) AS s + FROM range(6, 12) ORDER BY c) +TO 'test_files/scratch/projection_pushdown/ordered/2.parquet' STORED AS PARQUET; +---- +6 + +statement ok +SET datafusion.execution.target_partitions = 8; + +statement ok +SET datafusion.optimizer.repartition_file_scans = false; + +statement ok +SET datafusion.optimizer.prefer_existing_sort = true; + +statement ok +CREATE EXTERNAL TABLE ordered (c BIGINT, a BIGINT, b BIGINT, s STRUCT) +STORED AS PARQUET LOCATION 'test_files/scratch/projection_pushdown/ordered/' +WITH ORDER (c ASC); + +query TT +EXPLAIN SELECT a + b AS s FROM ordered WHERE c = a + b ORDER BY s; +---- +logical_plan +01)Sort: s ASC NULLS LAST +02)--Projection: ordered.a + ordered.b AS s +03)----Filter: ordered.c = ordered.a + ordered.b +04)------TableScan: ordered projection=[c, a, b], partial_filters=[ordered.c = ordered.a + ordered.b] +physical_plan +01)SortPreservingMergeExec: [s@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[a@1 + b@2 as s] +03)----RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=2, preserve_order=true, sort_exprs=c@0 ASC NULLS LAST +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[c, a, b], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 + +query I +SELECT a + b AS s FROM ordered WHERE c = a + b ORDER BY s; +---- +0 +2 +4 +6 +8 +10 +12 +14 +16 +18 +20 +22 + +# Round robin over one input partition also keeps the order. +statement ok +CREATE EXTERNAL TABLE ordered_one (c BIGINT, a BIGINT, b BIGINT, s STRUCT) +STORED AS PARQUET LOCATION 'test_files/scratch/projection_pushdown/ordered/1.parquet' +WITH ORDER (c ASC); + +query TT +EXPLAIN SELECT a + b AS s FROM ordered_one WHERE c = a + b ORDER BY s; +---- +logical_plan +01)Sort: s ASC NULLS LAST +02)--Projection: ordered_one.a + ordered_one.b AS s +03)----Filter: ordered_one.c = ordered_one.a + ordered_one.b +04)------TableScan: ordered_one projection=[c, a, b], partial_filters=[ordered_one.c = ordered_one.a + ordered_one.b] +physical_plan +01)SortPreservingMergeExec: [s@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[a@1 + b@2 as s] +03)----RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet]]}, projection=[c, a, b], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 + +query I +SELECT a + b AS s FROM ordered_one WHERE c = a + b ORDER BY s; +---- +0 +2 +4 +6 +8 +10 + +# The same with a leaf expression that the scan already extracts. +query TT +EXPLAIN SELECT a + b AS k, s['v'] AS v FROM ordered WHERE c = a + b ORDER BY k; +---- +logical_plan +01)Sort: k ASC NULLS LAST +02)--Projection: ordered.a + ordered.b AS k, __datafusion_extracted_1 AS v +03)----Filter: ordered.c = ordered.a + ordered.b +04)------Projection: get_field(ordered.s, Utf8("v")) AS __datafusion_extracted_1, ordered.c, ordered.a, ordered.b +05)--------TableScan: ordered projection=[c, a, b, s], partial_filters=[ordered.c = ordered.a + ordered.b] +physical_plan +01)SortPreservingMergeExec: [k@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[a@2 + b@3 as k, __datafusion_extracted_1@0 as v] +03)----RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=2, preserve_order=true, sort_exprs=c@1 ASC NULLS LAST +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[get_field(s@3, v) as __datafusion_extracted_1, c, a, b], output_ordering=[c@1 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 + +query II +SELECT a + b AS k, s['v'] AS v FROM ordered WHERE c = a + b ORDER BY k; +---- +0 0 +2 1 +4 2 +6 3 +8 4 +10 5 +12 6 +14 7 +16 8 +18 9 +20 10 +22 11 + +# The order needs `c`, but nothing above the scan reads the extracted `s['v']`. +# The scan must prune that column and keep `c`. +query TT +EXPLAIN SELECT a + b AS k FROM ordered WHERE c = a + b AND s['v'] >= 2 ORDER BY k; +---- +logical_plan +01)Sort: k ASC NULLS LAST +02)--Projection: ordered.a + ordered.b AS k +03)----Filter: ordered.c = ordered.a + ordered.b AND __datafusion_extracted_1 >= Int64(2) +04)------Projection: get_field(ordered.s, Utf8("v")) AS __datafusion_extracted_1, ordered.c, ordered.a, ordered.b +05)--------TableScan: ordered projection=[c, a, b, s], partial_filters=[ordered.c = ordered.a + ordered.b, get_field(ordered.s, Utf8("v")) >= Int64(2)] +physical_plan +01)SortPreservingMergeExec: [k@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[a@1 + b@2 as k] +03)----RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=2, preserve_order=true, sort_exprs=c@0 ASC NULLS LAST +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[c, a, b], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 AND get_field(s@3, v) >= 2 + +query I +SELECT a + b AS k FROM ordered WHERE c = a + b AND s['v'] >= 2 ORDER BY k; +---- +4 +6 +8 +10 +12 +14 +16 +18 +20 +22 + +# The same when the output also reads an extracted column. +query TT +EXPLAIN SELECT a + b AS k, s['v'] + 1 AS v FROM ordered WHERE c = a + b AND b >= 2 AND s['v'] < 9 ORDER BY k; +---- +logical_plan +01)Sort: k ASC NULLS LAST +02)--Projection: ordered.a + ordered.b AS k, __datafusion_extracted_2 + Int64(1) AS v +03)----Filter: ordered.c = ordered.a + ordered.b AND ordered.b >= Int64(2) AND __datafusion_extracted_1 < Int64(9) +04)------Projection: get_field(ordered.s, Utf8("v")) AS __datafusion_extracted_1, ordered.c, ordered.a, ordered.b, get_field(ordered.s, Utf8("v")) AS __datafusion_extracted_2 +05)--------TableScan: ordered projection=[c, a, b, s], partial_filters=[ordered.c = ordered.a + ordered.b, ordered.b >= Int64(2), get_field(ordered.s, Utf8("v")) < Int64(9)] +physical_plan +01)SortPreservingMergeExec: [k@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[a@1 + b@2 as k, __datafusion_extracted_2@3 + 1 as v] +03)----RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=2, preserve_order=true, sort_exprs=c@0 ASC NULLS LAST +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_extracted_2], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 AND b@2 >= 2 AND get_field(s@3, v) < 9, pruning_predicate=b_null_count@1 != row_count@2 AND b_max@0 >= 2, required_guarantees=[] + +query II +SELECT a + b AS k, s['v'] + 1 AS v FROM ordered WHERE c = a + b AND b >= 2 AND s['v'] < 9 ORDER BY k; +---- +4 3 +6 4 +8 5 +10 6 +12 7 +14 8 +16 9 + +# `a` does not affect the order, so the scan must prune it. It must also still +# extract the leaf expression. +query TT +EXPLAIN SELECT c, s['v'] + b AS x FROM ordered WHERE a > 8 ORDER BY c; +---- +logical_plan +01)Sort: ordered.c ASC NULLS LAST +02)--Projection: ordered.c, __datafusion_extracted_1 + ordered.b AS x +03)----Filter: ordered.a > Int64(8) +04)------Projection: get_field(ordered.s, Utf8("v")) AS __datafusion_extracted_1, ordered.c, ordered.a, ordered.b +05)--------TableScan: ordered projection=[c, a, b, s], partial_filters=[ordered.a > Int64(8)] +physical_plan +01)SortPreservingMergeExec: [c@0 ASC NULLS LAST] +02)--ProjectionExec: expr=[c@1 as c, __datafusion_extracted_1@0 + b@2 as x] +03)----RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[get_field(s@3, v) as __datafusion_extracted_1, c, b], output_ordering=[c@1 ASC NULLS LAST], file_type=parquet, predicate=a@1 > 8, pruning_predicate=a_null_count@1 != row_count@2 AND a_max@0 > 8, required_guarantees=[] + +query II +SELECT c, s['v'] + b AS x FROM ordered WHERE a > 8 ORDER BY c; +---- +18 18 +20 20 +22 22 + +# Nothing above needs the order of `c`, so the scan must prune it. +query TT +EXPLAIN SELECT a * b AS k FROM ordered WHERE c > 8; +---- +logical_plan +01)Projection: ordered.a * ordered.b AS k +02)--Filter: ordered.c > Int64(8) +03)----TableScan: ordered projection=[c, a, b], partial_filters=[ordered.c > Int64(8)] +physical_plan +01)ProjectionExec: expr=[a@0 * b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=2 +03)----DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[a, b], file_type=parquet, predicate=c@0 > 8, pruning_predicate=c_null_count@1 != row_count@2 AND c_max@0 > 8, required_guarantees=[] + +statement ok +SET datafusion.execution.target_partitions = 4; + +statement ok +SET datafusion.optimizer.prefer_existing_sort = false; + +# `CoalescePartitionsExec` lets the pruning projection through to the scan. +query TT +EXPLAIN SELECT a * b AS k FROM (SELECT * FROM ordered WHERE c >= 0 LIMIT 100); +---- +logical_plan +01)Projection: ordered.a * ordered.b AS k +02)--Limit: skip=0, fetch=100 +03)----Filter: ordered.c >= Int64(0) +04)------TableScan: ordered projection=[c, a, b], partial_filters=[ordered.c >= Int64(0)] +physical_plan +01)ProjectionExec: expr=[a@0 * b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----CoalescePartitionsExec: fetch=100 +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[a, b], limit=100, file_type=parquet, predicate=c@0 >= 0, pruning_predicate=c_null_count@1 != row_count@2 AND c_max@0 >= 0, required_guarantees=[] + +query I rowsort +SELECT a * b AS k FROM (SELECT * FROM ordered WHERE c >= 0 LIMIT 100); +---- +0 +1 +100 +121 +16 +25 +36 +4 +49 +64 +81 +9 + +# `SortPreservingMergeExec` lets the projection through only if the sort key +# survives. The projection stays above it, so `c` does not cross the repartition. +query TT +EXPLAIN SELECT a * b AS k FROM (SELECT * FROM ordered WHERE a >= 0 ORDER BY c LIMIT 100); +---- +logical_plan +01)Projection: ordered.a * ordered.b AS k +02)--Sort: ordered.c ASC NULLS LAST, fetch=100 +03)----Filter: ordered.a >= Int64(0) +04)------TableScan: ordered projection=[c, a, b], partial_filters=[ordered.a >= Int64(0)] +physical_plan +01)ProjectionExec: expr=[a@0 * b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----ProjectionExec: expr=[a@1 as a, b@2 as b] +04)------SortPreservingMergeExec: [c@0 ASC NULLS LAST], fetch=100 +05)--------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/2.parquet]]}, projection=[c, a, b], limit=100, output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=a@1 >= 0, pruning_predicate=a_null_count@1 != row_count@2 AND a_max@0 >= 0, required_guarantees=[] + +query I rowsort +SELECT a * b AS k FROM (SELECT * FROM ordered WHERE a >= 0 ORDER BY c LIMIT 100); +---- +0 +1 +100 +121 +16 +25 +36 +4 +49 +64 +81 +9 + +# `c` makes `k` constant, so the plan sorts by `a` alone. No expression reads `c`, +# but `k` is no longer known to be constant without it. +query I +COPY ( + SELECT column1 AS c, column2 AS a, column3 AS b + FROM VALUES (6, 5, 1), (6, 4, 2), (6, -1, 7), (6, 9, -3) +) +TO 'test_files/scratch/projection_pushdown/constant.parquet' +STORED AS PARQUET; +---- +4 + +statement ok +CREATE EXTERNAL TABLE constant_c STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/constant.parquet'; + +query TT +EXPLAIN SELECT a + b + 1 AS k, a FROM constant_c WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; +---- +logical_plan +01)Sort: k ASC NULLS LAST, constant_c.a ASC NULLS LAST +02)--Projection: constant_c.a + constant_c.b + Int64(1) AS k, constant_c.a +03)----Filter: constant_c.c = constant_c.a + constant_c.b AND constant_c.c + Int64(1) = Int64(7) +04)------TableScan: constant_c projection=[c, a, b], partial_filters=[constant_c.c = constant_c.a + constant_c.b, constant_c.c + Int64(1) = Int64(7)] +physical_plan +01)SortPreservingMergeExec: [k@0 ASC NULLS LAST, a@1 ASC NULLS LAST] +02)--SortExec: expr=[a@1 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[a@1 + b@2 + 1 as k, a@1 as a] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/constant.parquet]]}, projection=[c, a, b], file_type=parquet, predicate=c@0 = a@1 + b@2 AND c@0 + 1 = 7, sort_order_for_reorder=[a@1 ASC NULLS LAST] + +query II +SELECT a + b + 1 AS k, a FROM constant_c WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; +---- +7 -1 +7 4 +7 5 +7 9 + +statement ok +DROP TABLE constant_c; + +# No operator relies on the ordering of `k`, so the split can drop `c`. +query TT +EXPLAIN SELECT a + b AS k FROM ordered_one WHERE c = a + b; +---- +logical_plan +01)Projection: ordered_one.a + ordered_one.b AS k +02)--Filter: ordered_one.c = ordered_one.a + ordered_one.b +03)----TableScan: ordered_one projection=[c, a, b], partial_filters=[ordered_one.c = ordered_one.a + ordered_one.b] +physical_plan +01)ProjectionExec: expr=[a@0 + b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet]]}, projection=[a, b], file_type=parquet, predicate=c@0 = a@1 + b@2 + +# The same for a sort by another key, which does not rely on the order of its input. +query TT +EXPLAIN SELECT a + b AS k, b % 3 AS m FROM ordered_one WHERE c = a + b ORDER BY m; +---- +logical_plan +01)Sort: m ASC NULLS LAST +02)--Projection: ordered_one.a + ordered_one.b AS k, ordered_one.b % Int64(3) AS m +03)----Filter: ordered_one.c = ordered_one.a + ordered_one.b +04)------TableScan: ordered_one projection=[c, a, b], partial_filters=[ordered_one.c = ordered_one.a + ordered_one.b] +physical_plan +01)SortPreservingMergeExec: [m@1 ASC NULLS LAST] +02)--SortExec: expr=[m@1 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[a@0 + b@1 as k, b@1 % 3 as m] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet]]}, projection=[a, b], file_type=parquet, predicate=c@0 = a@1 + b@2 + +# An ordered limit does rely on it. +query TT +EXPLAIN SELECT a + b AS k FROM ordered_one WHERE c = a + b ORDER BY k LIMIT 2; +---- +logical_plan +01)Sort: k ASC NULLS LAST, fetch=2 +02)--Projection: ordered_one.a + ordered_one.b AS k +03)----Filter: ordered_one.c = ordered_one.a + ordered_one.b +04)------TableScan: ordered_one projection=[c, a, b], partial_filters=[ordered_one.c = ordered_one.a + ordered_one.b] +physical_plan +01)SortPreservingMergeExec: [k@0 ASC NULLS LAST], fetch=2 +02)--ProjectionExec: expr=[a@1 + b@2 as k] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/ordered/1.parquet]]}, projection=[c, a, b], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 + +statement ok +DROP TABLE ordered; + +statement ok +DROP TABLE ordered_one; + +statement ok +RESET datafusion.optimizer.repartition_file_scans; + +statement ok +RESET datafusion.optimizer.prefer_existing_sort; + +# A split that extracts a leaf must keep the orderings, constants and equalities +# that an ancestor relies on. The logical rewrite would extract the leaf earlier, +# so these queries disable it. +statement ok +SET datafusion.optimizer.enable_leaf_expression_pushdown = false; + +query I +COPY (SELECT value * 2 AS c, value AS a, value AS b, named_struct('v', value) AS s + FROM range(0, 6) ORDER BY c) +TO 'test_files/scratch/projection_pushdown/leaf_ordered.parquet' STORED AS PARQUET; +---- +6 + +statement ok +CREATE EXTERNAL TABLE leaf_ordered (c BIGINT, a BIGINT, b BIGINT, s STRUCT) +STORED AS PARQUET LOCATION 'test_files/scratch/projection_pushdown/leaf_ordered.parquet' +WITH ORDER (c ASC); + +# `c = a + b` makes the order of `c` the order of `k`, which the merge needs. +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY k LIMIT 2; +---- +logical_plan +01)Sort: k ASC NULLS LAST, fetch=2 +02)--Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k +03)----Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b +04)------TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] +physical_plan +01)SortPreservingMergeExec: [k@1 ASC NULLS LAST], fetch=2 +02)--ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 + +query II +SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY k LIMIT 2; +---- +1 0 +2 2 + +# The same for an aggregate that the order reaches through. +query II +SELECT k, sum(l) FROM (SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b) +GROUP BY k ORDER BY k; +---- +0 1 +2 2 +4 3 +6 4 +8 5 +10 6 + +# Nothing needs the order of `k`, so the scan does not read `c`. +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b; +---- +logical_plan +01)Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k +02)--Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b +03)----TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 + +# The same for a sort by another key, which does not need the order of its input. +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY l; +---- +logical_plan +01)Sort: l ASC NULLS LAST +02)--Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k +03)----Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b +04)------TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] +physical_plan +01)SortPreservingMergeExec: [l@0 ASC NULLS LAST] +02)--SortExec: expr=[l@0 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 + +# `c` makes `k` constant, so the plan sorts by `a` alone. +query I +COPY (SELECT column1 AS c, column2 AS a, column3 AS b, named_struct('v', column2) AS s + FROM VALUES (6, 5, 1), (6, 4, 2), (6, -1, 7), (6, 9, -3)) +TO 'test_files/scratch/projection_pushdown/leaf_constant.parquet' STORED AS PARQUET; +---- +4 + +statement ok +CREATE EXTERNAL TABLE leaf_constant STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/leaf_constant.parquet'; + +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b + 1 AS k, a FROM leaf_constant WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; +---- +logical_plan +01)Sort: k ASC NULLS LAST, leaf_constant.a ASC NULLS LAST +02)--Projection: get_field(leaf_constant.s, Utf8("v")) + Int64(1) AS l, leaf_constant.a + leaf_constant.b + Int64(1) AS k, leaf_constant.a +03)----Filter: leaf_constant.c = leaf_constant.a + leaf_constant.b AND leaf_constant.c + Int64(1) = Int64(7) +04)------TableScan: leaf_constant projection=[c, a, b, s], partial_filters=[leaf_constant.c = leaf_constant.a + leaf_constant.b, leaf_constant.c + Int64(1) = Int64(7)] +physical_plan +01)SortPreservingMergeExec: [k@1 ASC NULLS LAST, a@2 ASC NULLS LAST] +02)--SortExec: expr=[a@2 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 + 1 as k, a@1 as a] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_constant.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 AND c@0 + 1 = 7, sort_order_for_reorder=[a@1 ASC NULLS LAST] + +query III +SELECT s['v'] + 1 AS l, a + b + 1 AS k, a FROM leaf_constant WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; +---- +0 7 -1 +5 7 4 +6 7 5 +10 7 9 + +statement ok +DROP TABLE leaf_constant; + +statement ok +DROP TABLE leaf_ordered; + +statement ok +RESET datafusion.optimizer.enable_leaf_expression_pushdown; + statement ok SET datafusion.execution.batch_size = 8192;