1use 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};
61pub use datafusion_physical_expr::projection::{
64 ProjectionExpr, ProjectionExprs, update_expr,
65};
66
67use futures::stream::{Stream, StreamExt};
68use log::trace;
69
70#[derive(Debug, Clone)]
75pub struct ProjectionExec {
76 projector: Projector,
79 input: Arc<dyn ExecutionPlan>,
81 metrics: ExecutionPlanMetricsSet,
83 cache: Arc<PlanProperties>,
85 overrides_metadata: bool,
88}
89
90impl ProjectionExec {
91 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 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 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 pub fn expr(&self) -> &[ProjectionExpr] {
206 self.projector.projection().as_ref()
207 }
208
209 pub fn projection_expr(&self) -> &ProjectionExprs {
211 self.projector.projection()
212 }
213
214 pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
216 &self.input
217 }
218
219 fn compute_properties(
221 input: &Arc<dyn ExecutionPlan>,
222 projection_mapping: &ProjectionMapping,
223 schema: SchemaRef,
224 ) -> Result<PlanProperties> {
225 let input_eq_properties = input.equivalence_properties();
227 let eq_properties = input_eq_properties.project(projection_mapping, schema);
228 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 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 fn overrides_metadata(&self) -> bool {
265 self.overrides_metadata
266 }
267
268 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 fn properties(&self) -> &Arc<PlanProperties> {
340 &self.cache
341 }
342
343 fn maintains_input_order(&self) -> Vec<bool> {
344 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 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 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 if let Some(reassigned) = remapper.try_remap(&filter)? {
497 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 for sort_expr in order {
530 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 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 if let Some(child_col) = proj_expr.expr.downcast_ref::<Column>() {
547 Ok(Transformed::yes(Arc::new(child_col.clone()) as _))
549 } else {
550 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 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 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 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 let _timer = self.baseline_metrics.elapsed_compute().timer();
682 self.projector.project_batch(batch)
683 }
684}
685
686struct 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 self.input.size_hint()
711 }
712}
713
714impl RecordBatchStream for ProjectionStream {
715 fn schema(&self) -> SchemaRef {
717 Arc::clone(self.projector.output_schema())
718 }
719}
720
721pub trait EmbeddedProjection: ExecutionPlan + Sized {
731 fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self>;
732}
733
734pub fn try_embed_projection<Exec: EmbeddedProjection + 'static>(
737 projection: &ProjectionExec,
738 execution_plan: &Exec,
739) -> Result<Option<Arc<dyn ExecutionPlan>>> {
740 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 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 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 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 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 Ok(Some(new_execution_plan))
793 } else if columns_reduced {
794 Ok(Some(new_projection))
797 } else {
798 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
854pub 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 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 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 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 JoinSide::None => return Ok(None),
939 }
940 }
941
942 if left_proj.is_empty() || right_proj.is_empty() {
944 return Ok(None);
945 }
946
947 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
975pub 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 is_projection_removable(projection) {
986 return Ok(Transformed::yes(Arc::clone(projection.input())));
987 }
988 if projection.overrides_metadata() {
991 return Ok(Transformed::no(plan));
992 }
993 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
1003fn 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
1019pub 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
1031pub 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
1049pub 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
1063pub fn all_columns(exprs: &[ProjectionExpr]) -> bool {
1065 exprs.iter().all(|proj_expr| proj_expr.expr.is::<Column>())
1066}
1067
1068pub 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
1086pub 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
1104pub 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
1120pub 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 (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
1160fn 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
1188pub 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_as_columns.len() < join_schema.fields().len()
1201 && (far_right_left_col_ind + 1 == far_left_right_col_ind)
1203 && far_right_left_col_ind >= 0
1205 && far_left_right_col_ind < projection_as_columns.len() as i32
1206}
1207
1208pub 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
1241pub 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
1260pub 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 (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
1306fn 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 column_ref_map.clear();
1328 for proj_expr in ¤t_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 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 ¤t_exprs {
1355 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 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
1385fn collect_column_indices(exprs: &[ProjectionExpr]) -> Vec<usize> {
1387 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 if seen.insert(col.index()) {
1399 indices.push(col.index());
1400 }
1401 } else {
1402 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
1421fn 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
1446fn 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 Arc::clone(*on)
1463 .transform(|expr| {
1464 if let Some(column) = expr.downcast_ref::<Column>() {
1465 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 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 #[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 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 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 (expr, "c".to_string()),
2006 ],
2007 exec,
2008 )
2009 .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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let expected_filter1 = "a@0 > 5";
2281 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 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 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 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 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 let expected_filter1 = "a@0 > 5";
2346 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 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 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 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 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 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 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 assert_eq!(
2441 format!("{}", pushed_filters[0].predicate),
2442 "unknown_col@1 > 5"
2443 );
2444
2445 Ok(())
2446 }
2447
2448 #[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 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 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 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 assert_eq!(
2502 format!("{}", pushed_filters.predicate),
2503 "DynamicFilter [ empty ]"
2504 );
2505
2506 let new_expr =
2508 Arc::new(BinaryExpr::new(Arc::clone(&col_a), Operator::Gt, lit(5i32)));
2509 dynamic_filter.update(new_expr)?;
2510
2511 let current = dynamic_filter.current()?;
2513 assert_eq!(format!("{current}"), "a@0 > 5");
2514
2515 assert_eq!(
2517 format!("{}", pushed_filters.predicate),
2518 "DynamicFilter [ b@0 - 1 > 5 ]"
2519 );
2520
2521 Ok(())
2522 }
2523}