Skip to main content

datafusion_physical_plan/
projection.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Defines the projection execution plan. A projection determines which columns or expressions
19//! are returned from a query. The SQL statement `SELECT a, b, a+b FROM t1` is an example
20//! of a projection on table `t1` where the expressions `a`, `b`, and `a+b` are the
21//! projection expressions. `SELECT` without `FROM` will only evaluate expressions.
22
23use super::expressions::Column;
24use super::metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet};
25use super::{
26    DisplayAs, ExecutionPlanProperties, PlanProperties, RecordBatchStream,
27    SendableRecordBatchStream, SortOrderPushdownResult, Statistics,
28};
29use crate::column_rewriter::PhysicalColumnRewriter;
30use crate::execution_plan::{CardinalityEffect, replace_children_if_necessary};
31use crate::filter_pushdown::{
32    ChildFilterDescription, ChildPushdownResult, FilterDescription, FilterPushdownPhase,
33    FilterPushdownPropagation, FilterRemapper, PushedDownPredicate,
34};
35use crate::joins::utils::{ColumnIndex, JoinFilter, JoinOn, JoinOnRef};
36use crate::statistics::{ChildStats, StatisticsArgs};
37use crate::{
38    ChildrenPropertiesMode, DisplayFormatType, ExecutionPlan, PhysicalExpr,
39    ReplaceChildrenOptions, validate_child_count,
40};
41use std::collections::HashMap;
42use std::pin::Pin;
43use std::sync::Arc;
44use std::task::{Context, Poll};
45
46use arrow::datatypes::{Schema, SchemaRef};
47use arrow::record_batch::RecordBatch;
48use datafusion_common::config::ConfigOptions;
49use datafusion_common::tree_node::{
50    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
51};
52use datafusion_common::{DataFusionError, JoinSide, Result, internal_err, plan_err};
53use datafusion_execution::TaskContext;
54use datafusion_expr::ExpressionPlacement;
55use datafusion_physical_expr::equivalence::ProjectionMapping;
56use datafusion_physical_expr::projection::Projector;
57use datafusion_physical_expr_common::physical_expr::{PhysicalExprRef, fmt_sql};
58use datafusion_physical_expr_common::sort_expr::{
59    LexOrdering, LexRequirement, PhysicalSortExpr,
60};
61// Re-exported from datafusion-physical-expr for backwards compatibility
62// We recommend updating your imports to use datafusion-physical-expr directly
63pub use datafusion_physical_expr::projection::{
64    ProjectionExpr, ProjectionExprs, update_expr,
65};
66
67use futures::stream::{Stream, StreamExt};
68use log::trace;
69
70/// [`ExecutionPlan`] for a projection
71///
72/// Computes a set of scalar value expressions for each input row, producing one
73/// output row for each input row.
74#[derive(Debug, Clone)]
75pub struct ProjectionExec {
76    /// A projector specialized to apply the projection to the input schema from the child node
77    /// and produce [`RecordBatch`]es with the output schema of this node.
78    projector: Projector,
79    /// The input plan
80    input: Arc<dyn ExecutionPlan>,
81    /// Execution metrics
82    metrics: ExecutionPlanMetricsSet,
83    /// Cache holding plan properties like equivalences, output partitioning etc.
84    cache: Arc<PlanProperties>,
85    /// Whether the output metadata differs from the metadata derived from the
86    /// projection expressions and input schema.
87    overrides_metadata: bool,
88}
89
90impl ProjectionExec {
91    /// Create a projection on an input
92    ///
93    /// # Example:
94    /// Create a `ProjectionExec` to crate `SELECT a, a+b AS sum_ab FROM t1`:
95    ///
96    /// ```
97    /// # use std::sync::Arc;
98    /// # use arrow_schema::{Schema, Field, DataType};
99    /// # use datafusion_expr::Operator;
100    /// # use datafusion_physical_plan::ExecutionPlan;
101    /// # use datafusion_physical_expr::expressions::{col, binary};
102    /// # use datafusion_physical_plan::empty::EmptyExec;
103    /// # use datafusion_physical_plan::projection::{ProjectionExec, ProjectionExpr};
104    /// # fn schema() -> Arc<Schema> {
105    /// #  Arc::new(Schema::new(vec![
106    /// #   Field::new("a", DataType::Int32, false),
107    /// #   Field::new("b", DataType::Int32, false),
108    /// # ]))
109    /// # }
110    /// #
111    /// # fn input() -> Arc<dyn ExecutionPlan> {
112    /// #  Arc::new(EmptyExec::new(schema()))
113    /// # }
114    /// #
115    /// # fn main() {
116    /// let schema = schema();
117    /// // Create PhysicalExprs
118    /// let a = col("a", &schema).unwrap();
119    /// let b = col("b", &schema).unwrap();
120    /// let a_plus_b = binary(Arc::clone(&a), Operator::Plus, b, &schema).unwrap();
121    /// // create ProjectionExec
122    /// let proj = ProjectionExec::try_new(
123    ///     [
124    ///         ProjectionExpr {
125    ///             // expr a produces the column named "a"
126    ///             expr: a,
127    ///             alias: "a".to_string(),
128    ///         },
129    ///         ProjectionExpr {
130    ///             // expr: a + b produces the column named "sum_ab"
131    ///             expr: a_plus_b,
132    ///             alias: "sum_ab".to_string(),
133    ///         },
134    ///     ],
135    ///     input(),
136    /// )
137    /// .unwrap();
138    /// # }
139    /// ```
140    pub fn try_new<I, E>(expr: I, input: Arc<dyn ExecutionPlan>) -> Result<Self>
141    where
142        I: IntoIterator<Item = E>,
143        E: Into<ProjectionExpr>,
144    {
145        let input_schema = input.schema();
146        let expr_arc = expr.into_iter().map(Into::into).collect::<Arc<_>>();
147        let projection = ProjectionExprs::from_expressions(expr_arc);
148        let projector = projection.make_projector(&input_schema)?;
149        Self::try_from_projector(projector, input, false)
150    }
151
152    /// Create a projection using field and schema metadata from
153    /// `projected_schema`.
154    ///
155    /// Field names, data types, and nullability are still derived from the physical
156    /// projection expressions and the input plan; only field and schema metadata are
157    /// taken from `projected_schema`.
158    ///
159    /// # Errors
160    ///
161    /// Returns an error if the projection cannot be applied to the input plan, or if
162    /// `projected_schema` has a different number of fields than the projection.
163    pub fn try_new_with_schema_metadata<I, E>(
164        expr: I,
165        input: Arc<dyn ExecutionPlan>,
166        projected_schema: &Schema,
167    ) -> Result<Self>
168    where
169        I: IntoIterator<Item = E>,
170        E: Into<ProjectionExpr>,
171    {
172        let input_schema = input.schema();
173        let expr_arc = expr.into_iter().map(Into::into).collect::<Arc<_>>();
174        let projection = ProjectionExprs::from_expressions(expr_arc);
175        let projector = projection
176            .make_projector_with_schema_metadata(&input_schema, projected_schema)?;
177        let overrides_metadata =
178            Self::compute_overrides_metadata(&projector, &input_schema)?;
179        Self::try_from_projector(projector, input, overrides_metadata)
180    }
181
182    fn try_from_projector(
183        projector: Projector,
184        input: Arc<dyn ExecutionPlan>,
185        overrides_metadata: bool,
186    ) -> Result<Self> {
187        // Construct a map from the input expressions to the output expression of the Projection
188        let projection_mapping =
189            projector.projection().projection_mapping(&input.schema())?;
190        let cache = Self::compute_properties(
191            &input,
192            &projection_mapping,
193            Arc::clone(projector.output_schema()),
194        )?;
195        Ok(Self {
196            projector,
197            input,
198            metrics: ExecutionPlanMetricsSet::new(),
199            cache: Arc::new(cache),
200            overrides_metadata,
201        })
202    }
203
204    /// The projection expressions stored as tuples of (expression, output column name)
205    pub fn expr(&self) -> &[ProjectionExpr] {
206        self.projector.projection().as_ref()
207    }
208
209    /// The projection expressions as a [`ProjectionExprs`].
210    pub fn projection_expr(&self) -> &ProjectionExprs {
211        self.projector.projection()
212    }
213
214    /// The input plan
215    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
216        &self.input
217    }
218
219    /// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
220    fn compute_properties(
221        input: &Arc<dyn ExecutionPlan>,
222        projection_mapping: &ProjectionMapping,
223        schema: SchemaRef,
224    ) -> Result<PlanProperties> {
225        // Calculate equivalence properties:
226        let input_eq_properties = input.equivalence_properties();
227        let eq_properties = input_eq_properties.project(projection_mapping, schema);
228        // Calculate output partitioning, which needs to respect aliases:
229        let output_partitioning = input
230            .output_partitioning()
231            .project(projection_mapping, input_eq_properties);
232
233        Ok(PlanProperties::new(
234            eq_properties,
235            output_partitioning,
236            input.pipeline_behavior(),
237            input.boundedness(),
238        ))
239    }
240
241    /// Returns whether `projector`'s output metadata differs from the metadata
242    /// derived from its expressions and `input_schema`.
243    fn compute_overrides_metadata(
244        projector: &Projector,
245        input_schema: &Schema,
246    ) -> Result<bool> {
247        let output_schema = projector.output_schema();
248        if input_schema.metadata() != output_schema.metadata() {
249            return Ok(true);
250        }
251        for (projection, output_field) in
252            projector.projection().iter().zip(output_schema.fields())
253        {
254            let derived_field = projection.expr.return_field(input_schema)?;
255            if derived_field.metadata() != output_field.metadata() {
256                return Ok(true);
257            }
258        }
259        Ok(false)
260    }
261
262    /// Returns whether this projection's output metadata differs from the
263    /// metadata derived when the projection was constructed.
264    fn overrides_metadata(&self) -> bool {
265        self.overrides_metadata
266    }
267
268    /// Collect reverse alias mapping from projection expressions.
269    /// The result hash map is a map from aliased Column in parent to original expr.
270    fn collect_reverse_alias(
271        &self,
272    ) -> Result<datafusion_common::HashMap<Column, Arc<dyn PhysicalExpr>>> {
273        let mut alias_map = datafusion_common::HashMap::new();
274        for projection in self.projection_expr().iter() {
275            let (aliased_index, _output_field) = self
276                .projector
277                .output_schema()
278                .column_with_name(&projection.alias)
279                .ok_or_else(|| {
280                    DataFusionError::Internal(format!(
281                        "Expr {} with alias {} not found in output schema",
282                        projection.expr, projection.alias
283                    ))
284                })?;
285            let aliased_col = Column::new(&projection.alias, aliased_index);
286            alias_map.insert(aliased_col, Arc::clone(&projection.expr));
287        }
288        Ok(alias_map)
289    }
290}
291
292impl DisplayAs for ProjectionExec {
293    fn fmt_as(
294        &self,
295        t: DisplayFormatType,
296        f: &mut std::fmt::Formatter,
297    ) -> std::fmt::Result {
298        match t {
299            DisplayFormatType::Default | DisplayFormatType::Verbose => {
300                let expr: Vec<String> = self
301                    .projector
302                    .projection()
303                    .as_ref()
304                    .iter()
305                    .map(|proj_expr| {
306                        let e = proj_expr.expr.to_string();
307                        if e != proj_expr.alias {
308                            format!("{e} as {}", proj_expr.alias)
309                        } else {
310                            e
311                        }
312                    })
313                    .collect();
314
315                write!(f, "ProjectionExec: expr=[{}]", expr.join(", "))
316            }
317            DisplayFormatType::TreeRender => {
318                for (i, proj_expr) in self.expr().iter().enumerate() {
319                    let expr_sql = fmt_sql(proj_expr.expr.as_ref());
320                    if proj_expr.expr.to_string() == proj_expr.alias {
321                        writeln!(f, "expr{i}={expr_sql}")?;
322                    } else {
323                        writeln!(f, "{}={expr_sql}", proj_expr.alias)?;
324                    }
325                }
326
327                Ok(())
328            }
329        }
330    }
331}
332
333impl ExecutionPlan for ProjectionExec {
334    fn name(&self) -> &'static str {
335        "ProjectionExec"
336    }
337
338    /// Return a reference to Any that can be used for downcasting
339    fn properties(&self) -> &Arc<PlanProperties> {
340        &self.cache
341    }
342
343    fn maintains_input_order(&self) -> Vec<bool> {
344        // Tell optimizer this operator doesn't reorder its input
345        vec![true]
346    }
347
348    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
349        let all_simple_exprs =
350            self.projector
351                .projection()
352                .as_ref()
353                .iter()
354                .all(|proj_expr| {
355                    !matches!(
356                        proj_expr.expr.placement(),
357                        ExpressionPlacement::KeepInPlace
358                    )
359                });
360        // If expressions are all either column_expr or Literal (or other cheap expressions),
361        // then all computations in this projection are reorder or rename,
362        // and projection would not benefit from the repartition, benefits_from_input_partitioning will return false.
363        vec![!all_simple_exprs]
364    }
365
366    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
367        vec![&self.input]
368    }
369
370    fn apply_expressions(
371        &self,
372        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
373    ) -> Result<TreeNodeRecursion> {
374        crate::apply_expression_roots(self.projector.projection().as_ref().iter(), f)
375    }
376
377    fn replace_children(
378        self: Arc<Self>,
379        mut children: Vec<Arc<dyn ExecutionPlan>>,
380        options: ReplaceChildrenOptions,
381    ) -> Result<Arc<dyn ExecutionPlan>> {
382        validate_child_count!(self, children);
383        match options.children_properties {
384            ChildrenPropertiesMode::Keep => Ok(Arc::new(Self {
385                input: children.swap_remove(0),
386                metrics: ExecutionPlanMetricsSet::new(),
387                ..Self::clone(&*self)
388            })),
389            ChildrenPropertiesMode::Recompute => {
390                let input = children.swap_remove(0);
391                let projector = self.projector.clone();
392                let overrides_metadata = ProjectionExec::compute_overrides_metadata(
393                    &projector,
394                    input.schema().as_ref(),
395                )?;
396                ProjectionExec::try_from_projector(projector, input, overrides_metadata)
397                    .map(|p| Arc::new(p) as _)
398            }
399        }
400    }
401
402    fn with_new_children(
403        self: Arc<Self>,
404        children: Vec<Arc<dyn ExecutionPlan>>,
405    ) -> Result<Arc<dyn ExecutionPlan>> {
406        self.replace_children(
407            children,
408            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
409        )
410    }
411
412    fn with_new_children_and_same_properties(
413        self: Arc<Self>,
414        children: Vec<Arc<dyn ExecutionPlan>>,
415    ) -> Result<Arc<dyn ExecutionPlan>> {
416        self.replace_children(
417            children,
418            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
419        )
420    }
421
422    fn execute(
423        &self,
424        partition: usize,
425        context: Arc<TaskContext>,
426    ) -> Result<SendableRecordBatchStream> {
427        trace!(
428            "Start ProjectionExec::execute for partition {} of context session_id {} and task_id {:?}",
429            partition,
430            context.session_id(),
431            context.task_id()
432        );
433
434        let projector = self.projector.with_metrics(&self.metrics, partition);
435        Ok(Box::pin(ProjectionStream::new(
436            projector,
437            self.input.execute(partition, context)?,
438            BaselineMetrics::new(&self.metrics, partition),
439        )?))
440    }
441
442    fn metrics(&self) -> Option<MetricsSet> {
443        Some(self.metrics.clone_inner())
444    }
445
446    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
447        vec![ChildStats::At(partition)]
448    }
449
450    fn statistics_from_inputs(
451        &self,
452        input_stats: &[Arc<Statistics>],
453        _args: &StatisticsArgs,
454    ) -> Result<Arc<Statistics>> {
455        let input_stats = input_stats[0].as_ref().clone();
456        let output_schema = self.schema();
457        Ok(Arc::new(
458            self.projector
459                .projection()
460                .project_statistics(input_stats, &output_schema)?,
461        ))
462    }
463
464    fn supports_limit_pushdown(&self) -> bool {
465        true
466    }
467
468    fn cardinality_effect(&self) -> CardinalityEffect {
469        CardinalityEffect::Equal
470    }
471
472    fn try_swapping_with_projection(
473        &self,
474        projection: &ProjectionExec,
475    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
476        match try_collapse_projection_chain(projection)? {
477            Some(plan) => Ok(Some(plan)),
478            None => Ok(Some(Arc::new(projection.clone()))),
479        }
480    }
481
482    fn gather_filters_for_pushdown(
483        &self,
484        _phase: FilterPushdownPhase,
485        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
486        _config: &ConfigOptions,
487    ) -> Result<FilterDescription> {
488        // expand alias column to original expr in parent filters
489        let invert_alias_map = self.collect_reverse_alias()?;
490        let output_schema = self.schema();
491        let remapper = FilterRemapper::new(output_schema);
492        let mut child_parent_filters = Vec::with_capacity(parent_filters.len());
493
494        for filter in parent_filters {
495            // Check that column exists in child, then reassign column indices to match child schema
496            if let Some(reassigned) = remapper.try_remap(&filter)? {
497                // rewrite filter expression using invert alias map
498                let mut rewriter = PhysicalColumnRewriter::new(&invert_alias_map);
499                let rewritten = reassigned.rewrite(&mut rewriter)?.data;
500                child_parent_filters.push(PushedDownPredicate::supported(rewritten));
501            } else {
502                child_parent_filters.push(PushedDownPredicate::unsupported(filter));
503            }
504        }
505
506        Ok(FilterDescription::new().with_child(ChildFilterDescription {
507            parent_filters: child_parent_filters,
508            self_filters: vec![],
509        }))
510    }
511
512    fn handle_child_pushdown_result(
513        &self,
514        _phase: FilterPushdownPhase,
515        child_pushdown_result: ChildPushdownResult,
516        _config: &ConfigOptions,
517    ) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
518        Ok(FilterPushdownPropagation::if_all(child_pushdown_result))
519    }
520
521    fn try_pushdown_sort(
522        &self,
523        order: &[PhysicalSortExpr],
524    ) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
525        let child = self.input();
526        let mut child_order = Vec::new();
527
528        // Check and transform sort expressions
529        for sort_expr in order {
530            // Recursively transform the expression
531            let mut can_pushdown = true;
532            let transformed = Arc::clone(&sort_expr.expr).transform(|expr| {
533                if let Some(col) = expr.downcast_ref::<Column>() {
534                    // Check if column index is valid.
535                    // This should always be true but fail gracefully if it's not.
536                    if col.index() >= self.expr().len() {
537                        can_pushdown = false;
538                        return Ok(Transformed::no(expr));
539                    }
540
541                    let proj_expr = &self.expr()[col.index()];
542
543                    // Check if projection expression is a simple column
544                    // We cannot push down order by clauses that depend on
545                    // projected computations as they would have nothing to reference.
546                    if let Some(child_col) = proj_expr.expr.downcast_ref::<Column>() {
547                        // Replace with the child column
548                        Ok(Transformed::yes(Arc::new(child_col.clone()) as _))
549                    } else {
550                        // Projection involves computation, cannot push down
551                        can_pushdown = false;
552                        Ok(Transformed::no(expr))
553                    }
554                } else {
555                    Ok(Transformed::no(expr))
556                }
557            })?;
558
559            if !can_pushdown {
560                return Ok(SortOrderPushdownResult::Unsupported);
561            }
562
563            child_order.push(PhysicalSortExpr {
564                expr: transformed.data,
565                options: sort_expr.options,
566            });
567        }
568
569        // Recursively push down to child node
570        match child.try_pushdown_sort(&child_order)? {
571            SortOrderPushdownResult::Exact { inner } => {
572                let new_exec =
573                    replace_children_if_necessary(Arc::new(self.clone()), vec![inner])?;
574                Ok(SortOrderPushdownResult::Exact { inner: new_exec })
575            }
576            SortOrderPushdownResult::Inexact { inner } => {
577                let new_exec =
578                    replace_children_if_necessary(Arc::new(self.clone()), vec![inner])?;
579                Ok(SortOrderPushdownResult::Inexact { inner: new_exec })
580            }
581            SortOrderPushdownResult::Unsupported => {
582                Ok(SortOrderPushdownResult::Unsupported)
583            }
584        }
585    }
586
587    fn with_preserve_order(
588        &self,
589        preserve_order: bool,
590    ) -> Option<Arc<dyn ExecutionPlan>> {
591        self.input
592            .with_preserve_order(preserve_order)
593            .and_then(|new_input| {
594                replace_children_if_necessary(Arc::new(self.clone()), vec![new_input])
595                    .ok()
596            })
597    }
598
599    #[cfg(feature = "proto")]
600    fn try_to_proto(
601        &self,
602        ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
603    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
604        use datafusion_proto_models::protobuf;
605        let input = ctx.encode_child(self.input())?;
606        let expr = ctx.encode_expressions(self.expr().iter().map(|p| &p.expr))?;
607        let expr_name = self.expr().iter().map(|p| p.alias.clone()).collect();
608        Ok(Some(protobuf::PhysicalPlanNode {
609            physical_plan_type: Some(
610                protobuf::physical_plan_node::PhysicalPlanType::Projection(Box::new(
611                    protobuf::ProjectionExecNode {
612                        input: Some(Box::new(input)),
613                        expr,
614                        expr_name,
615                    },
616                )),
617            ),
618        }))
619    }
620}
621
622#[cfg(feature = "proto")]
623impl ProjectionExec {
624    /// Reconstruct a [`ProjectionExec`] from its protobuf representation.
625    ///
626    /// The exact inverse of [`ExecutionPlan::try_to_proto`]: it takes the whole
627    /// [`PhysicalPlanNode`] so every plan's `try_from_proto` shares one
628    /// signature. Child plans and expressions are decoded recursively via the
629    /// [`ExecutionPlanDecodeCtx`].
630    ///
631    /// [`PhysicalPlanNode`]: datafusion_proto_models::protobuf::PhysicalPlanNode
632    /// [`ExecutionPlan::try_to_proto`]: crate::ExecutionPlan::try_to_proto
633    /// [`ExecutionPlanDecodeCtx`]: crate::proto::ExecutionPlanDecodeCtx
634    pub fn try_from_proto(
635        node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
636        ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
637    ) -> Result<Arc<dyn ExecutionPlan>> {
638        use datafusion_proto_models::protobuf;
639        let projection = crate::expect_plan_variant!(
640            node,
641            protobuf::physical_plan_node::PhysicalPlanType::Projection,
642            "ProjectionExec",
643        );
644        let input = ctx.decode_required_child(
645            projection.input.as_deref(),
646            "ProjectionExec",
647            "input",
648        )?;
649        let input_schema = input.schema();
650        let exprs = projection
651            .expr
652            .iter()
653            .zip(projection.expr_name.iter())
654            .map(|(expr, name)| {
655                Ok(ProjectionExpr {
656                    expr: ctx.decode_expr(expr, input_schema.as_ref())?,
657                    alias: name.to_string(),
658                })
659            })
660            .collect::<Result<Vec<ProjectionExpr>>>()?;
661        Ok(Arc::new(ProjectionExec::try_new(exprs, input)?))
662    }
663}
664
665impl ProjectionStream {
666    /// Create a new projection stream
667    fn new(
668        projector: Projector,
669        input: SendableRecordBatchStream,
670        baseline_metrics: BaselineMetrics,
671    ) -> Result<Self> {
672        Ok(Self {
673            projector,
674            input,
675            baseline_metrics,
676        })
677    }
678
679    fn batch_project(&self, batch: &RecordBatch) -> Result<RecordBatch> {
680        // Records time on drop
681        let _timer = self.baseline_metrics.elapsed_compute().timer();
682        self.projector.project_batch(batch)
683    }
684}
685
686/// Projection iterator
687struct ProjectionStream {
688    projector: Projector,
689    input: SendableRecordBatchStream,
690    baseline_metrics: BaselineMetrics,
691}
692
693impl Stream for ProjectionStream {
694    type Item = Result<RecordBatch>;
695
696    fn poll_next(
697        mut self: Pin<&mut Self>,
698        cx: &mut Context<'_>,
699    ) -> Poll<Option<Self::Item>> {
700        let poll = self.input.poll_next_unpin(cx).map(|x| match x {
701            Some(Ok(batch)) => Some(self.batch_project(&batch)),
702            other => other,
703        });
704
705        self.baseline_metrics.record_poll(poll)
706    }
707
708    fn size_hint(&self) -> (usize, Option<usize>) {
709        // Same number of record batches
710        self.input.size_hint()
711    }
712}
713
714impl RecordBatchStream for ProjectionStream {
715    /// Get the schema
716    fn schema(&self) -> SchemaRef {
717        Arc::clone(self.projector.output_schema())
718    }
719}
720
721/// Trait for execution plans that can embed a projection, avoiding a separate
722/// [`ProjectionExec`] wrapper.
723///
724/// # Empty projections
725///
726/// `Some(vec![])` is a valid projection that produces zero output columns while
727/// preserving the correct row count. Implementors must ensure that runtime batch
728/// construction still returns batches with the right number of rows even when no
729/// columns are selected (e.g. for `SELECT count(1) … JOIN …`).
730pub trait EmbeddedProjection: ExecutionPlan + Sized {
731    fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self>;
732}
733
734/// Some projection can't be pushed down left input or right input of hash join because filter or on need may need some columns that won't be used in later.
735/// By embed those projection to hash join, we can reduce the cost of build_batch_from_indices in hash join (build_batch_from_indices need to can compute::take() for each column) and avoid unnecessary output creation.
736pub fn try_embed_projection<Exec: EmbeddedProjection + 'static>(
737    projection: &ProjectionExec,
738    execution_plan: &Exec,
739) -> Result<Option<Arc<dyn ExecutionPlan>>> {
740    // If the projection has no expressions at all (e.g., ProjectionExec: expr=[]),
741    // embed an empty projection into the execution plan so it outputs zero columns.
742    // This avoids allocating throwaway null arrays for build-side columns
743    // when no output columns are actually needed (e.g., count(1) over a right join).
744    if projection.expr().is_empty() {
745        let new_execution_plan = Arc::new(execution_plan.with_projection(Some(vec![]))?);
746        return Ok(Some(new_execution_plan));
747    }
748
749    // Collect all column indices from the given projection expressions.
750    let projection_index = collect_column_indices(projection.expr());
751
752    if projection_index.is_empty() {
753        return Ok(None);
754    };
755
756    let columns_reduced = projection_index.len() < execution_plan.schema().fields().len();
757
758    let new_execution_plan =
759        Arc::new(execution_plan.with_projection(Some(projection_index.to_vec()))?);
760
761    // Build projection expressions for update_expr. Zip the projection_index with the new_execution_plan output schema fields.
762    let embed_project_exprs = projection_index
763        .iter()
764        .zip(new_execution_plan.schema().fields())
765        .map(|(index, field)| ProjectionExpr {
766            expr: Arc::new(Column::new(field.name(), *index)) as Arc<dyn PhysicalExpr>,
767            alias: field.name().to_owned(),
768        })
769        .collect::<Vec<_>>();
770
771    let mut new_projection_exprs = Vec::with_capacity(projection.expr().len());
772
773    for proj_expr in projection.expr() {
774        // update column index for projection expression since the input schema has been changed.
775        let Some(expr) =
776            update_expr(&proj_expr.expr, embed_project_exprs.as_slice(), false)?
777        else {
778            return Ok(None);
779        };
780        new_projection_exprs.push(ProjectionExpr {
781            expr,
782            alias: proj_expr.alias.clone(),
783        });
784    }
785    // Old projection may contain some alias or expression such as `a + 1` and `CAST('true' AS BOOLEAN)`, but our projection_exprs in hash join just contain column, so we need to create the new projection to keep the original projection.
786    let new_projection = Arc::new(ProjectionExec::try_new(
787        new_projection_exprs,
788        Arc::clone(&new_execution_plan) as _,
789    )?);
790    if is_projection_removable(&new_projection) {
791        // Residual is identity — embedding fully absorbed the projection.
792        Ok(Some(new_execution_plan))
793    } else if columns_reduced {
794        // Embedding reduced columns even though a residual is still needed
795        // for renames or expressions — worth keeping.
796        Ok(Some(new_projection))
797    } else {
798        // No columns eliminated and residual still needed — embedding just
799        // adds an unnecessary column reorder inside the operator.
800        Ok(None)
801    }
802}
803
804pub struct JoinData {
805    pub projected_left_child: ProjectionExec,
806    pub projected_right_child: ProjectionExec,
807    pub join_filter: Option<JoinFilter>,
808    pub join_on: JoinOn,
809}
810
811#[deprecated(
812    since = "55.0.0",
813    note = "Use try_pushdown_through_join_with_column_indices instead"
814)]
815pub fn try_pushdown_through_join(
816    projection: &ProjectionExec,
817    join_left: &Arc<dyn ExecutionPlan>,
818    join_right: &Arc<dyn ExecutionPlan>,
819    join_on: JoinOnRef,
820    schema: &SchemaRef,
821    filter: Option<&JoinFilter>,
822) -> Result<Option<JoinData>> {
823    let left_field_count = join_left.schema().fields().len();
824    let column_indices = schema
825        .fields()
826        .iter()
827        .enumerate()
828        .map(|(index, _)| {
829            if index < left_field_count {
830                ColumnIndex {
831                    index,
832                    side: JoinSide::Left,
833                }
834            } else {
835                ColumnIndex {
836                    index: index - left_field_count,
837                    side: JoinSide::Right,
838                }
839            }
840        })
841        .collect::<Vec<_>>();
842
843    try_pushdown_through_join_with_column_indices(
844        projection,
845        join_left,
846        join_right,
847        join_on,
848        schema,
849        filter,
850        &column_indices,
851    )
852}
853
854/// Attempts to move a projection below a join by mapping each join output
855/// column to the child column that produced it.
856///
857/// `schema` is the complete output schema of the join, not either child's
858/// schema. `column_indices` must contain one entry for each field in `schema`.
859/// Each [`JoinSide::Left`] or [`JoinSide::Right`] entry identifies the source
860/// child and uses an index relative to that child's schema.
861///
862/// [`JoinSide::None`] identifies a column produced by the join itself, such as
863/// a mark column. If `projection` references such a column, this function
864/// returns `Ok(None)` because neither child can produce it.
865///
866/// Returns `Ok(None)` when the projection cannot be pushed down safely.
867///
868/// # Errors
869///
870/// Returns an error if `column_indices` does not match `schema` or contains an
871/// index outside the corresponding child schema.
872pub fn try_pushdown_through_join_with_column_indices(
873    projection: &ProjectionExec,
874    join_left: &Arc<dyn ExecutionPlan>,
875    join_right: &Arc<dyn ExecutionPlan>,
876    join_on: JoinOnRef,
877    schema: &SchemaRef,
878    filter: Option<&JoinFilter>,
879    column_indices: &[ColumnIndex],
880) -> Result<Option<JoinData>> {
881    if column_indices.len() != schema.fields().len() {
882        return plan_err!(
883            "Column index mapping has {} entries but join schema has {} fields",
884            column_indices.len(),
885            schema.fields().len()
886        );
887    }
888    // Validate each output-to-child mapping before using it to rewrite the
889    // projection. Synthetic outputs have no child index to validate.
890    for (output_index, column_index) in column_indices.iter().enumerate() {
891        let (side, child_field_count) = match column_index.side {
892            JoinSide::Left => ("left", join_left.schema().fields().len()),
893            JoinSide::Right => ("right", join_right.schema().fields().len()),
894            JoinSide::None => continue,
895        };
896        if column_index.index >= child_field_count {
897            return plan_err!(
898                "Join output column {output_index} maps to {side} child column {}, but the child has {child_field_count} fields",
899                column_index.index
900            );
901        }
902    }
903
904    // Convert projected expressions to columns. We can not proceed if this is not possible.
905    let Some(projection_as_columns) = physical_to_column_exprs(projection.expr()) else {
906        return Ok(None);
907    };
908
909    if projection_as_columns.len() >= schema.fields().len() {
910        return Ok(None);
911    }
912    let mut left_proj: Vec<(Column, String)> = Vec::new();
913    let mut right_proj: Vec<(Column, String)> = Vec::new();
914    let mut seen_right = false;
915    for (col, alias) in &projection_as_columns {
916        let Some(origin) = column_indices.get(col.index()) else {
917            return plan_err!(
918                "Projection column {} is outside the {}-entry column index mapping",
919                col.index(),
920                column_indices.len()
921            );
922        };
923        match origin.side {
924            // Keep the "left block before right block" contiguity the current
925            // pushdown supports; a left column after a right one is "mixed".
926            JoinSide::Left => {
927                if seen_right {
928                    return Ok(None);
929                }
930                left_proj.push((Column::new(col.name(), origin.index), alias.clone()));
931            }
932            JoinSide::Right => {
933                seen_right = true;
934                right_proj.push((Column::new(col.name(), origin.index), alias.clone()));
935            }
936            // Synthetic column (e.g. mark): belongs to neither child.
937            // Phase 2 declines; Phase 3 keeps it at the join output instead.
938            JoinSide::None => return Ok(None),
939        }
940    }
941
942    // Parity: neither side fully dropped.
943    if left_proj.is_empty() || right_proj.is_empty() {
944        return Ok(None);
945    }
946
947    // `left_proj` / `right_proj` carry *child* indices (from `column_indices`),
948    // so the shared `update_join_*` helpers must use a 0 column-index offset for
949    // both sides (the offset bridges child -> join-output index, which is the
950    // identity here).
951    let new_filter = if let Some(filter) = filter {
952        match update_join_filter(&left_proj, &right_proj, filter, 0) {
953            Some(updated) => Some(updated),
954            None => return Ok(None),
955        }
956    } else {
957        None
958    };
959
960    let Some(new_on) = update_join_on(&left_proj, &right_proj, join_on, 0) else {
961        return Ok(None);
962    };
963
964    let (new_left, new_right) =
965        new_join_children_from_groups(&left_proj, &right_proj, join_left, join_right)?;
966
967    Ok(Some(JoinData {
968        projected_left_child: new_left,
969        projected_right_child: new_right,
970        join_filter: new_filter,
971        join_on: new_on,
972    }))
973}
974
975/// This function checks if `plan` is a [`ProjectionExec`], and inspects its
976/// input(s) to test whether it can push `plan` under its input(s). This function
977/// will operate on the entire tree and may ultimately remove `plan` entirely
978/// by leveraging source providers with built-in projection capabilities.
979pub fn remove_unnecessary_projections(
980    plan: Arc<dyn ExecutionPlan>,
981) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
982    let maybe_modified = if let Some(projection) = plan.downcast_ref::<ProjectionExec>() {
983        // If the projection does not cause any change on the input, we can
984        // safely remove it:
985        if is_projection_removable(projection) {
986            return Ok(Transformed::yes(Arc::clone(projection.input())));
987        }
988        // Swapping a projection with observable metadata can change query results
989        // by changing the metadata visible to its child expressions.
990        if projection.overrides_metadata() {
991            return Ok(Transformed::no(plan));
992        }
993        // Otherwise, check if we can push it under its child(ren):
994        projection
995            .input()
996            .try_swapping_with_projection(projection)?
997    } else {
998        return Ok(Transformed::no(plan));
999    };
1000    Ok(maybe_modified.map_or_else(|| Transformed::no(plan), Transformed::yes))
1001}
1002
1003/// Compare the inputs and outputs of the projection. All expressions must be
1004/// columns without alias, and projection does not change the order of fields.
1005/// The input and output schemas must also match exactly to preserve metadata.
1006/// For example, if the input schema is `a, b`, `SELECT a, b` is removable,
1007/// but `SELECT b, a` and `SELECT a+1, b` and `SELECT a AS c, b` are not.
1008fn is_projection_removable(projection: &ProjectionExec) -> bool {
1009    let exprs = projection.expr();
1010    exprs.iter().enumerate().all(|(idx, proj_expr)| {
1011        let Some(col) = proj_expr.expr.downcast_ref::<Column>() else {
1012            return false;
1013        };
1014        col.name() == proj_expr.alias && col.index() == idx
1015    }) && exprs.len() == projection.input().schema().fields().len()
1016        && projection.schema() == projection.input().schema()
1017}
1018
1019/// Given the expression set of a projection, checks if the projection causes
1020/// any renaming or constructs a non-`Column` physical expression.
1021pub fn all_alias_free_columns(exprs: &[ProjectionExpr]) -> bool {
1022    exprs.iter().all(|proj_expr| {
1023        proj_expr
1024            .expr
1025            .downcast_ref::<Column>()
1026            .map(|column| column.name() == proj_expr.alias)
1027            .unwrap_or(false)
1028    })
1029}
1030
1031/// Updates a source provider's projected columns according to the given
1032/// projection operator's expressions. To use this function safely, one must
1033/// ensure that all expressions are `Column` expressions without aliases.
1034pub fn new_projections_for_columns(
1035    projection: &[ProjectionExpr],
1036    source: &[usize],
1037) -> Vec<usize> {
1038    projection
1039        .iter()
1040        .filter_map(|proj_expr| {
1041            proj_expr
1042                .expr
1043                .downcast_ref::<Column>()
1044                .map(|expr| source[expr.index()])
1045        })
1046        .collect()
1047}
1048
1049/// Creates a new [`ProjectionExec`] instance with the given child plan and
1050/// projected expressions, preserving the original output metadata.
1051pub fn make_with_child(
1052    projection: &ProjectionExec,
1053    child: &Arc<dyn ExecutionPlan>,
1054) -> Result<Arc<dyn ExecutionPlan>> {
1055    ProjectionExec::try_new_with_schema_metadata(
1056        projection.expr().to_vec(),
1057        Arc::clone(child),
1058        projection.schema().as_ref(),
1059    )
1060    .map(|e| Arc::new(e) as _)
1061}
1062
1063/// Returns `true` if all the expressions in the argument are `Column`s.
1064pub fn all_columns(exprs: &[ProjectionExpr]) -> bool {
1065    exprs.iter().all(|proj_expr| proj_expr.expr.is::<Column>())
1066}
1067
1068/// Updates the given lexicographic ordering according to given projected
1069/// expressions using the [`update_expr`] function.
1070pub fn update_ordering(
1071    ordering: LexOrdering,
1072    projected_exprs: &[ProjectionExpr],
1073) -> Result<Option<LexOrdering>> {
1074    let mut updated_exprs = vec![];
1075    for mut sort_expr in ordering.into_iter() {
1076        let Some(updated_expr) = update_expr(&sort_expr.expr, projected_exprs, false)?
1077        else {
1078            return Ok(None);
1079        };
1080        sort_expr.expr = updated_expr;
1081        updated_exprs.push(sort_expr);
1082    }
1083    Ok(LexOrdering::new(updated_exprs))
1084}
1085
1086/// Updates the given lexicographic requirement according to given projected
1087/// expressions using the [`update_expr`] function.
1088pub fn update_ordering_requirement(
1089    reqs: LexRequirement,
1090    projected_exprs: &[ProjectionExpr],
1091) -> Result<Option<LexRequirement>> {
1092    let mut updated_exprs = vec![];
1093    for mut sort_expr in reqs.into_iter() {
1094        let Some(updated_expr) = update_expr(&sort_expr.expr, projected_exprs, false)?
1095        else {
1096            return Ok(None);
1097        };
1098        sort_expr.expr = updated_expr;
1099        updated_exprs.push(sort_expr);
1100    }
1101    Ok(LexRequirement::new(updated_exprs))
1102}
1103
1104/// Downcasts all the expressions in `exprs` to `Column`s. If any of the given
1105/// expressions is not a `Column`, returns `None`.
1106pub fn physical_to_column_exprs(
1107    exprs: &[ProjectionExpr],
1108) -> Option<Vec<(Column, String)>> {
1109    exprs
1110        .iter()
1111        .map(|proj_expr| {
1112            proj_expr
1113                .expr
1114                .downcast_ref::<Column>()
1115                .map(|col| (col.clone(), proj_expr.alias.clone()))
1116        })
1117        .collect()
1118}
1119
1120/// If pushing down the projection over this join's children seems possible,
1121/// this function constructs the new [`ProjectionExec`]s that will come on top
1122/// of the original children of the join.
1123pub fn new_join_children(
1124    projection_as_columns: &[(Column, String)],
1125    far_right_left_col_ind: i32,
1126    far_left_right_col_ind: i32,
1127    left_child: &Arc<dyn ExecutionPlan>,
1128    right_child: &Arc<dyn ExecutionPlan>,
1129) -> Result<(ProjectionExec, ProjectionExec)> {
1130    let new_left = ProjectionExec::try_new(
1131        projection_as_columns[0..=far_right_left_col_ind as _]
1132            .iter()
1133            .map(|(col, alias)| ProjectionExpr {
1134                expr: Arc::new(Column::new(col.name(), col.index())) as _,
1135                alias: alias.clone(),
1136            }),
1137        Arc::clone(left_child),
1138    )?;
1139    let left_size = left_child.schema().fields().len() as i32;
1140    let new_right = ProjectionExec::try_new(
1141        projection_as_columns[far_left_right_col_ind as _..]
1142            .iter()
1143            .map(|(col, alias)| {
1144                ProjectionExpr {
1145                    expr: Arc::new(Column::new(
1146                        col.name(),
1147                        // Align projected expressions coming from the right
1148                        // table with the new right child projection:
1149                        (col.index() as i32 - left_size) as _,
1150                    )) as _,
1151                    alias: alias.clone(),
1152                }
1153            }),
1154        Arc::clone(right_child),
1155    )?;
1156
1157    Ok((new_left, new_right))
1158}
1159
1160/// Build the projected left and right children from side-grouped projection
1161/// columns whose indices are already *child*-relative (e.g. derived from a
1162/// join's `ColumnIndex`). Unlike [`new_join_children`], this does not infer
1163/// child ownership from output position, so it is safe for join schemas whose
1164/// output is not a plain `left ++ right` (used by the schema-aware
1165/// `try_pushdown_through_join_with_column_indices`).
1166fn new_join_children_from_groups(
1167    left_proj: &[(Column, String)],
1168    right_proj: &[(Column, String)],
1169    left_child: &Arc<dyn ExecutionPlan>,
1170    right_child: &Arc<dyn ExecutionPlan>,
1171) -> Result<(ProjectionExec, ProjectionExec)> {
1172    let build = |cols: &[(Column, String)], child: &Arc<dyn ExecutionPlan>| {
1173        ProjectionExec::try_new(
1174            cols.iter().map(|(col, alias)| ProjectionExpr {
1175                expr: Arc::new(Column::new(col.name(), col.index())) as _,
1176                alias: alias.clone(),
1177            }),
1178            Arc::clone(child),
1179        )
1180    };
1181
1182    Ok((
1183        build(left_proj, left_child)?,
1184        build(right_proj, right_child)?,
1185    ))
1186}
1187
1188/// Checks three conditions for pushing a projection down through a join:
1189/// - Projection must narrow the join output schema.
1190/// - Columns coming from left/right tables must be collected at the left/right
1191///   sides of the output table.
1192/// - Left or right table is not lost after the projection.
1193pub fn join_allows_pushdown(
1194    projection_as_columns: &[(Column, String)],
1195    join_schema: &SchemaRef,
1196    far_right_left_col_ind: i32,
1197    far_left_right_col_ind: i32,
1198) -> bool {
1199    // Projection must narrow the join output:
1200    projection_as_columns.len() < join_schema.fields().len()
1201    // Are the columns from different tables mixed?
1202    && (far_right_left_col_ind + 1 == far_left_right_col_ind)
1203    // Left or right table is not lost after the projection.
1204    && far_right_left_col_ind >= 0
1205    && far_left_right_col_ind < projection_as_columns.len() as i32
1206}
1207
1208/// Returns the last index before encountering a column coming from the right table when traveling
1209/// through the projection from left to right, and the last index before encountering a column
1210/// coming from the left table when traveling through the projection from right to left.
1211/// If there is no column in the projection coming from the left side, it returns (-1, ...),
1212/// if there is no column in the projection coming from the right side, it returns (..., projection length).
1213pub fn join_table_borders(
1214    left_table_column_count: usize,
1215    projection_as_columns: &[(Column, String)],
1216) -> (i32, i32) {
1217    let far_right_left_col_ind = projection_as_columns
1218        .iter()
1219        .enumerate()
1220        .take_while(|(_, (projection_column, _))| {
1221            projection_column.index() < left_table_column_count
1222        })
1223        .last()
1224        .map(|(index, _)| index as i32)
1225        .unwrap_or(-1);
1226
1227    let far_left_right_col_ind = projection_as_columns
1228        .iter()
1229        .enumerate()
1230        .rev()
1231        .take_while(|(_, (projection_column, _))| {
1232            projection_column.index() >= left_table_column_count
1233        })
1234        .last()
1235        .map(|(index, _)| index as i32)
1236        .unwrap_or(projection_as_columns.len() as i32);
1237
1238    (far_right_left_col_ind, far_left_right_col_ind)
1239}
1240
1241/// Tries to update the equi-join `Column`'s of a join as if the input of
1242/// the join was replaced by a projection.
1243pub fn update_join_on(
1244    proj_left_exprs: &[(Column, String)],
1245    proj_right_exprs: &[(Column, String)],
1246    hash_join_on: &[(PhysicalExprRef, PhysicalExprRef)],
1247    left_field_size: usize,
1248) -> Option<Vec<(PhysicalExprRef, PhysicalExprRef)>> {
1249    let (left_idx, right_idx): (Vec<_>, Vec<_>) = hash_join_on
1250        .iter()
1251        .map(|(left, right)| (left, right))
1252        .unzip();
1253
1254    let new_left = new_columns_for_join_on(&left_idx, proj_left_exprs, 0)?;
1255    let new_right =
1256        new_columns_for_join_on(&right_idx, proj_right_exprs, left_field_size)?;
1257    Some(new_left.into_iter().zip(new_right).collect())
1258}
1259
1260/// Tries to update the column indices of a [`JoinFilter`] as if the input of
1261/// the join was replaced by a projection.
1262pub fn update_join_filter(
1263    projection_left_exprs: &[(Column, String)],
1264    projection_right_exprs: &[(Column, String)],
1265    join_filter: &JoinFilter,
1266    left_field_size: usize,
1267) -> Option<JoinFilter> {
1268    let mut new_left_indices = new_indices_for_join_filter(
1269        join_filter,
1270        JoinSide::Left,
1271        projection_left_exprs,
1272        0,
1273    )
1274    .into_iter();
1275    let mut new_right_indices = new_indices_for_join_filter(
1276        join_filter,
1277        JoinSide::Right,
1278        projection_right_exprs,
1279        left_field_size,
1280    )
1281    .into_iter();
1282
1283    // Check if all columns match:
1284    (new_right_indices.len() + new_left_indices.len()
1285        == join_filter.column_indices().len())
1286    .then(|| {
1287        JoinFilter::new(
1288            Arc::clone(join_filter.expression()),
1289            join_filter
1290                .column_indices()
1291                .iter()
1292                .map(|col_idx| ColumnIndex {
1293                    index: if col_idx.side == JoinSide::Left {
1294                        new_left_indices.next().unwrap()
1295                    } else {
1296                        new_right_indices.next().unwrap()
1297                    },
1298                    side: col_idx.side,
1299                })
1300                .collect(),
1301            Arc::clone(join_filter.schema()),
1302        )
1303    })
1304}
1305
1306/// Collapse a chain of consecutive [`ProjectionExec`]s into one. Returns
1307/// `None` if nothing could be merged.
1308///
1309/// The projection-removal optimizer checks `outer.overrides_metadata()` before
1310/// reaching this helper. The unified projection also keeps `outer`'s schema, so
1311/// collapsing cannot lose its output metadata. Inner projections still need the
1312/// check below because outer expressions may observe their metadata.
1313fn try_collapse_projection_chain(
1314    outer: &ProjectionExec,
1315) -> Result<Option<Arc<dyn ExecutionPlan>>> {
1316    let mut current_exprs: Vec<ProjectionExpr> = outer.expr().to_vec();
1317    let mut current_input: Arc<dyn ExecutionPlan> = Arc::clone(outer.input());
1318    let mut column_ref_map: HashMap<Column, usize> = HashMap::new();
1319    let mut collapsed_any = false;
1320
1321    'outer: while let Some(inner_proj) = current_input.downcast_ref::<ProjectionExec>() {
1322        if inner_proj.overrides_metadata() {
1323            break;
1324        }
1325
1326        // Collect the column references usage in the outer projection.
1327        column_ref_map.clear();
1328        for proj_expr in &current_exprs {
1329            proj_expr.expr.apply(|expr| {
1330                if let Some(column) = expr.downcast_ref::<Column>() {
1331                    *column_ref_map.entry(column.clone()).or_default() += 1;
1332                }
1333                Ok(TreeNodeRecursion::Continue)
1334            })?;
1335        }
1336        let inner_exprs = inner_proj.expr();
1337        // Merging these projections is not beneficial, e.g
1338        // If an expression is not trivial (KeepInPlace) and it is referred more than 1, unifies projections will be
1339        // beneficial as caching mechanism for non-trivial computations.
1340        // See discussion in: https://github.com/apache/datafusion/issues/8296
1341        let blocked = column_ref_map.iter().any(|(column, count)| {
1342            *count > 1
1343                && !inner_exprs[column.index()]
1344                    .expr
1345                    .placement()
1346                    .should_push_to_leaves()
1347        });
1348        if blocked {
1349            break;
1350        }
1351
1352        let mut new_phys: Vec<Arc<dyn PhysicalExpr>> =
1353            Vec::with_capacity(current_exprs.len());
1354        for proj_expr in &current_exprs {
1355            // If there is no match in the input projection, we cannot unify these
1356            // projections. This case will arise if the projection expression contains
1357            // a `PhysicalExpr` variant `update_expr` doesn't support.
1358            let Some(expr) = update_expr(&proj_expr.expr, inner_exprs, true)? else {
1359                break 'outer;
1360            };
1361            new_phys.push(expr);
1362        }
1363        for (proj_expr, expr) in current_exprs.iter_mut().zip(new_phys) {
1364            proj_expr.expr = expr;
1365        }
1366        current_input = Arc::clone(inner_proj.input());
1367        collapsed_any = true;
1368    }
1369
1370    if !collapsed_any {
1371        return Ok(None);
1372    }
1373
1374    // To unify 3 or more sequential projections:
1375    // Preserve the outer projection's output metadata.
1376    let unified: Arc<dyn ExecutionPlan> =
1377        Arc::new(ProjectionExec::try_new_with_schema_metadata(
1378            current_exprs,
1379            current_input,
1380            outer.schema().as_ref(),
1381        )?);
1382    remove_unnecessary_projections(unified).data().map(Some)
1383}
1384
1385/// Collect all column indices from the given projection expressions.
1386fn collect_column_indices(exprs: &[ProjectionExpr]) -> Vec<usize> {
1387    // Collect column indices in a deterministic order that preserves the
1388    // projection's column ordering. For simple Column expressions, we use
1389    // the column index directly. For complex expressions, we walk the
1390    // expression tree to collect column references in traversal order.
1391    // This allows the embedded projection to match the desired output
1392    // column order, avoiding a residual ProjectionExec.
1393    let mut seen = std::collections::HashSet::new();
1394    let mut indices = Vec::new();
1395    for proj_expr in exprs {
1396        if let Some(col) = proj_expr.expr.downcast_ref::<Column>() {
1397            // Simple column reference: preserve projection order.
1398            if seen.insert(col.index()) {
1399                indices.push(col.index());
1400            }
1401        } else {
1402            // Complex expression: collect all referenced columns in
1403            // expression tree traversal order (deterministic) to preserve
1404            // the natural ordering of column references.
1405            proj_expr
1406                .expr
1407                .apply(|expr| {
1408                    if let Some(col) = expr.downcast_ref::<Column>()
1409                        && seen.insert(col.index())
1410                    {
1411                        indices.push(col.index());
1412                    }
1413                    Ok(TreeNodeRecursion::Continue)
1414                })
1415                .expect("closure always returns OK");
1416        }
1417    }
1418    indices
1419}
1420
1421/// This function determines and returns a vector of indices representing the
1422/// positions of columns in `projection_exprs` that are involved in `join_filter`,
1423/// and correspond to a particular side (`join_side`) of the join operation.
1424///
1425/// Notes: Column indices in the projection expressions are based on the join schema,
1426/// whereas the join filter is based on the join child schema. `column_index_offset`
1427/// represents the offset between them.
1428fn new_indices_for_join_filter(
1429    join_filter: &JoinFilter,
1430    join_side: JoinSide,
1431    projection_exprs: &[(Column, String)],
1432    column_index_offset: usize,
1433) -> Vec<usize> {
1434    join_filter
1435        .column_indices()
1436        .iter()
1437        .filter(|col_idx| col_idx.side == join_side)
1438        .filter_map(|col_idx| {
1439            projection_exprs
1440                .iter()
1441                .position(|(col, _)| col_idx.index + column_index_offset == col.index())
1442        })
1443        .collect()
1444}
1445
1446/// This function generates a new set of columns to be used in a hash join
1447/// operation based on a set of equi-join conditions (`hash_join_on`) and a
1448/// list of projection expressions (`projection_exprs`).
1449///
1450/// Notes: Column indices in the projection expressions are based on the join schema,
1451/// whereas the join on expressions are based on the join child schema. `column_index_offset`
1452/// represents the offset between them.
1453fn new_columns_for_join_on(
1454    hash_join_on: &[&PhysicalExprRef],
1455    projection_exprs: &[(Column, String)],
1456    column_index_offset: usize,
1457) -> Option<Vec<PhysicalExprRef>> {
1458    let new_columns = hash_join_on
1459        .iter()
1460        .filter_map(|on| {
1461            // Rewrite all columns in `on`
1462            Arc::clone(*on)
1463                .transform(|expr| {
1464                    if let Some(column) = expr.downcast_ref::<Column>() {
1465                        // Find the column in the projection expressions
1466                        let new_column = projection_exprs
1467                            .iter()
1468                            .enumerate()
1469                            .find(|(_, (proj_column, _))| {
1470                                column.name() == proj_column.name()
1471                                    && column.index() + column_index_offset
1472                                        == proj_column.index()
1473                            })
1474                            .map(|(index, (_, alias))| Column::new(alias, index));
1475                        if let Some(new_column) = new_column {
1476                            Ok(Transformed::yes(Arc::new(new_column)))
1477                        } else {
1478                            // If the column is not found in the projection expressions,
1479                            // it means that the column is not projected. In this case,
1480                            // we cannot push the projection down.
1481                            internal_err!(
1482                                "Column {:?} not found in projection expressions",
1483                                column
1484                            )
1485                        }
1486                    } else {
1487                        Ok(Transformed::no(expr))
1488                    }
1489                })
1490                .data()
1491                .ok()
1492        })
1493        .collect::<Vec<_>>();
1494    (new_columns.len() == hash_join_on.len()).then_some(new_columns)
1495}
1496
1497#[cfg(test)]
1498mod tests {
1499    use super::*;
1500
1501    use crate::common::collect;
1502    use crate::empty::EmptyExec;
1503    use crate::filter::FilterExec;
1504
1505    use crate::filter_pushdown::PushedDown;
1506    use crate::statistics::{StatisticsArgs, StatisticsContext};
1507    use crate::test;
1508    use crate::test::exec::StatisticsExec;
1509
1510    use arrow::array::StringArray;
1511    use arrow::datatypes::{DataType, Field, Schema};
1512    use datafusion_common::ScalarValue;
1513    use datafusion_common::stats::{ColumnStatistics, Precision, Statistics};
1514
1515    use datafusion_expr::{Operator, ScalarUDF};
1516    use datafusion_functions::core::arrow_metadata::ArrowMetadataFunc;
1517    use datafusion_physical_expr::ScalarFunctionExpr;
1518    use datafusion_physical_expr::expressions::{
1519        BinaryExpr, Column, DynamicFilterPhysicalExpr, Literal, binary, col, is_null, lit,
1520    };
1521
1522    #[test]
1523    fn test_try_new_with_schema_metadata_only_replaces_metadata() -> Result<()> {
1524        let input_schema = Arc::new(Schema::new(vec![Field::new(
1525            "input",
1526            DataType::Int32,
1527            false,
1528        )]));
1529        let input: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(input_schema));
1530        let field_metadata =
1531            HashMap::from([("field-key".to_string(), "field-value".to_string())]);
1532        let schema_metadata =
1533            HashMap::from([("schema-key".to_string(), "schema-value".to_string())]);
1534        let metadata_schema = Schema::new_with_metadata(
1535            vec![
1536                Field::new("ignored", DataType::Utf8, true)
1537                    .with_metadata(field_metadata.clone()),
1538            ],
1539            schema_metadata.clone(),
1540        );
1541
1542        let projection = ProjectionExec::try_new_with_schema_metadata(
1543            [ProjectionExpr {
1544                expr: Arc::new(Column::new("input", 0)),
1545                alias: "output".to_string(),
1546            }],
1547            input,
1548            &metadata_schema,
1549        )?;
1550
1551        let expected_schema = Arc::new(Schema::new_with_metadata(
1552            vec![
1553                Field::new("output", DataType::Int32, false)
1554                    .with_metadata(field_metadata),
1555            ],
1556            schema_metadata,
1557        ));
1558        assert_eq!(projection.schema(), expected_schema);
1559        Ok(())
1560    }
1561
1562    fn identity_projection_with_metadata(
1563        input: Arc<dyn ExecutionPlan>,
1564        field_metadata: HashMap<String, String>,
1565        schema_metadata: HashMap<String, String>,
1566    ) -> Result<Arc<dyn ExecutionPlan>> {
1567        let metadata_schema = Schema::new_with_metadata(
1568            vec![Field::new("i", DataType::Int32, true).with_metadata(field_metadata)],
1569            schema_metadata,
1570        );
1571        Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata(
1572            [ProjectionExpr {
1573                expr: Arc::new(Column::new("i", 0)),
1574                alias: "i".to_string(),
1575            }],
1576            input,
1577            &metadata_schema,
1578        )?))
1579    }
1580
1581    #[test]
1582    fn test_field_metadata_projection_is_not_removable() -> Result<()> {
1583        let projection = identity_projection_with_metadata(
1584            test::scan_partitioned(1),
1585            HashMap::from([("event_field".to_string(), "true".to_string())]),
1586            HashMap::new(),
1587        )?;
1588        let expected_schema = projection.schema();
1589
1590        let optimized = remove_unnecessary_projections(projection)?.data;
1591
1592        assert!(optimized.downcast_ref::<ProjectionExec>().is_some());
1593        assert_eq!(optimized.schema(), expected_schema);
1594        Ok(())
1595    }
1596
1597    #[test]
1598    fn test_schema_metadata_projection_is_not_removable() -> Result<()> {
1599        let projection = identity_projection_with_metadata(
1600            test::scan_partitioned(1),
1601            HashMap::new(),
1602            HashMap::from([("schema-key".to_string(), "schema-value".to_string())]),
1603        )?;
1604        let expected_schema = projection.schema();
1605
1606        let optimized = remove_unnecessary_projections(projection)?.data;
1607
1608        assert!(optimized.downcast_ref::<ProjectionExec>().is_some());
1609        assert_eq!(optimized.schema(), expected_schema);
1610        Ok(())
1611    }
1612
1613    #[test]
1614    fn test_replace_children_recomputes_metadata_override() -> Result<()> {
1615        let field_metadata =
1616            HashMap::from([("event_field".to_string(), "true".to_string())]);
1617        let projection = identity_projection_with_metadata(
1618            test::scan_partitioned(1),
1619            field_metadata.clone(),
1620            HashMap::new(),
1621        )?;
1622        assert!(
1623            projection
1624                .downcast_ref::<ProjectionExec>()
1625                .expect("test plan should be a ProjectionExec")
1626                .overrides_metadata()
1627        );
1628
1629        let replacement_schema = Arc::new(Schema::new(vec![
1630            Field::new("i", DataType::Int32, true).with_metadata(field_metadata),
1631        ]));
1632        let replacement: Arc<dyn ExecutionPlan> =
1633            Arc::new(EmptyExec::new(replacement_schema));
1634        let replaced = projection.replace_children(
1635            vec![replacement],
1636            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
1637        )?;
1638
1639        assert!(
1640            !replaced
1641                .downcast_ref::<ProjectionExec>()
1642                .expect("replaced plan should be a ProjectionExec")
1643                .overrides_metadata()
1644        );
1645        Ok(())
1646    }
1647
1648    #[test]
1649    fn test_make_with_child_preserves_output_metadata() -> Result<()> {
1650        let projection = identity_projection_with_metadata(
1651            test::scan_partitioned(1),
1652            HashMap::from([("event_field".to_string(), "true".to_string())]),
1653            HashMap::from([("schema-key".to_string(), "schema-value".to_string())]),
1654        )?;
1655        let projection = projection
1656            .downcast_ref::<ProjectionExec>()
1657            .expect("test plan should be a ProjectionExec");
1658
1659        let rebuilt = make_with_child(projection, &test::scan_partitioned(1))?;
1660
1661        assert_eq!(rebuilt.schema(), projection.schema());
1662        Ok(())
1663    }
1664
1665    #[tokio::test]
1666    async fn test_metadata_observing_parent_blocks_projection_collapse() -> Result<()> {
1667        let inner = identity_projection_with_metadata(
1668            test::scan_partitioned(1),
1669            HashMap::from([("event_field".to_string(), "true".to_string())]),
1670            HashMap::new(),
1671        )?;
1672        let arrow_metadata = ScalarFunctionExpr::new(
1673            "arrow_metadata",
1674            Arc::new(ScalarUDF::new_from_impl(ArrowMetadataFunc::new())),
1675            vec![
1676                Arc::new(Column::new("i", 0)),
1677                Arc::new(Literal::new(ScalarValue::Utf8(Some(
1678                    "event_field".to_string(),
1679                )))),
1680            ],
1681            Arc::new(Field::new("arrow_metadata", DataType::Utf8, true)),
1682            Arc::new(ConfigOptions::default()),
1683        );
1684        let outer: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
1685            [ProjectionExpr {
1686                expr: Arc::new(arrow_metadata),
1687                alias: "metadata".to_string(),
1688            }],
1689            inner,
1690        )?);
1691
1692        let outer_projection = outer
1693            .downcast_ref::<ProjectionExec>()
1694            .expect("test plan should be a ProjectionExec");
1695        assert!(try_collapse_projection_chain(outer_projection)?.is_none());
1696
1697        let optimized = remove_unnecessary_projections(outer)?.data;
1698        let batches =
1699            collect(optimized.execute(0, Arc::new(TaskContext::default()))?).await?;
1700        let values = batches[0]
1701            .column(0)
1702            .as_any()
1703            .downcast_ref::<StringArray>()
1704            .expect("metadata expression should return Utf8");
1705        assert_eq!(values.value(0), "true");
1706        Ok(())
1707    }
1708
1709    #[tokio::test]
1710    async fn test_metadata_observing_filter_blocks_projection_pushdown() -> Result<()> {
1711        let widened: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
1712            [
1713                ProjectionExpr {
1714                    expr: Arc::new(Column::new("i", 0)),
1715                    alias: "i".to_string(),
1716                },
1717                ProjectionExpr {
1718                    expr: Arc::new(Column::new("i", 0)),
1719                    alias: "j".to_string(),
1720                },
1721            ],
1722            test::scan_partitioned(1),
1723        )?);
1724        let arrow_metadata = Arc::new(ScalarFunctionExpr::new(
1725            "arrow_metadata",
1726            Arc::new(ScalarUDF::new_from_impl(ArrowMetadataFunc::new())),
1727            vec![
1728                Arc::new(Column::new("i", 0)),
1729                Arc::new(Literal::new(ScalarValue::Utf8(Some(
1730                    "event_field".to_string(),
1731                )))),
1732            ],
1733            Arc::new(Field::new("arrow_metadata", DataType::Utf8, true)),
1734            Arc::new(ConfigOptions::default()),
1735        ));
1736        let filter: Arc<dyn ExecutionPlan> =
1737            Arc::new(FilterExec::try_new(is_null(arrow_metadata)?, widened)?);
1738        let projection = identity_projection_with_metadata(
1739            filter,
1740            HashMap::from([("event_field".to_string(), "true".to_string())]),
1741            HashMap::new(),
1742        )?;
1743        let expected_schema = projection.schema();
1744
1745        let optimized = remove_unnecessary_projections(projection)?.data;
1746        assert_eq!(optimized.schema(), expected_schema);
1747        let batches =
1748            collect(optimized.execute(0, Arc::new(TaskContext::default()))?).await?;
1749
1750        assert_eq!(
1751            batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
1752            100
1753        );
1754        Ok(())
1755    }
1756
1757    // A schema-only metadata override must block projection embedding. The filter
1758    // rebuilds the schema from expressions and would otherwise drop this metadata.
1759    #[tokio::test]
1760    async fn test_schema_level_metadata_blocks_projection_embedding() -> Result<()> {
1761        let scan = test::scan_partitioned(1);
1762        let predicate = binary(
1763            col("i", &scan.schema())?,
1764            Operator::Gt,
1765            lit(ScalarValue::Int32(Some(-1))),
1766            &scan.schema(),
1767        )?;
1768        let filter: Arc<dyn ExecutionPlan> =
1769            Arc::new(FilterExec::try_new(predicate, scan)?);
1770        let projection = identity_projection_with_metadata(
1771            filter,
1772            HashMap::new(),
1773            HashMap::from([("schema-key".to_string(), "schema-value".to_string())]),
1774        )?;
1775        // Field metadata matches, so this checks the schema-level comparison.
1776        let projection_exec = projection
1777            .downcast_ref::<ProjectionExec>()
1778            .expect("test plan should be a ProjectionExec");
1779        assert!(projection_exec.overrides_metadata());
1780        let expected_schema = projection.schema();
1781
1782        let optimized = remove_unnecessary_projections(projection)?.data;
1783
1784        assert_eq!(optimized.schema(), expected_schema);
1785        assert_eq!(
1786            optimized.schema().metadata(),
1787            &HashMap::from([("schema-key".to_string(), "schema-value".to_string())])
1788        );
1789
1790        let batches =
1791            collect(optimized.execute(0, Arc::new(TaskContext::default()))?).await?;
1792        assert_eq!(
1793            batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
1794            100
1795        );
1796        Ok(())
1797    }
1798
1799    #[test]
1800    fn test_collect_column_indices() -> Result<()> {
1801        let expr = Arc::new(BinaryExpr::new(
1802            Arc::new(Column::new("b", 7)),
1803            Operator::Minus,
1804            Arc::new(BinaryExpr::new(
1805                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1806                Operator::Plus,
1807                Arc::new(Column::new("a", 1)),
1808            )),
1809        ));
1810        let column_indices = collect_column_indices(&[ProjectionExpr {
1811            expr,
1812            alias: "b-(1+a)".to_string(),
1813        }]);
1814        // Tree traversal order: b@7 is visited before a@1
1815        assert_eq!(column_indices, vec![7, 1]);
1816        Ok(())
1817    }
1818
1819    #[test]
1820    fn test_try_pushdown_through_join_validates_column_indices() -> Result<()> {
1821        let child_schema =
1822            Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
1823        let left: Arc<dyn ExecutionPlan> =
1824            Arc::new(EmptyExec::new(Arc::clone(&child_schema)));
1825        let right: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(child_schema));
1826        let join_schema = Arc::new(Schema::new(vec![
1827            Field::new("left_i", DataType::Int32, false),
1828            Field::new("right_i", DataType::Int32, false),
1829        ]));
1830        let join: Arc<dyn ExecutionPlan> =
1831            Arc::new(EmptyExec::new(Arc::clone(&join_schema)));
1832        let projection = ProjectionExec::try_new(
1833            vec![ProjectionExpr {
1834                expr: Arc::new(Column::new("left_i", 0)),
1835                alias: "left_i".to_string(),
1836            }],
1837            join,
1838        )?;
1839
1840        let Err(error) = try_pushdown_through_join_with_column_indices(
1841            &projection,
1842            &left,
1843            &right,
1844            &[],
1845            &join_schema,
1846            None,
1847            &[],
1848        ) else {
1849            panic!("expected a mismatched mapping length to return an error");
1850        };
1851        assert!(
1852            error.to_string().contains(
1853                "Column index mapping has 0 entries but join schema has 2 fields"
1854            )
1855        );
1856
1857        let invalid_child_index = [
1858            ColumnIndex {
1859                index: 1,
1860                side: JoinSide::Left,
1861            },
1862            ColumnIndex {
1863                index: 0,
1864                side: JoinSide::Right,
1865            },
1866        ];
1867        let Err(error) = try_pushdown_through_join_with_column_indices(
1868            &projection,
1869            &left,
1870            &right,
1871            &[],
1872            &join_schema,
1873            None,
1874            &invalid_child_index,
1875        ) else {
1876            panic!("expected an invalid child index to return an error");
1877        };
1878        assert!(error.to_string().contains(
1879            "Join output column 0 maps to left child column 1, but the child has 1 fields"
1880        ));
1881
1882        let wider_join_schema = Arc::new(Schema::new(vec![
1883            Field::new("left_i", DataType::Int32, false),
1884            Field::new("right_i", DataType::Int32, false),
1885            Field::new("extra", DataType::Int32, false),
1886        ]));
1887        let wider_join: Arc<dyn ExecutionPlan> =
1888            Arc::new(EmptyExec::new(wider_join_schema));
1889        let out_of_mapping_projection = ProjectionExec::try_new(
1890            vec![ProjectionExpr {
1891                expr: Arc::new(Column::new("extra", 2)),
1892                alias: "extra".to_string(),
1893            }],
1894            wider_join,
1895        )?;
1896        let valid_child_indices = [
1897            ColumnIndex {
1898                index: 0,
1899                side: JoinSide::Left,
1900            },
1901            ColumnIndex {
1902                index: 0,
1903                side: JoinSide::Right,
1904            },
1905        ];
1906        let Err(error) = try_pushdown_through_join_with_column_indices(
1907            &out_of_mapping_projection,
1908            &left,
1909            &right,
1910            &[],
1911            &join_schema,
1912            None,
1913            &valid_child_indices,
1914        ) else {
1915            panic!("expected an out-of-mapping projection to return an error");
1916        };
1917        assert!(
1918            error.to_string().contains(
1919                "Projection column 2 is outside the 2-entry column index mapping"
1920            )
1921        );
1922
1923        Ok(())
1924    }
1925
1926    #[test]
1927    fn test_join_table_borders() -> Result<()> {
1928        let projections = vec![
1929            (Column::new("b", 1), "b".to_owned()),
1930            (Column::new("c", 2), "c".to_owned()),
1931            (Column::new("e", 4), "e".to_owned()),
1932            (Column::new("d", 3), "d".to_owned()),
1933            (Column::new("c", 2), "c".to_owned()),
1934            (Column::new("f", 5), "f".to_owned()),
1935            (Column::new("h", 7), "h".to_owned()),
1936            (Column::new("g", 6), "g".to_owned()),
1937        ];
1938        let left_table_column_count = 5;
1939        assert_eq!(
1940            join_table_borders(left_table_column_count, &projections),
1941            (4, 5)
1942        );
1943
1944        let left_table_column_count = 8;
1945        assert_eq!(
1946            join_table_borders(left_table_column_count, &projections),
1947            (7, 8)
1948        );
1949
1950        let left_table_column_count = 1;
1951        assert_eq!(
1952            join_table_borders(left_table_column_count, &projections),
1953            (-1, 0)
1954        );
1955
1956        let projections = vec![
1957            (Column::new("a", 0), "a".to_owned()),
1958            (Column::new("b", 1), "b".to_owned()),
1959            (Column::new("d", 3), "d".to_owned()),
1960            (Column::new("g", 6), "g".to_owned()),
1961            (Column::new("e", 4), "e".to_owned()),
1962            (Column::new("f", 5), "f".to_owned()),
1963            (Column::new("e", 4), "e".to_owned()),
1964            (Column::new("h", 7), "h".to_owned()),
1965        ];
1966        let left_table_column_count = 5;
1967        assert_eq!(
1968            join_table_borders(left_table_column_count, &projections),
1969            (2, 7)
1970        );
1971
1972        let left_table_column_count = 7;
1973        assert_eq!(
1974            join_table_borders(left_table_column_count, &projections),
1975            (6, 7)
1976        );
1977
1978        Ok(())
1979    }
1980
1981    #[tokio::test]
1982    async fn project_no_column() -> Result<()> {
1983        let task_ctx = Arc::new(TaskContext::default());
1984
1985        let exec = test::scan_partitioned(1);
1986        let expected = collect(exec.execute(0, Arc::clone(&task_ctx))?).await?;
1987
1988        let projection = ProjectionExec::try_new(vec![] as Vec<ProjectionExpr>, exec)?;
1989        let stream = projection.execute(0, Arc::clone(&task_ctx))?;
1990        let output = collect(stream).await?;
1991        assert_eq!(output.len(), expected.len());
1992
1993        Ok(())
1994    }
1995
1996    #[tokio::test]
1997    async fn project_old_syntax() {
1998        let exec = test::scan_partitioned(1);
1999        let schema = exec.schema();
2000        let expr = col("i", &schema).unwrap();
2001        ProjectionExec::try_new(
2002            vec![
2003                // use From impl of ProjectionExpr to create ProjectionExpr
2004                // to test old syntax
2005                (expr, "c".to_string()),
2006            ],
2007            exec,
2008        )
2009        // expect this to succeed
2010        .unwrap();
2011    }
2012
2013    #[test]
2014    fn test_projection_statistics_uses_input_schema() {
2015        let input_schema = Schema::new(vec![
2016            Field::new("a", DataType::Int32, false),
2017            Field::new("b", DataType::Int32, false),
2018            Field::new("c", DataType::Int32, false),
2019            Field::new("d", DataType::Int32, false),
2020            Field::new("e", DataType::Int32, false),
2021            Field::new("f", DataType::Int32, false),
2022        ]);
2023
2024        let input_statistics = Statistics {
2025            num_rows: Precision::Exact(10),
2026            column_statistics: vec![
2027                ColumnStatistics {
2028                    min_value: Precision::Exact(ScalarValue::Int32(Some(1))),
2029                    max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
2030                    ..Default::default()
2031                },
2032                ColumnStatistics {
2033                    min_value: Precision::Exact(ScalarValue::Int32(Some(5))),
2034                    max_value: Precision::Exact(ScalarValue::Int32(Some(50))),
2035                    ..Default::default()
2036                },
2037                ColumnStatistics {
2038                    min_value: Precision::Exact(ScalarValue::Int32(Some(10))),
2039                    max_value: Precision::Exact(ScalarValue::Int32(Some(40))),
2040                    ..Default::default()
2041                },
2042                ColumnStatistics {
2043                    min_value: Precision::Exact(ScalarValue::Int32(Some(20))),
2044                    max_value: Precision::Exact(ScalarValue::Int32(Some(30))),
2045                    ..Default::default()
2046                },
2047                ColumnStatistics {
2048                    min_value: Precision::Exact(ScalarValue::Int32(Some(21))),
2049                    max_value: Precision::Exact(ScalarValue::Int32(Some(29))),
2050                    ..Default::default()
2051                },
2052                ColumnStatistics {
2053                    min_value: Precision::Exact(ScalarValue::Int32(Some(24))),
2054                    max_value: Precision::Exact(ScalarValue::Int32(Some(26))),
2055                    ..Default::default()
2056                },
2057            ],
2058            ..Default::default()
2059        };
2060
2061        let input = Arc::new(StatisticsExec::new(input_statistics, input_schema));
2062
2063        // Create projection expressions that reference columns from the input schema and the length
2064        // of output schema columns < input schema columns and hence if we use the last few columns
2065        // from the input schema in the expressions here, bounds_check would fail on them if output
2066        // schema is supplied to the partitions_statistics method.
2067        let exprs: Vec<ProjectionExpr> = vec![
2068            ProjectionExpr {
2069                expr: Arc::new(Column::new("c", 2)) as Arc<dyn PhysicalExpr>,
2070                alias: "c_renamed".to_string(),
2071            },
2072            ProjectionExpr {
2073                expr: Arc::new(BinaryExpr::new(
2074                    Arc::new(Column::new("e", 4)),
2075                    Operator::Plus,
2076                    Arc::new(Column::new("f", 5)),
2077                )) as Arc<dyn PhysicalExpr>,
2078                alias: "e_plus_f".to_string(),
2079            },
2080        ];
2081
2082        let projection = ProjectionExec::try_new(exprs, input).unwrap();
2083
2084        let stats = StatisticsContext::new()
2085            .compute(&projection, &StatisticsArgs::new())
2086            .unwrap();
2087
2088        assert_eq!(stats.num_rows, Precision::Exact(10));
2089        assert_eq!(
2090            stats.column_statistics.len(),
2091            2,
2092            "Expected 2 columns in projection statistics"
2093        );
2094        assert!(stats.total_byte_size.is_exact().unwrap_or(false));
2095    }
2096
2097    #[test]
2098    fn test_filter_pushdown_with_alias() -> Result<()> {
2099        let input_schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2100        let input = Arc::new(StatisticsExec::new(
2101            Statistics::new_unknown(&input_schema),
2102            input_schema.clone(),
2103        ));
2104
2105        // project "a" as "b"
2106        let projection = ProjectionExec::try_new(
2107            vec![ProjectionExpr {
2108                expr: Arc::new(Column::new("a", 0)),
2109                alias: "b".to_string(),
2110            }],
2111            input,
2112        )?;
2113
2114        // filter "b > 5"
2115        let filter = Arc::new(BinaryExpr::new(
2116            Arc::new(Column::new("b", 0)),
2117            Operator::Gt,
2118            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2119        )) as Arc<dyn PhysicalExpr>;
2120
2121        let description = projection.gather_filters_for_pushdown(
2122            FilterPushdownPhase::Post,
2123            vec![filter],
2124            &ConfigOptions::default(),
2125        )?;
2126
2127        // Should be converted to "a > 5"
2128        // "a" is index 0 in input
2129        let expected_filter = Arc::new(BinaryExpr::new(
2130            Arc::new(Column::new("a", 0)),
2131            Operator::Gt,
2132            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2133        )) as Arc<dyn PhysicalExpr>;
2134
2135        assert_eq!(description.self_filters(), vec![vec![]]);
2136        let pushed_filters = &description.parent_filters()[0];
2137        assert_eq!(
2138            format!("{}", pushed_filters[0].predicate),
2139            format!("{}", expected_filter)
2140        );
2141        // Verify the predicate was actually pushed down
2142        assert!(matches!(pushed_filters[0].discriminant, PushedDown::Yes));
2143
2144        Ok(())
2145    }
2146
2147    #[test]
2148    fn test_filter_pushdown_with_multiple_aliases() -> Result<()> {
2149        let input_schema = Schema::new(vec![
2150            Field::new("a", DataType::Int32, false),
2151            Field::new("b", DataType::Int32, false),
2152        ]);
2153        let input = Arc::new(StatisticsExec::new(
2154            Statistics {
2155                column_statistics: vec![Default::default(); input_schema.fields().len()],
2156                ..Default::default()
2157            },
2158            input_schema.clone(),
2159        ));
2160
2161        // project "a" as "x", "b" as "y"
2162        let projection = ProjectionExec::try_new(
2163            vec![
2164                ProjectionExpr {
2165                    expr: Arc::new(Column::new("a", 0)),
2166                    alias: "x".to_string(),
2167                },
2168                ProjectionExpr {
2169                    expr: Arc::new(Column::new("b", 1)),
2170                    alias: "y".to_string(),
2171                },
2172            ],
2173            input,
2174        )?;
2175
2176        // filter "x > 5"
2177        let filter1 = Arc::new(BinaryExpr::new(
2178            Arc::new(Column::new("x", 0)),
2179            Operator::Gt,
2180            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2181        )) as Arc<dyn PhysicalExpr>;
2182
2183        // filter "y < 10"
2184        let filter2 = Arc::new(BinaryExpr::new(
2185            Arc::new(Column::new("y", 1)),
2186            Operator::Lt,
2187            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
2188        )) as Arc<dyn PhysicalExpr>;
2189
2190        let description = projection.gather_filters_for_pushdown(
2191            FilterPushdownPhase::Post,
2192            vec![filter1, filter2],
2193            &ConfigOptions::default(),
2194        )?;
2195
2196        // Should be converted to "a > 5" and "b < 10"
2197        let expected_filter1 = Arc::new(BinaryExpr::new(
2198            Arc::new(Column::new("a", 0)),
2199            Operator::Gt,
2200            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2201        )) as Arc<dyn PhysicalExpr>;
2202
2203        let expected_filter2 = Arc::new(BinaryExpr::new(
2204            Arc::new(Column::new("b", 1)),
2205            Operator::Lt,
2206            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
2207        )) as Arc<dyn PhysicalExpr>;
2208
2209        let pushed_filters = &description.parent_filters()[0];
2210        assert_eq!(pushed_filters.len(), 2);
2211        // Note: The order of filters is preserved
2212        assert_eq!(
2213            format!("{}", pushed_filters[0].predicate),
2214            format!("{}", expected_filter1)
2215        );
2216        assert_eq!(
2217            format!("{}", pushed_filters[1].predicate),
2218            format!("{}", expected_filter2)
2219        );
2220        // Verify the predicates were actually pushed down
2221        assert!(matches!(pushed_filters[0].discriminant, PushedDown::Yes));
2222        assert!(matches!(pushed_filters[1].discriminant, PushedDown::Yes));
2223
2224        Ok(())
2225    }
2226
2227    #[test]
2228    fn test_filter_pushdown_with_swapped_aliases() -> Result<()> {
2229        let input_schema = Schema::new(vec![
2230            Field::new("a", DataType::Int32, false),
2231            Field::new("b", DataType::Int32, false),
2232        ]);
2233        let input = Arc::new(StatisticsExec::new(
2234            Statistics {
2235                column_statistics: vec![Default::default(); input_schema.fields().len()],
2236                ..Default::default()
2237            },
2238            input_schema.clone(),
2239        ));
2240
2241        // project "a" as "b", "b" as "a"
2242        let projection = ProjectionExec::try_new(
2243            vec![
2244                ProjectionExpr {
2245                    expr: Arc::new(Column::new("a", 0)),
2246                    alias: "b".to_string(),
2247                },
2248                ProjectionExpr {
2249                    expr: Arc::new(Column::new("b", 1)),
2250                    alias: "a".to_string(),
2251                },
2252            ],
2253            input,
2254        )?;
2255
2256        // filter "b > 5" (output column 0, which is "a" in input)
2257        let filter1 = Arc::new(BinaryExpr::new(
2258            Arc::new(Column::new("b", 0)),
2259            Operator::Gt,
2260            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2261        )) as Arc<dyn PhysicalExpr>;
2262
2263        // filter "a < 10" (output column 1, which is "b" in input)
2264        let filter2 = Arc::new(BinaryExpr::new(
2265            Arc::new(Column::new("a", 1)),
2266            Operator::Lt,
2267            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
2268        )) as Arc<dyn PhysicalExpr>;
2269
2270        let description = projection.gather_filters_for_pushdown(
2271            FilterPushdownPhase::Post,
2272            vec![filter1, filter2],
2273            &ConfigOptions::default(),
2274        )?;
2275
2276        let pushed_filters = &description.parent_filters()[0];
2277        assert_eq!(pushed_filters.len(), 2);
2278
2279        // "b" (output index 0) -> "a" (input index 0)
2280        let expected_filter1 = "a@0 > 5";
2281        // "a" (output index 1) -> "b" (input index 1)
2282        let expected_filter2 = "b@1 < 10";
2283
2284        assert_eq!(format!("{}", pushed_filters[0].predicate), expected_filter1);
2285        assert_eq!(format!("{}", pushed_filters[1].predicate), expected_filter2);
2286        // Verify the predicates were actually pushed down
2287        assert!(matches!(pushed_filters[0].discriminant, PushedDown::Yes));
2288        assert!(matches!(pushed_filters[1].discriminant, PushedDown::Yes));
2289
2290        Ok(())
2291    }
2292
2293    #[test]
2294    fn test_filter_pushdown_with_mixed_columns() -> Result<()> {
2295        let input_schema = Schema::new(vec![
2296            Field::new("a", DataType::Int32, false),
2297            Field::new("b", DataType::Int32, false),
2298        ]);
2299        let input = Arc::new(StatisticsExec::new(
2300            Statistics {
2301                column_statistics: vec![Default::default(); input_schema.fields().len()],
2302                ..Default::default()
2303            },
2304            input_schema.clone(),
2305        ));
2306
2307        // project "a" as "x", "b" as "b" (pass through)
2308        let projection = ProjectionExec::try_new(
2309            vec![
2310                ProjectionExpr {
2311                    expr: Arc::new(Column::new("a", 0)),
2312                    alias: "x".to_string(),
2313                },
2314                ProjectionExpr {
2315                    expr: Arc::new(Column::new("b", 1)),
2316                    alias: "b".to_string(),
2317                },
2318            ],
2319            input,
2320        )?;
2321
2322        // filter "x > 5"
2323        let filter1 = Arc::new(BinaryExpr::new(
2324            Arc::new(Column::new("x", 0)),
2325            Operator::Gt,
2326            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2327        )) as Arc<dyn PhysicalExpr>;
2328
2329        // filter "b < 10" (using output index 1 which corresponds to 'b')
2330        let filter2 = Arc::new(BinaryExpr::new(
2331            Arc::new(Column::new("b", 1)),
2332            Operator::Lt,
2333            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
2334        )) as Arc<dyn PhysicalExpr>;
2335
2336        let description = projection.gather_filters_for_pushdown(
2337            FilterPushdownPhase::Post,
2338            vec![filter1, filter2],
2339            &ConfigOptions::default(),
2340        )?;
2341
2342        let pushed_filters = &description.parent_filters()[0];
2343        assert_eq!(pushed_filters.len(), 2);
2344        // "x" -> "a" (index 0)
2345        let expected_filter1 = "a@0 > 5";
2346        // "b" -> "b" (index 1)
2347        let expected_filter2 = "b@1 < 10";
2348
2349        assert_eq!(format!("{}", pushed_filters[0].predicate), expected_filter1);
2350        assert_eq!(format!("{}", pushed_filters[1].predicate), expected_filter2);
2351        // Verify the predicates were actually pushed down
2352        assert!(matches!(pushed_filters[0].discriminant, PushedDown::Yes));
2353        assert!(matches!(pushed_filters[1].discriminant, PushedDown::Yes));
2354
2355        Ok(())
2356    }
2357
2358    #[test]
2359    fn test_filter_pushdown_with_complex_expression() -> Result<()> {
2360        let input_schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2361        let input = Arc::new(StatisticsExec::new(
2362            Statistics {
2363                column_statistics: vec![Default::default(); input_schema.fields().len()],
2364                ..Default::default()
2365            },
2366            input_schema.clone(),
2367        ));
2368
2369        // project "a + 1" as "z"
2370        let projection = ProjectionExec::try_new(
2371            vec![ProjectionExpr {
2372                expr: Arc::new(BinaryExpr::new(
2373                    Arc::new(Column::new("a", 0)),
2374                    Operator::Plus,
2375                    Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
2376                )),
2377                alias: "z".to_string(),
2378            }],
2379            input,
2380        )?;
2381
2382        // filter "z > 10"
2383        let filter = Arc::new(BinaryExpr::new(
2384            Arc::new(Column::new("z", 0)),
2385            Operator::Gt,
2386            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
2387        )) as Arc<dyn PhysicalExpr>;
2388
2389        let description = projection.gather_filters_for_pushdown(
2390            FilterPushdownPhase::Post,
2391            vec![filter],
2392            &ConfigOptions::default(),
2393        )?;
2394
2395        // expand to `a + 1 > 10`
2396        let pushed_filters = &description.parent_filters()[0];
2397        assert!(matches!(pushed_filters[0].discriminant, PushedDown::Yes));
2398        assert_eq!(format!("{}", pushed_filters[0].predicate), "a@0 + 1 > 10");
2399
2400        Ok(())
2401    }
2402
2403    #[test]
2404    fn test_filter_pushdown_with_unknown_column() -> Result<()> {
2405        let input_schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2406        let input = Arc::new(StatisticsExec::new(
2407            Statistics {
2408                column_statistics: vec![Default::default(); input_schema.fields().len()],
2409                ..Default::default()
2410            },
2411            input_schema.clone(),
2412        ));
2413
2414        // project "a" as "a"
2415        let projection = ProjectionExec::try_new(
2416            vec![ProjectionExpr {
2417                expr: Arc::new(Column::new("a", 0)),
2418                alias: "a".to_string(),
2419            }],
2420            input,
2421        )?;
2422
2423        // filter "unknown_col > 5" - using a column name that doesn't exist in projection output
2424        // Column constructor: name, index. Index 1 doesn't exist.
2425        let filter = Arc::new(BinaryExpr::new(
2426            Arc::new(Column::new("unknown_col", 1)),
2427            Operator::Gt,
2428            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
2429        )) as Arc<dyn PhysicalExpr>;
2430
2431        let description = projection.gather_filters_for_pushdown(
2432            FilterPushdownPhase::Post,
2433            vec![filter],
2434            &ConfigOptions::default(),
2435        )?;
2436
2437        let pushed_filters = &description.parent_filters()[0];
2438        assert!(matches!(pushed_filters[0].discriminant, PushedDown::No));
2439        // The column shouldn't be found in the alias map, so it remains unchanged with its index
2440        assert_eq!(
2441            format!("{}", pushed_filters[0].predicate),
2442            "unknown_col@1 > 5"
2443        );
2444
2445        Ok(())
2446    }
2447
2448    /// Basic test for `DynamicFilterPhysicalExpr` can correctly update its child expression
2449    /// i.e. starting with lit(true) and after update it becomes `a > 5`
2450    /// with projection [b - 1 as a], the pushed down filter should be `b - 1 > 5`
2451    #[test]
2452    fn test_basic_dyn_filter_projection_pushdown_update_child() -> Result<()> {
2453        let input_schema =
2454            Arc::new(Schema::new(vec![Field::new("b", DataType::Int32, false)]));
2455
2456        let input = Arc::new(StatisticsExec::new(
2457            Statistics {
2458                column_statistics: vec![Default::default(); input_schema.fields().len()],
2459                ..Default::default()
2460            },
2461            input_schema.as_ref().clone(),
2462        ));
2463
2464        // project "b" - 1 as "a"
2465        let projection = ProjectionExec::try_new(
2466            vec![ProjectionExpr {
2467                expr: binary(
2468                    Arc::new(Column::new("b", 0)),
2469                    Operator::Minus,
2470                    lit(1),
2471                    &input_schema,
2472                )
2473                .unwrap(),
2474                alias: "a".to_string(),
2475            }],
2476            input,
2477        )?;
2478
2479        // simulate projection's parent create a dynamic filter on "a"
2480        let projected_schema = projection.schema();
2481        let col_a = col("a", &projected_schema)?;
2482        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(
2483            vec![Arc::clone(&col_a)],
2484            lit(true),
2485        ));
2486        // Initial state should be lit(true)
2487        let current = dynamic_filter.current()?;
2488        assert_eq!(format!("{current}"), "true");
2489
2490        let dyn_phy_expr: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
2491
2492        let description = projection.gather_filters_for_pushdown(
2493            FilterPushdownPhase::Post,
2494            vec![dyn_phy_expr],
2495            &ConfigOptions::default(),
2496        )?;
2497
2498        let pushed_filters = &description.parent_filters()[0][0];
2499
2500        // Check currently pushed_filters is lit(true)
2501        assert_eq!(
2502            format!("{}", pushed_filters.predicate),
2503            "DynamicFilter [ empty ]"
2504        );
2505
2506        // Update to a > 5 (after projection, b is now called a)
2507        let new_expr =
2508            Arc::new(BinaryExpr::new(Arc::clone(&col_a), Operator::Gt, lit(5i32)));
2509        dynamic_filter.update(new_expr)?;
2510
2511        // Now it should be a > 5
2512        let current = dynamic_filter.current()?;
2513        assert_eq!(format!("{current}"), "a@0 > 5");
2514
2515        // Check currently pushed_filters is b - 1 > 5 (because b - 1 is projected as a)
2516        assert_eq!(
2517            format!("{}", pushed_filters.predicate),
2518            "DynamicFilter [ b@0 - 1 > 5 ]"
2519        );
2520
2521        Ok(())
2522    }
2523}