Skip to main content

datafusion_optimizer/optimize_projections/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`OptimizeProjections`] identifies and eliminates unused columns
6//!
7//! # Precedence over `PushDownLeafProjections`
8//!
9//! `OptimizeProjections` merges adjacent projections, including a recovery
10//! projection over an extraction projection that
11//! [`PushDownLeafProjections`] creates. To keep the two rules from undoing each
12//! other, `PushDownLeafProjections` only creates that pair when the extraction
13//! projection moves below the input. See the module documentation of
14//! [`extract_leaf_expressions`](crate::extract_leaf_expressions).
15//!
16//! [`PushDownLeafProjections`]: crate::extract_leaf_expressions::PushDownLeafProjections
17
18mod required_indices;
19
20use crate::optimizer::ApplyOrder;
21use crate::{OptimizerConfig, OptimizerRule};
22use datafusion_expr::logical_plan::MaterializedCtePlan;
23use std::sync::Arc;
24
25use datafusion_common::{
26    Column, DFSchema, DFSchemaRef, HashMap, JoinType, Result, assert_eq_or_internal_err,
27    get_required_group_by_exprs_indices, internal_datafusion_err, internal_err,
28};
29use datafusion_expr::expr::Alias;
30use datafusion_expr::utils::passthrough_field_index;
31use datafusion_expr::{
32    Aggregate, Distinct, EmptyRelation, Expr, Projection, TableScanBuilder, Unnest,
33    Window, logical_plan::LogicalPlan,
34};
35
36use crate::optimize_projections::required_indices::RequiredIndices;
37use crate::utils::NamePreserver;
38use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeContainer};
39
40/// Optimizer rule to prune unnecessary columns from intermediate schemas
41/// inside the [`LogicalPlan`]. This rule:
42/// - Removes unnecessary columns that do not appear at the output and/or are
43///   not used during any computation step.
44/// - Adds projections to decrease table column size before operators that
45///   benefit from a smaller memory footprint at its input.
46/// - Removes unnecessary [`LogicalPlan::Projection`]s from the [`LogicalPlan`].
47///
48/// `OptimizeProjections` is an optimizer rule that identifies and eliminates
49/// columns from a logical plan that are not used by downstream operations.
50/// This can improve query performance and reduce unnecessary data processing.
51///
52/// The rule analyzes the input logical plan, determines the necessary column
53/// indices, and then removes any unnecessary columns. It also removes any
54/// unnecessary projections from the plan tree.
55///
56/// ## Schema, Field Properties, and Metadata Handling
57///
58/// The `OptimizeProjections` rule preserves schema and field metadata in most optimization scenarios:
59///
60/// **Schema-level metadata preservation by plan type**:
61/// - **Window and Aggregate plans**: Schema metadata is preserved
62/// - **Projection plans**: Schema metadata is preserved per [`projection_schema`](datafusion_expr::logical_plan::projection_schema).
63/// - **Other logical plans**: Schema metadata is preserved unless [`LogicalPlan::recompute_schema`]
64///   is called on plan types that drop metadata
65///
66/// **Field-level properties and metadata**: Individual field properties are preserved when fields
67/// are retained in the optimized plan, determined by [`exprlist_to_fields`](datafusion_expr::utils::exprlist_to_fields)
68/// and [`ExprSchemable::to_field`](datafusion_expr::expr_schema::ExprSchemable::to_field).
69///
70/// **Field precedence**: When the same field appears multiple times, the optimizer
71/// maintains one occurrence and removes duplicates (refer to `RequiredIndices::compact()`),
72/// preserving the properties and metadata of that occurrence.
73#[derive(Default, Debug)]
74pub struct OptimizeProjections {}
75
76impl OptimizeProjections {
77    #[expect(missing_docs)]
78    pub fn new() -> Self {
79        Self {}
80    }
81}
82
83impl OptimizerRule for OptimizeProjections {
84    fn name(&self) -> &str {
85        "optimize_projections"
86    }
87
88    fn apply_order(&self) -> Option<ApplyOrder> {
89        None
90    }
91
92    fn rewrite(
93        &self,
94        plan: LogicalPlan,
95        config: &dyn OptimizerConfig,
96    ) -> Result<Transformed<LogicalPlan>> {
97        // All output fields are necessary:
98        let indices = RequiredIndices::new_for_all_exprs(&plan);
99        optimize_projections(plan, config, indices)
100    }
101}
102
103/// Removes unnecessary columns (e.g. columns that do not appear in the output
104/// schema and/or are not used during any computation step such as expression
105/// evaluation) from the logical plan and its inputs.
106///
107/// # Parameters
108///
109/// - `plan`: A reference to the input `LogicalPlan` to optimize.
110/// - `config`: A reference to the optimizer configuration.
111/// - `indices`: A slice of column indices that represent the necessary column
112///   indices for downstream (parent) plan nodes.
113///
114/// # Returns
115///
116/// A `Result` object with the following semantics:
117///
118/// - `Ok(Some(LogicalPlan))`: An optimized `LogicalPlan` without unnecessary
119///   columns.
120/// - `Ok(None)`: Signal that the given logical plan did not require any change.
121/// - `Err(error)`: An error occurred during the optimization process.
122#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
123fn optimize_projections(
124    plan: LogicalPlan,
125    config: &dyn OptimizerConfig,
126    indices: RequiredIndices,
127) -> Result<Transformed<LogicalPlan>> {
128    // Recursively rewrite any nodes that may be able to avoid computation given
129    // their parents' required indices.
130    match plan {
131        LogicalPlan::Projection(proj) => {
132            return merge_consecutive_projections(proj)?
133                .transform_data(|proj| {
134                    rewrite_projection_given_requirements(proj, config, &indices)
135                })?
136                .transform_data(|plan| optimize_subqueries(plan, config));
137        }
138        LogicalPlan::Aggregate(aggregate) => {
139            // Split parent requirements to GROUP BY and aggregate sections:
140            let n_group_exprs = aggregate.group_expr_len()?;
141            // Offset aggregate indices so that they point to valid indices at
142            // `aggregate.aggr_expr`:
143            let (group_by_reqs, aggregate_reqs) = indices.split_off(n_group_exprs);
144
145            // Get absolutely necessary GROUP BY fields.
146            //
147            // When the input has no functional dependencies, we can
148            // short-circuit this analysis.
149            let new_group_bys = if aggregate
150                .input
151                .schema()
152                .functional_dependencies()
153                .is_empty()
154            {
155                aggregate.group_expr
156            } else {
157                let group_by_input_indices = aggregate
158                    .group_expr
159                    .iter()
160                    .map(|group_by_expr| {
161                        passthrough_field_index(group_by_expr, aggregate.input.schema())
162                    })
163                    .collect::<Vec<_>>();
164
165                if let Some(simplest_groupby_indices) =
166                    get_required_group_by_exprs_indices(
167                        aggregate.input.schema(),
168                        &group_by_input_indices,
169                    )
170                {
171                    // Some of the fields in the GROUP BY may be required by
172                    // the parent even if these fields are unnecessary in
173                    // terms of functional dependency.
174                    group_by_reqs
175                        .append(&simplest_groupby_indices)
176                        .get_at_indices(&aggregate.group_expr)
177                } else {
178                    aggregate.group_expr
179                }
180            };
181
182            // Only use the absolutely necessary aggregate expressions required
183            // by the parent:
184            let new_aggr_expr = aggregate_reqs.get_at_indices(&aggregate.aggr_expr);
185
186            if new_group_bys.is_empty() && new_aggr_expr.is_empty() {
187                // Global aggregation with no aggregate functions always produces 1 row and no columns.
188                return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
189                    EmptyRelation {
190                        produce_one_row: true,
191                        schema: Arc::new(DFSchema::empty()),
192                    },
193                )));
194            }
195
196            let all_exprs_iter = new_group_bys.iter().chain(new_aggr_expr.iter());
197            let schema = aggregate.input.schema();
198            let necessary_indices =
199                RequiredIndices::new().with_exprs(schema, all_exprs_iter);
200            let necessary_exprs = necessary_indices.get_required_exprs(schema);
201
202            return optimize_projections(
203                Arc::unwrap_or_clone(aggregate.input),
204                config,
205                necessary_indices,
206            )?
207            .transform_data(|aggregate_input| {
208                // Simplify the input of the aggregation by adding a projection so
209                // that its input only contains absolutely necessary columns for
210                // the aggregate expressions. Note that necessary_indices refer to
211                // fields in `aggregate.input.schema()`.
212                add_projection_on_top_if_helpful(aggregate_input, necessary_exprs)
213            })?
214            .map_data(|aggregate_input| {
215                // Create a new aggregate plan with the updated input and only the
216                // absolutely necessary fields:
217                Aggregate::try_new(
218                    Arc::new(aggregate_input),
219                    new_group_bys,
220                    new_aggr_expr,
221                )
222                .map(LogicalPlan::Aggregate)
223            })?
224            .transform_data(|plan| optimize_subqueries(plan, config));
225        }
226        LogicalPlan::Window(window) => {
227            let input_schema = Arc::clone(window.input.schema());
228            // Split parent requirements to child and window expression sections:
229            let n_input_fields = input_schema.fields().len();
230            // Offset window expression indices so that they point to valid
231            // indices at `window.window_expr`:
232            let (child_reqs, window_reqs) = indices.split_off(n_input_fields);
233
234            // Only use window expressions that are absolutely necessary according
235            // to parent requirements:
236            let new_window_expr = window_reqs.get_at_indices(&window.window_expr);
237
238            // Get all the required column indices at the input, either by the
239            // parent or window expression requirements.
240            let required_indices = child_reqs.with_exprs(&input_schema, &new_window_expr);
241
242            return optimize_projections(
243                Arc::unwrap_or_clone(window.input),
244                config,
245                required_indices.clone(),
246            )?
247            .transform_data(|window_child| {
248                if new_window_expr.is_empty() {
249                    // When no window expression is necessary, use the input directly:
250                    Ok(Transformed::no(window_child))
251                } else {
252                    // Calculate required expressions at the input of the window.
253                    // Please note that we use `input_schema`, because `required_indices`
254                    // refers to that schema
255                    let required_exprs =
256                        required_indices.get_required_exprs(&input_schema);
257                    let window_child =
258                        add_projection_on_top_if_helpful(window_child, required_exprs)?
259                            .data;
260                    Window::try_new(new_window_expr, Arc::new(window_child))
261                        .map(LogicalPlan::Window)
262                        .map(Transformed::yes)
263                }
264            })?
265            .transform_data(|plan| optimize_subqueries(plan, config));
266        }
267        LogicalPlan::TableScan(table_scan) => {
268            // Get indices referred to in the original (schema with all fields)
269            // given projected indices.
270            let projection = match &table_scan.projection {
271                Some(projection) => indices.into_mapped_indices(|idx| projection[idx]),
272                None => indices.into_inner(),
273            };
274            let new_scan = TableScanBuilder::from(table_scan)
275                .with_projection(Some(projection))
276                .build()?;
277
278            return Transformed::yes(LogicalPlan::TableScan(new_scan))
279                .transform_data(|plan| optimize_subqueries(plan, config));
280        }
281        // Other node types are handled below
282        _ => {}
283    }
284
285    // For other plan node types, calculate indices for columns they use and
286    // try to rewrite their children
287    let mut child_required_indices: Vec<RequiredIndices> = match &plan {
288        LogicalPlan::Sort(_)
289        | LogicalPlan::Filter(_)
290        | LogicalPlan::Repartition(_)
291        | LogicalPlan::Union(_)
292        | LogicalPlan::SubqueryAlias(_)
293        | LogicalPlan::Distinct(Distinct::On(_)) => {
294            // Pass index requirements from the parent as well as column indices
295            // that appear in this plan's expressions to its child. All these
296            // operators benefit from "small" inputs, so the projection_beneficial
297            // flag is `true`.
298            plan.inputs()
299                .into_iter()
300                .map(|input| {
301                    indices
302                        .clone()
303                        .with_projection_beneficial()
304                        .with_plan_exprs(&plan, input.schema())
305                })
306                .collect::<Result<_>>()?
307        }
308        LogicalPlan::Limit(_) => {
309            // Pass index requirements from the parent as well as column indices
310            // that appear in this plan's expressions to its child. These operators
311            // do not benefit from "small" inputs, so the projection_beneficial
312            // flag is `false`.
313            plan.inputs()
314                .into_iter()
315                .map(|input| indices.clone().with_plan_exprs(&plan, input.schema()))
316                .collect::<Result<_>>()?
317        }
318        LogicalPlan::Copy(_)
319        | LogicalPlan::Ddl(_)
320        | LogicalPlan::Dml(_)
321        | LogicalPlan::Explain(_)
322        | LogicalPlan::Analyze(_)
323        | LogicalPlan::Subquery(_)
324        | LogicalPlan::Statement(_)
325        | LogicalPlan::Distinct(Distinct::All(_)) => {
326            // These plans require all their fields, and their children should
327            // be treated as final plans -- otherwise, we may have schema a
328            // mismatch.
329            // TODO: For some subquery variants (e.g. a subquery arising from an
330            //       EXISTS expression), we may not need to require all indices.
331            plan.inputs()
332                .into_iter()
333                .map(RequiredIndices::new_for_all_exprs)
334                .collect()
335        }
336        LogicalPlan::Extension(extension) => {
337            if let Some(necessary_children_indices) =
338                extension.node.necessary_children_exprs(indices.indices())
339            {
340                let children = extension.node.inputs();
341                assert_eq_or_internal_err!(
342                    children.len(),
343                    necessary_children_indices.len(),
344                    "Inconsistent length between children and necessary children indices. \
345                Make sure `.necessary_children_exprs` implementation of the \
346                `UserDefinedLogicalNode` is consistent with actual children length \
347                for the node."
348                );
349                children
350                    .into_iter()
351                    .zip(necessary_children_indices)
352                    .map(|(child, necessary_indices)| {
353                        RequiredIndices::new_from_indices(necessary_indices)
354                            .with_plan_exprs(&plan, child.schema())
355                    })
356                    .collect::<Result<Vec<_>>>()?
357            } else {
358                // Requirements from parent cannot be routed down to user defined logical plan safely
359                // Assume it requires all input exprs here
360                plan.inputs()
361                    .into_iter()
362                    .map(RequiredIndices::new_for_all_exprs)
363                    .collect()
364            }
365        }
366        LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
367            // The scans are leaves whose schema is the schema of the body, so
368            // the body keeps every column. The output is the output of the
369            // continuation, so the continuation needs what the parent needs.
370            vec![
371                RequiredIndices::new_for_all_exprs(&cte.cte),
372                RequiredIndices::new_from_indices(indices.into_inner()),
373            ]
374        }
375        LogicalPlan::EmptyRelation(_)
376        | LogicalPlan::Values(_)
377        | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_))
378        | LogicalPlan::Show(_) => {
379            // These operators have no inputs, so stop the optimization process.
380            return Ok(Transformed::no(plan));
381        }
382        LogicalPlan::RecursiveQuery(_) => {
383            // optimize the static and recursive terms: treat each recursive CTE term like a
384            // standalone subquery: optimize its internals, but do not push parent required indices
385            // through the RecursiveQuery boundary, as this can otherwise lead to bugs
386            // (see: https://github.com/apache/datafusion/issues/22249)
387            return plan.map_children(|c| {
388                let indices = RequiredIndices::new_for_all_exprs(&c);
389                optimize_projections(c, config, indices)
390            });
391        }
392        LogicalPlan::Join(join) => {
393            let left_len = join.left.schema().fields().len();
394            let right_len = join.right.schema().fields().len();
395            let (left_req_indices, right_req_indices) =
396                split_join_requirements(left_len, right_len, indices, &join.join_type);
397            let mut left_indices =
398                left_req_indices.with_plan_exprs(&plan, join.left.schema())?;
399            let mut right_indices =
400                right_req_indices.with_plan_exprs(&plan, join.right.schema())?;
401            // Ensure an empty mark join still has a column to qualify mark
402            match join.join_type {
403                JoinType::LeftMark if right_indices.indices().is_empty() => {
404                    right_indices = right_indices.append(&[0]);
405                }
406                JoinType::RightMark if left_indices.indices().is_empty() => {
407                    left_indices = left_indices.append(&[0]);
408                }
409                _ => {}
410            }
411            // Joins benefit from "small" input tables (lower memory usage).
412            // Therefore, each child benefits from projection:
413            vec![
414                left_indices.with_projection_beneficial(),
415                right_indices.with_projection_beneficial(),
416            ]
417        }
418        LogicalPlan::AsOfJoin(join) => {
419            let left_len = join.left.schema().fields().len();
420            let mut left_required = Vec::new();
421            let mut right_required = Vec::new();
422            for index in indices.indices() {
423                if *index < left_len {
424                    left_required.push(*index);
425                } else {
426                    right_required.push(*index - left_len);
427                }
428            }
429            let left_indices = RequiredIndices::new_from_indices(left_required)
430                .with_plan_exprs(&plan, join.left.schema())?;
431            let right_indices = RequiredIndices::new_from_indices(right_required)
432                .with_plan_exprs(&plan, join.right.schema())?;
433            vec![
434                left_indices.with_projection_beneficial(),
435                right_indices.with_projection_beneficial(),
436            ]
437        }
438        // these nodes are explicitly rewritten in the match statement above
439        LogicalPlan::Projection(_)
440        | LogicalPlan::Aggregate(_)
441        | LogicalPlan::Window(_)
442        | LogicalPlan::TableScan(_) => {
443            return internal_err!(
444                "OptimizeProjection: should have handled in the match statement above"
445            );
446        }
447        LogicalPlan::Unnest(Unnest {
448            input,
449            dependency_indices,
450            ..
451        }) => {
452            // at least provide the indices for the exec-columns as a starting point
453            let required_indices =
454                RequiredIndices::new().with_plan_exprs(&plan, input.schema())?;
455
456            // Add additional required indices from the parent
457            let mut additional_necessary_child_indices =
458                Vec::with_capacity(indices.indices().len());
459            indices.indices().iter().for_each(|idx| {
460                if let Some(index) = dependency_indices.get(*idx) {
461                    additional_necessary_child_indices.push(*index);
462                }
463            });
464            vec![required_indices.append(&additional_necessary_child_indices)]
465        }
466    };
467
468    // Required indices are currently ordered (child0, child1, ...)
469    // but the loop pops off the last element, so we need to reverse the order
470    child_required_indices.reverse();
471    assert_eq_or_internal_err!(
472        child_required_indices.len(),
473        plan.inputs().len(),
474        "OptimizeProjection: child_required_indices length mismatch with plan inputs"
475    );
476
477    // Rewrite children of the plan
478    let transformed_plan = plan.map_children(|child| {
479        let required_indices = child_required_indices.pop().ok_or_else(|| {
480            internal_datafusion_err!(
481                "Unexpected number of required_indices in OptimizeProjections rule"
482            )
483        })?;
484
485        let projection_beneficial = required_indices.projection_beneficial();
486        let project_exprs = required_indices.get_required_exprs(child.schema());
487
488        optimize_projections(child, config, required_indices)?.transform_data(
489            |new_input| {
490                if projection_beneficial {
491                    add_projection_on_top_if_helpful(new_input, project_exprs)
492                } else {
493                    Ok(Transformed::no(new_input))
494                }
495            },
496        )
497    })?;
498
499    let transformed_plan =
500        transformed_plan.transform_data(|plan| optimize_subqueries(plan, config))?;
501
502    // If any of the children are transformed, we need to potentially update the plan's schema
503    if transformed_plan.transformed {
504        transformed_plan.map_data(|plan| plan.recompute_schema())
505    } else {
506        Ok(transformed_plan)
507    }
508}
509
510/// Optimizes uncorrelated subquery plans embedded in expressions of the given
511/// plan node (e.g., `Expr::ScalarSubquery`). `map_children` only visits direct
512/// plan inputs, so subqueries must be handled separately.
513fn optimize_subqueries(
514    plan: LogicalPlan,
515    config: &dyn OptimizerConfig,
516) -> Result<Transformed<LogicalPlan>> {
517    plan.map_uncorrelated_subqueries(|subquery_plan| {
518        let indices = RequiredIndices::new_for_all_exprs(&subquery_plan);
519        optimize_projections(subquery_plan, config, indices)
520    })
521}
522
523/// Given a projection `proj`, this function attempts to merge it with a previous
524/// projection if it exists and if merging is beneficial. Merging is considered
525/// beneficial when expressions in the current projection are non-trivial and
526/// appear more than once in its input fields. This can act as a caching mechanism
527/// for non-trivial computations.
528///
529/// ## Metadata Handling During Projection Merging
530///
531/// **Alias metadata preservation**: When merging projections, alias metadata from both
532/// the current and previous projections is carefully preserved. The presence of metadata
533/// precludes alias trimming.
534///
535/// **Schema, Fields, and metadata**: If a projection is rewritten, the schema and metadata
536/// are preserved. Individual field properties and metadata flows through expression rewriting
537/// and are preserved when fields are referenced in the merged projection.
538/// Refer to [`projection_schema`](datafusion_expr::logical_plan::projection_schema)
539/// for more details.
540///
541/// # Parameters
542///
543/// * `proj` - A reference to the `Projection` to be merged.
544///
545/// # Returns
546///
547/// A `Result` object with the following semantics:
548///
549/// - `Ok(Some(Projection))`: Merge was beneficial and successful. Contains the
550///   merged projection.
551/// - `Ok(None)`: Signals that merge is not beneficial (and has not taken place).
552/// - `Err(error)`: An error occurred during the function call.
553fn merge_consecutive_projections(proj: Projection) -> Result<Transformed<Projection>> {
554    // Collapse the whole chain in one pass; otherwise an N-deep chain needs
555    // N outer optimizer passes to fully fold.
556    let mut current = proj;
557    let mut transformed_any = false;
558    loop {
559        let Transformed {
560            data, transformed, ..
561        } = merge_consecutive_projections_one_level(current)?;
562        current = data;
563        if !transformed {
564            break;
565        }
566        transformed_any = true;
567    }
568    Ok(if transformed_any {
569        Transformed::yes(current)
570    } else {
571        Transformed::no(current)
572    })
573}
574
575fn merge_consecutive_projections_one_level(
576    proj: Projection,
577) -> Result<Transformed<Projection>> {
578    let Projection {
579        expr,
580        input,
581        schema,
582        ..
583    } = proj;
584    let LogicalPlan::Projection(prev_projection) = input.as_ref() else {
585        return Projection::try_new_with_schema(expr, input, schema).map(Transformed::no);
586    };
587
588    // Count usages (referrals) of each projection expression in its input fields:
589    let mut column_referral_map = HashMap::<&Column, usize>::new();
590    for expr in &expr {
591        expr.add_column_ref_counts(&mut column_referral_map);
592    }
593
594    // If an expression is non-trivial (KeepInPlace) and appears more than once, do not merge
595    // them as consecutive projections will benefit from a compute-once approach.
596    // For details, see: https://github.com/apache/datafusion/issues/8296
597    if column_referral_map.into_iter().any(|(col, usage)| {
598        usage > 1
599            && !prev_projection.expr[prev_projection.schema.index_of_column(col).unwrap()]
600                .placement()
601                .should_push_to_leaves()
602    }) {
603        // no change
604        return Projection::try_new_with_schema(expr, input, schema).map(Transformed::no);
605    }
606
607    let LogicalPlan::Projection(prev_projection) = Arc::unwrap_or_clone(input) else {
608        // We know it is a `LogicalPlan::Projection` from check above
609        unreachable!();
610    };
611
612    // Try to rewrite the expressions in the current projection using the
613    // previous projection as input:
614    let name_preserver = NamePreserver::new_for_projection();
615    let mut original_names = Vec::with_capacity(expr.len());
616    let new_exprs = expr.map_elements(|expr| {
617        original_names.push(name_preserver.save(&expr));
618
619        // do not rewrite top level Aliases (rewriter will remove all aliases within exprs)
620        match expr {
621            Expr::Alias(Alias {
622                expr,
623                relation,
624                name,
625                metadata,
626            }) => rewrite_expr(*expr, &prev_projection).map(|result| {
627                result.update_data(|expr| {
628                    // After substitution, the inner expression may now have the
629                    // same schema_name as the alias (e.g. when an extraction
630                    // alias like `__extracted_1 AS f(x)` is resolved back to
631                    // `f(x)`). Wrapping in a redundant self-alias causes a
632                    // cosmetic `f(x) AS f(x)` due to Display vs schema_name
633                    // formatting differences. Drop the alias when it matches.
634                    if metadata.is_none() && expr.schema_name().to_string() == name {
635                        expr
636                    } else {
637                        Expr::Alias(Alias {
638                            expr: Box::new(expr),
639                            relation,
640                            name,
641                            metadata,
642                        })
643                    }
644                })
645            }),
646            e => rewrite_expr(e, &prev_projection),
647        }
648    })?;
649
650    // if the expressions could be rewritten, create a new projection with the
651    // new expressions
652    if new_exprs.transformed {
653        // Add any needed aliases back to the expressions
654        let new_exprs = new_exprs
655            .data
656            .into_iter()
657            .zip(original_names)
658            .map(|(expr, original_name)| original_name.restore(expr))
659            .collect::<Vec<_>>();
660        Projection::try_new(new_exprs, prev_projection.input).map(Transformed::yes)
661    } else {
662        // not rewritten, so put the projection back together
663        let input = Arc::new(LogicalPlan::Projection(prev_projection));
664        Projection::try_new_with_schema(new_exprs.data, input, schema)
665            .map(Transformed::no)
666    }
667}
668
669/// Rewrites a projection expression using the projection before it (i.e. its input)
670/// This is a subroutine to the `merge_consecutive_projections` function.
671///
672/// # Parameters
673///
674/// * `expr` - A reference to the expression to rewrite.
675/// * `input` - A reference to the input of the projection expression (itself
676///   a projection).
677///
678/// # Returns
679///
680/// A `Result` object with the following semantics:
681///
682/// - `Ok(Some(Expr))`: Rewrite was successful. Contains the rewritten result.
683/// - `Ok(None)`: Signals that `expr` can not be rewritten.
684/// - `Err(error)`: An error occurred during the function call.
685///
686/// # Notes
687/// This rewrite also removes any unnecessary layers of aliasing. "Unnecessary" is
688/// defined as not contributing new information, such as metadata.
689///
690/// Without trimming, we can end up with unnecessary indirections inside expressions
691/// during projection merges.
692///
693/// Consider:
694///
695/// ```text
696/// Projection(a1 + b1 as sum1)
697/// --Projection(a as a1, b as b1)
698/// ----Source(a, b)
699/// ```
700///
701/// After merge, we want to produce:
702///
703/// ```text
704/// Projection(a + b as sum1)
705/// --Source(a, b)
706/// ```
707///
708/// Without trimming, we would end up with:
709///
710/// ```text
711/// Projection((a as a1 + b as b1) as sum1)
712/// --Source(a, b)
713/// ```
714fn rewrite_expr(expr: Expr, input: &Projection) -> Result<Transformed<Expr>> {
715    expr.transform_up(|expr| {
716        match expr {
717            //  remove any intermediate aliases if they do not carry metadata
718            Expr::Alias(alias) => {
719                match alias
720                    .metadata
721                    .as_ref()
722                    .map(|h| h.is_empty())
723                    .unwrap_or(true)
724                {
725                    true => Ok(Transformed::yes(*alias.expr)),
726                    false => Ok(Transformed::no(Expr::Alias(alias))),
727                }
728            }
729            Expr::Column(col) => {
730                // Find index of column:
731                let idx = input.schema.index_of_column(&col)?;
732                // get the corresponding unaliased input expression
733                //
734                // For example:
735                // * the input projection is [`a + b` as c, `d + e` as f]
736                // * the current column is an expression "f"
737                //
738                // return the expression `d + e` (not `d + e` as f)
739                let input_expr = input.expr[idx].clone().unalias_nested().data;
740                Ok(Transformed::yes(input_expr))
741            }
742            // Unsupported type for consecutive projection merge analysis.
743            _ => Ok(Transformed::no(expr)),
744        }
745    })
746}
747
748/// Splits requirement indices for a join into left and right children based on
749/// the join type.
750///
751/// This function takes the length of the left child, a slice of requirement
752/// indices, and the type of join (e.g. `INNER`, `LEFT`, `RIGHT`) as arguments.
753/// Depending on the join type, it divides the requirement indices into those
754/// that apply to the left child and those that apply to the right child.
755///
756/// - For `INNER`, `LEFT`, `RIGHT`, `FULL`, `LEFTMARK`, and `RIGHTMARK` joins,
757///   the requirements are split between left and right children. The right
758///   child indices are adjusted to point to valid positions within the right
759///   child by subtracting the length of the left child.
760///
761/// - For `LEFT ANTI`, `LEFT SEMI`, `RIGHT SEMI` and `RIGHT ANTI` joins, all
762///   requirements are re-routed to either the left child or the right child
763///   directly, depending on the join type.
764///
765/// # Parameters
766///
767/// * `left_len` - The length of the left child.
768/// * `right_len` - The length of the right child.
769/// * `indices` - A slice of requirement indices.
770/// * `join_type` - The type of join (e.g. `INNER`, `LEFT`, `RIGHT`).
771///
772/// # Returns
773///
774/// A tuple containing two vectors of `usize` indices: The first vector represents
775/// the requirements for the left child, and the second vector represents the
776/// requirements for the right child. The indices are appropriately split and
777/// adjusted based on the join type.
778fn split_join_requirements(
779    left_len: usize,
780    right_len: usize,
781    indices: RequiredIndices,
782    join_type: &JoinType,
783) -> (RequiredIndices, RequiredIndices) {
784    match join_type {
785        // In these cases requirements are split between left/right children:
786        JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
787            // Decrease right side indices by `left_len` so that they point to valid
788            // positions within the right child:
789            indices.split_off(left_len)
790        }
791        JoinType::LeftMark => {
792            // LeftMark output: [left_cols(0..left_len), mark]
793            // The mark column is synthetic (produced by the join itself),
794            // so discard it and route only to the left child.
795            let (left_indices, _mark) = indices.split_off(left_len);
796            (left_indices, RequiredIndices::new())
797        }
798        JoinType::RightMark => {
799            // Same as LeftMark, but for the right child.
800            let (right_indices, _mark) = indices.split_off(right_len);
801            (RequiredIndices::new(), right_indices)
802        }
803        // All requirements can be re-routed to left child directly.
804        JoinType::LeftAnti | JoinType::LeftSemi => (indices, RequiredIndices::new()),
805        // All requirements can be re-routed to right side directly.
806        // No need to change index, join schema is right child schema.
807        JoinType::RightSemi | JoinType::RightAnti => (RequiredIndices::new(), indices),
808    }
809}
810
811/// Adds a projection on top of a logical plan if doing so reduces the number
812/// of columns for the parent operator.
813///
814/// This function takes a `LogicalPlan` and a list of projection expressions.
815/// If the projection is beneficial (it reduces the number of columns in the
816/// plan) a new `LogicalPlan` with the projection is created and returned, along
817/// with a `true` flag. If the projection doesn't reduce the number of columns,
818/// the original plan is returned with a `false` flag.
819///
820/// # Parameters
821///
822/// * `plan` - The input `LogicalPlan` to potentially add a projection to.
823/// * `project_exprs` - A list of expressions for the projection.
824///
825/// # Returns
826///
827/// A `Transformed` indicating if a projection was added
828fn add_projection_on_top_if_helpful(
829    plan: LogicalPlan,
830    project_exprs: Vec<Expr>,
831) -> Result<Transformed<LogicalPlan>> {
832    // Make sure projection decreases the number of columns, otherwise it is unnecessary.
833    if project_exprs.len() >= plan.schema().fields().len() {
834        Ok(Transformed::no(plan))
835    } else {
836        Projection::try_new(project_exprs, Arc::new(plan))
837            .map(LogicalPlan::Projection)
838            .map(Transformed::yes)
839    }
840}
841
842/// Rewrite the given projection according to the fields required by its
843/// ancestors.
844///
845/// # Parameters
846///
847/// * `proj` - A reference to the original projection to rewrite.
848/// * `config` - A reference to the optimizer configuration.
849/// * `indices` - A slice of indices representing the columns required by the
850///   ancestors of the given projection.
851///
852/// # Returns
853///
854/// A `Result` object with the following semantics:
855///
856/// - `Ok(Some(LogicalPlan))`: Contains the rewritten projection
857/// - `Ok(None)`: No rewrite necessary.
858/// - `Err(error)`: An error occurred during the function call.
859fn rewrite_projection_given_requirements(
860    proj: Projection,
861    config: &dyn OptimizerConfig,
862    indices: &RequiredIndices,
863) -> Result<Transformed<LogicalPlan>> {
864    let Projection {
865        expr,
866        input,
867        schema,
868        ..
869    } = proj;
870
871    let exprs_used = indices.get_at_indices(&expr);
872
873    let required_indices =
874        RequiredIndices::new().with_exprs(input.schema(), exprs_used.iter());
875    let old_input_schema = Arc::clone(input.schema());
876    let read_indices = required_indices.indices().to_vec();
877
878    // rewrite the children projection, and if they are changed rewrite the
879    // projection down
880    optimize_projections(Arc::unwrap_or_clone(input), config, required_indices)?
881        .transform_data(|input| {
882            if is_projection_unnecessary(&input, &exprs_used)? {
883                Ok(Transformed::yes(input))
884            } else if exprs_used.iter().any(contains_subquery)
885                || !read_fields_unchanged(
886                    &old_input_schema,
887                    input.schema(),
888                    &read_indices,
889                )
890            {
891                // A subquery is optimized on its own, and rewriting the input
892                // can change the fields this projection reads, so the stored
893                // schema may be stale. Recompute it rather than reuse it.
894                Projection::try_new(exprs_used, Arc::new(input))
895                    .map(LogicalPlan::Projection)
896                    .map(Transformed::yes)
897            } else {
898                // The retained expressions are a subset of the original ones and
899                // read unchanged input fields, so their output fields are
900                // unchanged too. Select them from the existing schema instead of
901                // recomputing each one via `Expr::to_field` (see
902                // `projection_schema`), which costs O(exprs * schema_width).
903                // `merge_consecutive_projections` reuses the schema the same way.
904                let projected_schema =
905                    project_schema_by_indices(&schema, indices.indices())?;
906                Projection::try_new_with_schema(
907                    exprs_used,
908                    Arc::new(input),
909                    projected_schema,
910                )
911                .map(LogicalPlan::Projection)
912                .map(Transformed::yes)
913            }
914        })
915}
916
917/// Returns true if the input fields at `read_indices` of `old` are unchanged in
918/// `new`, the input after it was rewritten for those indices.
919///
920/// The rewritten input either keeps every field of `old` or only the fields at
921/// `read_indices`, in order. Any other shape is treated as changed.
922fn read_fields_unchanged(old: &DFSchema, new: &DFSchema, read_indices: &[usize]) -> bool {
923    if new.fields().len() == old.fields().len() {
924        read_indices.iter().all(|&i| old.field(i) == new.field(i))
925    } else if new.fields().len() == read_indices.len() {
926        read_indices
927            .iter()
928            .enumerate()
929            .all(|(j, &i)| old.field(i) == new.field(j))
930    } else {
931        false
932    }
933}
934
935/// Returns true if `expr` contains a subquery expression.
936fn contains_subquery(expr: &Expr) -> bool {
937    expr.exists(|e| {
938        Ok(matches!(
939            e,
940            Expr::Exists(_)
941                | Expr::InSubquery(_)
942                | Expr::SetComparison(_)
943                | Expr::ScalarSubquery(_)
944        ))
945    })
946    .expect("exists closure is infallible")
947}
948
949/// Builds the output schema of a projection that keeps only the fields at
950/// `indices` (a sorted, deduplicated subset produced by [`RequiredIndices`]) of
951/// `schema`, reusing the already-computed fields instead of recomputing each
952/// field's type/nullability from the expressions.
953///
954/// Pruning unreferenced sibling columns cannot change the retained fields, so
955/// as long as `schema` is current for the projection's expressions and input,
956/// the sliced fields are identical to the ones [`projection_schema`] would
957/// recompute, at O(k) instead of O(exprs * schema_width). Functional
958/// dependencies can be weaker than recomputed ones, never stronger.
959///
960/// [`projection_schema`]: datafusion_expr::logical_plan::projection_schema
961fn project_schema_by_indices(
962    schema: &DFSchemaRef,
963    indices: &[usize],
964) -> Result<DFSchemaRef> {
965    // Nothing pruned: the output schema is unchanged, reuse it as-is.
966    if indices.len() == schema.fields().len() {
967        return Ok(Arc::clone(schema));
968    }
969
970    let qualified_fields = indices
971        .iter()
972        .map(|&i| {
973            let (qualifier, field) = schema.qualified_field(i);
974            (qualifier.cloned(), Arc::clone(field))
975        })
976        .collect::<Vec<_>>();
977
978    let func_deps = schema
979        .functional_dependencies()
980        .project_functional_dependencies(indices, indices.len());
981
982    let projected =
983        DFSchema::new_with_metadata(qualified_fields, schema.metadata().clone())?
984            .with_functional_dependencies(func_deps)?;
985
986    Ok(Arc::new(projected))
987}
988
989/// Projection is unnecessary, when
990/// - input schema of the projection, output schema of the projection are same, and
991/// - all projection expressions are either Column or Literal
992pub fn is_projection_unnecessary(
993    input: &LogicalPlan,
994    proj_exprs: &[Expr],
995) -> Result<bool> {
996    // First check if the number of expressions is equal to the number of fields in the input schema.
997    if proj_exprs.len() != input.schema().fields().len() {
998        return Ok(false);
999    }
1000    Ok(input.schema().iter().zip(proj_exprs.iter()).all(
1001        |((field_relation, field_name), expr)| {
1002            // Check if the expression is a column and if it matches the field name
1003            if let Expr::Column(col) = expr {
1004                col.relation.as_ref() == field_relation && col.name.eq(field_name.name())
1005            } else {
1006                false
1007            }
1008        },
1009    ))
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use std::cmp::Ordering;
1015    use std::collections::HashMap;
1016    use std::fmt::Formatter;
1017    use std::ops::Add;
1018    use std::sync::Arc;
1019    use std::vec;
1020
1021    use crate::optimize_projections::OptimizeProjections;
1022    use crate::optimizer::{ApplyOrder, Optimizer};
1023    use crate::test::{
1024        assert_fields_eq, scan_empty, test_table_scan, test_table_scan_fields,
1025        test_table_scan_with_name,
1026    };
1027    use crate::{OptimizerConfig, OptimizerContext, OptimizerRule};
1028    use arrow::datatypes::{DataType, Field, Schema};
1029    use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
1030    use datafusion_common::{
1031        Column, DFSchema, DFSchemaRef, JoinType, Result, ScalarValue, TableReference,
1032    };
1033    use datafusion_expr::ExprFunctionExt;
1034    use datafusion_expr::{
1035        BinaryExpr, Expr, Extension, Like, LogicalPlan, Operator, Projection,
1036        UserDefinedLogicalNodeCore, WindowFunctionDefinition, binary_expr,
1037        build_join_schema,
1038        builder::table_scan_with_filters,
1039        col,
1040        expr::{self, Alias, Cast},
1041        lit,
1042        logical_plan::{builder::LogicalPlanBuilder, table_scan},
1043        not, try_cast, when,
1044    };
1045    use insta::assert_snapshot;
1046
1047    use crate::assert_optimized_plan_eq_snapshot;
1048    use datafusion_functions_aggregate::count::count_udaf;
1049    use datafusion_functions_aggregate::expr_fn::{count, max, min};
1050    use datafusion_functions_aggregate::min_max::max_udaf;
1051
1052    macro_rules! assert_optimized_plan_equal {
1053        (
1054            $plan:expr,
1055            @ $expected:literal $(,)?
1056        ) => {{
1057            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
1058            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(OptimizeProjections::new())];
1059            assert_optimized_plan_eq_snapshot!(
1060                optimizer_ctx,
1061                rules,
1062                $plan,
1063                @ $expected,
1064            )
1065        }};
1066    }
1067
1068    #[derive(Debug, Hash, PartialEq, Eq)]
1069    struct NoOpUserDefined {
1070        exprs: Vec<Expr>,
1071        schema: DFSchemaRef,
1072        input: Arc<LogicalPlan>,
1073    }
1074
1075    impl NoOpUserDefined {
1076        fn new(schema: DFSchemaRef, input: Arc<LogicalPlan>) -> Self {
1077            Self {
1078                exprs: vec![],
1079                schema,
1080                input,
1081            }
1082        }
1083
1084        fn with_exprs(mut self, exprs: Vec<Expr>) -> Self {
1085            self.exprs = exprs;
1086            self
1087        }
1088    }
1089
1090    // Manual implementation needed because of `schema` field. Comparison excludes this field.
1091    impl PartialOrd for NoOpUserDefined {
1092        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1093            match self.exprs.partial_cmp(&other.exprs) {
1094                Some(Ordering::Equal) => self.input.partial_cmp(&other.input),
1095                cmp => cmp,
1096            }
1097            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
1098            .filter(|cmp| *cmp != Ordering::Equal || self == other)
1099        }
1100    }
1101
1102    impl UserDefinedLogicalNodeCore for NoOpUserDefined {
1103        fn name(&self) -> &str {
1104            "NoOpUserDefined"
1105        }
1106
1107        fn inputs(&self) -> Vec<&LogicalPlan> {
1108            vec![&self.input]
1109        }
1110
1111        fn schema(&self) -> &DFSchemaRef {
1112            &self.schema
1113        }
1114
1115        fn expressions(&self) -> Vec<Expr> {
1116            self.exprs.clone()
1117        }
1118
1119        fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
1120            write!(f, "NoOpUserDefined")
1121        }
1122
1123        fn with_exprs_and_inputs(
1124            &self,
1125            exprs: Vec<Expr>,
1126            mut inputs: Vec<LogicalPlan>,
1127        ) -> Result<Self> {
1128            Ok(Self {
1129                exprs,
1130                input: Arc::new(inputs.swap_remove(0)),
1131                schema: Arc::clone(&self.schema),
1132            })
1133        }
1134
1135        fn necessary_children_exprs(
1136            &self,
1137            output_columns: &[usize],
1138        ) -> Option<Vec<Vec<usize>>> {
1139            // Since schema is same. Output columns requires their corresponding version in the input columns.
1140            Some(vec![output_columns.to_vec()])
1141        }
1142
1143        fn supports_limit_pushdown(&self) -> bool {
1144            false // Disallow limit push-down by default
1145        }
1146    }
1147
1148    #[derive(Debug, Hash, PartialEq, Eq)]
1149    struct UserDefinedCrossJoin {
1150        exprs: Vec<Expr>,
1151        schema: DFSchemaRef,
1152        left_child: Arc<LogicalPlan>,
1153        right_child: Arc<LogicalPlan>,
1154    }
1155
1156    impl UserDefinedCrossJoin {
1157        fn new(left_child: Arc<LogicalPlan>, right_child: Arc<LogicalPlan>) -> Self {
1158            let left_schema = left_child.schema();
1159            let right_schema = right_child.schema();
1160            let schema = Arc::new(
1161                build_join_schema(left_schema, right_schema, &JoinType::Inner).unwrap(),
1162            );
1163            Self {
1164                exprs: vec![],
1165                schema,
1166                left_child,
1167                right_child,
1168            }
1169        }
1170    }
1171
1172    // Manual implementation needed because of `schema` field. Comparison excludes this field.
1173    impl PartialOrd for UserDefinedCrossJoin {
1174        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1175            match self.exprs.partial_cmp(&other.exprs) {
1176                Some(Ordering::Equal) => {
1177                    match self.left_child.partial_cmp(&other.left_child) {
1178                        Some(Ordering::Equal) => {
1179                            self.right_child.partial_cmp(&other.right_child)
1180                        }
1181                        cmp => cmp,
1182                    }
1183                }
1184                cmp => cmp,
1185            }
1186            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
1187            .filter(|cmp| *cmp != Ordering::Equal || self == other)
1188        }
1189    }
1190
1191    impl UserDefinedLogicalNodeCore for UserDefinedCrossJoin {
1192        fn name(&self) -> &str {
1193            "UserDefinedCrossJoin"
1194        }
1195
1196        fn inputs(&self) -> Vec<&LogicalPlan> {
1197            vec![&self.left_child, &self.right_child]
1198        }
1199
1200        fn schema(&self) -> &DFSchemaRef {
1201            &self.schema
1202        }
1203
1204        fn expressions(&self) -> Vec<Expr> {
1205            self.exprs.clone()
1206        }
1207
1208        fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
1209            write!(f, "UserDefinedCrossJoin")
1210        }
1211
1212        fn with_exprs_and_inputs(
1213            &self,
1214            exprs: Vec<Expr>,
1215            mut inputs: Vec<LogicalPlan>,
1216        ) -> Result<Self> {
1217            assert_eq!(inputs.len(), 2);
1218            Ok(Self {
1219                exprs,
1220                left_child: Arc::new(inputs.remove(0)),
1221                right_child: Arc::new(inputs.remove(0)),
1222                schema: Arc::clone(&self.schema),
1223            })
1224        }
1225
1226        fn necessary_children_exprs(
1227            &self,
1228            output_columns: &[usize],
1229        ) -> Option<Vec<Vec<usize>>> {
1230            let left_child_len = self.left_child.schema().fields().len();
1231            let mut left_reqs = vec![];
1232            let mut right_reqs = vec![];
1233            for &out_idx in output_columns {
1234                if out_idx < left_child_len {
1235                    left_reqs.push(out_idx);
1236                } else {
1237                    // Output indices further than the left_child_len
1238                    // comes from right children
1239                    right_reqs.push(out_idx - left_child_len)
1240                }
1241            }
1242            Some(vec![left_reqs, right_reqs])
1243        }
1244
1245        fn supports_limit_pushdown(&self) -> bool {
1246            false // Disallow limit push-down by default
1247        }
1248    }
1249
1250    /// A user-defined node that does NOT implement `necessary_children_exprs`,
1251    /// so the optimizer cannot determine which columns are required from its
1252    /// children and must assume all columns are needed.
1253    #[derive(Debug, Hash, PartialEq, Eq)]
1254    struct OpaqueRequirementsUserDefined {
1255        input: Arc<LogicalPlan>,
1256        schema: DFSchemaRef,
1257    }
1258
1259    // Manual implementation needed because of `schema` field. Comparison excludes this field.
1260    impl PartialOrd for OpaqueRequirementsUserDefined {
1261        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1262            self.input
1263                .partial_cmp(&other.input)
1264                .filter(|cmp| *cmp != Ordering::Equal || self == other)
1265        }
1266    }
1267
1268    impl UserDefinedLogicalNodeCore for OpaqueRequirementsUserDefined {
1269        fn name(&self) -> &str {
1270            "OpaqueRequirementsUserDefined"
1271        }
1272
1273        fn inputs(&self) -> Vec<&LogicalPlan> {
1274            vec![&self.input]
1275        }
1276
1277        fn schema(&self) -> &DFSchemaRef {
1278            &self.schema
1279        }
1280
1281        fn expressions(&self) -> Vec<Expr> {
1282            vec![]
1283        }
1284
1285        fn with_exprs_and_inputs(
1286            &self,
1287            _exprs: Vec<Expr>,
1288            mut inputs: Vec<LogicalPlan>,
1289        ) -> Result<Self> {
1290            Ok(Self {
1291                input: Arc::new(inputs.swap_remove(0)),
1292                schema: Arc::clone(&self.schema),
1293            })
1294        }
1295
1296        fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
1297            write!(f, "OpaqueRequirementsUserDefined")
1298        }
1299    }
1300
1301    /// `project_schema_by_indices` must produce exactly the schema that
1302    /// recomputing it from scratch (`projection_schema`) would, for every subset
1303    /// of a projection's expressions. This is the correctness invariant that lets
1304    /// `rewrite_projection_given_requirements` reuse the parent schema instead of
1305    /// re-deriving each field's type via `Expr::to_field`.
1306    #[test]
1307    fn project_schema_by_indices_matches_recompute() -> Result<()> {
1308        use super::project_schema_by_indices;
1309        use datafusion_expr::logical_plan::projection_schema;
1310
1311        let input = Arc::new(test_table_scan()?); // columns: a, b, c (UInt32, NOT NULL)
1312
1313        // A deliberately mixed expression list: plain column, computed binary
1314        // expr, alias, nullable literal, and a qualified column. Every input
1315        // column is NOT NULL, so the NULL literal is what makes nullability
1316        // actually vary across the schema.
1317        let exprs = vec![
1318            col("a"),
1319            binary_expr(col("b"), Operator::Plus, col("c")),
1320            col("c").alias("c_alias"),
1321            lit(ScalarValue::Int64(None)).alias("null_one"),
1322            Expr::Column(Column::new(Some(TableReference::bare("test")), "b")),
1323        ];
1324
1325        let full_schema =
1326            Arc::clone(&Projection::try_new(exprs.clone(), Arc::clone(&input))?.schema);
1327
1328        // Guard the premise above: if this ever stops holding, the subsets below
1329        // would no longer exercise nullability propagation at all.
1330        assert!(
1331            full_schema.field(3).is_nullable(),
1332            "the literal must be nullable for this test to cover nullability"
1333        );
1334        assert!(
1335            !full_schema.field(0).is_nullable(),
1336            "input columns are expected to be NOT NULL"
1337        );
1338
1339        // A sample of the sorted, deduplicated subsets RequiredIndices can
1340        // produce, including the "nothing pruned" identity case.
1341        let subsets: Vec<Vec<usize>> = vec![
1342            vec![0, 1, 2, 3, 4], // identity (SELECT * fast path)
1343            vec![0],
1344            vec![1], // computed expr only
1345            vec![2], // alias only
1346            vec![3], // literal only
1347            vec![0, 2],
1348            vec![1, 3],
1349            vec![0, 1, 4],
1350            vec![2, 3, 4],
1351        ];
1352
1353        for indices in subsets {
1354            let exprs_used: Vec<Expr> =
1355                indices.iter().map(|&i| exprs[i].clone()).collect();
1356
1357            let reused = project_schema_by_indices(&full_schema, &indices)?;
1358            let recomputed = projection_schema(input.as_ref(), &exprs_used)?;
1359
1360            // Output fields (name, data type, nullability, field metadata) must
1361            // match the from-scratch computation exactly.
1362            assert_eq!(
1363                reused.fields(),
1364                recomputed.fields(),
1365                "fields differ for indices {indices:?}"
1366            );
1367
1368            // Column qualifiers (table references) must be preserved too.
1369            let reused_quals: Vec<_> = reused.iter().map(|(q, _)| q.cloned()).collect();
1370            let recomputed_quals: Vec<_> =
1371                recomputed.iter().map(|(q, _)| q.cloned()).collect();
1372            assert_eq!(
1373                reused_quals, recomputed_quals,
1374                "qualifiers differ for indices {indices:?}"
1375            );
1376
1377            // `project_schema_by_indices` also carries over schema-level
1378            // metadata and projects functional dependencies through the kept
1379            // indices, so both must match the from-scratch computation as well.
1380            assert_eq!(
1381                reused.metadata(),
1382                recomputed.metadata(),
1383                "schema metadata differs for indices {indices:?}"
1384            );
1385            assert_eq!(
1386                reused.functional_dependencies(),
1387                recomputed.functional_dependencies(),
1388                "functional dependencies differ for indices {indices:?}"
1389            );
1390        }
1391
1392        // The identity subset must reuse the very same Arc, not rebuild it.
1393        let identity = project_schema_by_indices(&full_schema, &[0, 1, 2, 3, 4])?;
1394        assert!(
1395            Arc::ptr_eq(&identity, &full_schema),
1396            "identity projection should reuse the existing schema Arc"
1397        );
1398
1399        Ok(())
1400    }
1401
1402    #[test]
1403    fn merge_two_projection() -> Result<()> {
1404        let table_scan = test_table_scan()?;
1405        let plan = LogicalPlanBuilder::from(table_scan)
1406            .project(vec![col("a")])?
1407            .project(vec![binary_expr(lit(1), Operator::Plus, col("a"))])?
1408            .build()?;
1409
1410        assert_optimized_plan_equal!(
1411            plan,
1412            @r"
1413        Projection: Int32(1) + test.a
1414          TableScan: test projection=[a]
1415        "
1416        )
1417    }
1418
1419    #[test]
1420    fn merge_three_projection() -> Result<()> {
1421        let table_scan = test_table_scan()?;
1422        let plan = LogicalPlanBuilder::from(table_scan)
1423            .project(vec![col("a"), col("b")])?
1424            .project(vec![col("a")])?
1425            .project(vec![binary_expr(lit(1), Operator::Plus, col("a"))])?
1426            .build()?;
1427
1428        assert_optimized_plan_equal!(
1429            plan,
1430            @r"
1431        Projection: Int32(1) + test.a
1432          TableScan: test projection=[a]
1433        "
1434        )
1435    }
1436
1437    #[test]
1438    fn merge_structurally_equal_non_idempotent_projections() -> Result<()> {
1439        let schema = Schema::new(vec![Field::new("i", DataType::Int32, false)]);
1440        let projection = || col("i").add(lit(1)).alias("i");
1441        let plan = table_scan(TableReference::none(), &schema, None)?
1442            .project(vec![projection()])?
1443            .project(vec![projection()])?
1444            .build()?;
1445
1446        assert_optimized_plan_equal!(
1447            plan,
1448            @r"
1449        Projection: ?table?.i + Int32(1) + Int32(1) AS i
1450          TableScan: ?table? projection=[i]
1451        "
1452        )
1453    }
1454
1455    #[test]
1456    fn merge_deep_projection_chain_in_one_pass() -> Result<()> {
1457        let schema = Schema::new(vec![Field::new("i", DataType::Int32, false)]);
1458        let mut plan = table_scan(TableReference::none(), &schema, None)?
1459            .project(vec![col("i").add(lit(1)).alias("i")])?
1460            .build()?;
1461        for _ in 1..12 {
1462            plan = LogicalPlanBuilder::from(plan)
1463                .project(vec![col("i").add(lit(1)).alias("i")])?
1464                .build()?;
1465        }
1466
1467        let optimizer = Optimizer::with_rules(vec![Arc::new(OptimizeProjections::new())]);
1468        let optimized = optimizer.optimize(
1469            plan,
1470            &OptimizerContext::new().with_max_passes(1),
1471            observe,
1472        )?;
1473        let plan_string = format!("{optimized}");
1474        assert_eq!(12, plan_string.matches("Int32(1)").count());
1475        assert_eq!(1, plan_string.matches("Projection:").count());
1476        Ok(())
1477    }
1478
1479    #[test]
1480    fn merge_columns_and_metadata_alias() -> Result<()> {
1481        let metadata =
1482            datafusion_common::metadata::FieldMetadata::from(HashMap::from([(
1483                "key".to_string(),
1484                "value".to_string(),
1485            )]));
1486        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1487            .project(vec![col("a")])?
1488            .project(vec![col("a").alias_with_metadata("a", Some(metadata))])?
1489            .build()?;
1490
1491        let optimized = optimize(plan)?;
1492        assert_eq!(
1493            "value",
1494            optimized.schema().field(0).metadata().get("key").unwrap()
1495        );
1496        assert_eq!(1, format!("{optimized}").matches("Projection:").count());
1497        Ok(())
1498    }
1499
1500    #[test]
1501    fn merge_alias() -> Result<()> {
1502        let table_scan = test_table_scan()?;
1503        let plan = LogicalPlanBuilder::from(table_scan)
1504            .project(vec![col("a")])?
1505            .project(vec![col("a").alias("alias")])?
1506            .build()?;
1507
1508        assert_optimized_plan_equal!(
1509            plan,
1510            @r"
1511        Projection: test.a AS alias
1512          TableScan: test projection=[a]
1513        "
1514        )
1515    }
1516
1517    #[test]
1518    fn merge_nested_alias() -> Result<()> {
1519        let table_scan = test_table_scan()?;
1520        let plan = LogicalPlanBuilder::from(table_scan)
1521            .project(vec![col("a").alias("alias1").alias("alias2")])?
1522            .project(vec![col("alias2").alias("alias")])?
1523            .build()?;
1524
1525        assert_optimized_plan_equal!(
1526            plan,
1527            @r"
1528        Projection: test.a AS alias
1529          TableScan: test projection=[a]
1530        "
1531        )
1532    }
1533
1534    #[test]
1535    fn test_nested_count() -> Result<()> {
1536        let schema = Schema::new(vec![Field::new("foo", DataType::Int32, false)]);
1537
1538        let groups: Vec<Expr> = vec![];
1539
1540        let plan = table_scan(TableReference::none(), &schema, None)
1541            .unwrap()
1542            .aggregate(groups.clone(), vec![count(lit(1))])
1543            .unwrap()
1544            .aggregate(groups, vec![count(lit(1))])
1545            .unwrap()
1546            .build()
1547            .unwrap();
1548
1549        assert_optimized_plan_equal!(
1550            plan,
1551            @r"
1552        Aggregate: groupBy=[[]], aggr=[[count(Int32(1))]]
1553          EmptyRelation: rows=1
1554        "
1555        )
1556    }
1557
1558    #[test]
1559    fn test_neg_push_down() -> Result<()> {
1560        let table_scan = test_table_scan()?;
1561        let plan = LogicalPlanBuilder::from(table_scan)
1562            .project(vec![-col("a")])?
1563            .build()?;
1564
1565        assert_optimized_plan_equal!(
1566            plan,
1567            @r"
1568        Projection: (- test.a)
1569          TableScan: test projection=[a]
1570        "
1571        )
1572    }
1573
1574    #[test]
1575    fn test_is_null() -> Result<()> {
1576        let table_scan = test_table_scan()?;
1577        let plan = LogicalPlanBuilder::from(table_scan)
1578            .project(vec![col("a").is_null()])?
1579            .build()?;
1580
1581        assert_optimized_plan_equal!(
1582            plan,
1583            @r"
1584        Projection: test.a IS NULL
1585          TableScan: test projection=[a]
1586        "
1587        )
1588    }
1589
1590    #[test]
1591    fn test_is_not_null() -> Result<()> {
1592        let table_scan = test_table_scan()?;
1593        let plan = LogicalPlanBuilder::from(table_scan)
1594            .project(vec![col("a").is_not_null()])?
1595            .build()?;
1596
1597        assert_optimized_plan_equal!(
1598            plan,
1599            @r"
1600        Projection: test.a IS NOT NULL
1601          TableScan: test projection=[a]
1602        "
1603        )
1604    }
1605
1606    #[test]
1607    fn test_is_true() -> Result<()> {
1608        let table_scan = test_table_scan()?;
1609        let plan = LogicalPlanBuilder::from(table_scan)
1610            .project(vec![col("a").is_true()])?
1611            .build()?;
1612
1613        assert_optimized_plan_equal!(
1614            plan,
1615            @r"
1616        Projection: test.a IS TRUE
1617          TableScan: test projection=[a]
1618        "
1619        )
1620    }
1621
1622    #[test]
1623    fn test_is_not_true() -> Result<()> {
1624        let table_scan = test_table_scan()?;
1625        let plan = LogicalPlanBuilder::from(table_scan)
1626            .project(vec![col("a").is_not_true()])?
1627            .build()?;
1628
1629        assert_optimized_plan_equal!(
1630            plan,
1631            @r"
1632        Projection: test.a IS NOT TRUE
1633          TableScan: test projection=[a]
1634        "
1635        )
1636    }
1637
1638    #[test]
1639    fn test_is_false() -> Result<()> {
1640        let table_scan = test_table_scan()?;
1641        let plan = LogicalPlanBuilder::from(table_scan)
1642            .project(vec![col("a").is_false()])?
1643            .build()?;
1644
1645        assert_optimized_plan_equal!(
1646            plan,
1647            @r"
1648        Projection: test.a IS FALSE
1649          TableScan: test projection=[a]
1650        "
1651        )
1652    }
1653
1654    #[test]
1655    fn test_is_not_false() -> Result<()> {
1656        let table_scan = test_table_scan()?;
1657        let plan = LogicalPlanBuilder::from(table_scan)
1658            .project(vec![col("a").is_not_false()])?
1659            .build()?;
1660
1661        assert_optimized_plan_equal!(
1662            plan,
1663            @r"
1664        Projection: test.a IS NOT FALSE
1665          TableScan: test projection=[a]
1666        "
1667        )
1668    }
1669
1670    #[test]
1671    fn test_is_unknown() -> Result<()> {
1672        let table_scan = test_table_scan()?;
1673        let plan = LogicalPlanBuilder::from(table_scan)
1674            .project(vec![col("a").is_unknown()])?
1675            .build()?;
1676
1677        assert_optimized_plan_equal!(
1678            plan,
1679            @r"
1680        Projection: test.a IS UNKNOWN
1681          TableScan: test projection=[a]
1682        "
1683        )
1684    }
1685
1686    #[test]
1687    fn test_is_not_unknown() -> Result<()> {
1688        let table_scan = test_table_scan()?;
1689        let plan = LogicalPlanBuilder::from(table_scan)
1690            .project(vec![col("a").is_not_unknown()])?
1691            .build()?;
1692
1693        assert_optimized_plan_equal!(
1694            plan,
1695            @r"
1696        Projection: test.a IS NOT UNKNOWN
1697          TableScan: test projection=[a]
1698        "
1699        )
1700    }
1701
1702    #[test]
1703    fn test_not() -> Result<()> {
1704        let table_scan = test_table_scan()?;
1705        let plan = LogicalPlanBuilder::from(table_scan)
1706            .project(vec![not(col("a"))])?
1707            .build()?;
1708
1709        assert_optimized_plan_equal!(
1710            plan,
1711            @r"
1712        Projection: NOT test.a
1713          TableScan: test projection=[a]
1714        "
1715        )
1716    }
1717
1718    #[test]
1719    fn test_try_cast() -> Result<()> {
1720        let table_scan = test_table_scan()?;
1721        let plan = LogicalPlanBuilder::from(table_scan)
1722            .project(vec![try_cast(col("a"), DataType::Float64)])?
1723            .build()?;
1724
1725        assert_optimized_plan_equal!(
1726            plan,
1727            @r"
1728        Projection: TRY_CAST(test.a AS Float64)
1729          TableScan: test projection=[a]
1730        "
1731        )
1732    }
1733
1734    #[test]
1735    fn test_similar_to() -> Result<()> {
1736        let table_scan = test_table_scan()?;
1737        let expr = Box::new(col("a"));
1738        let pattern = Box::new(lit("[0-9]"));
1739        let similar_to_expr =
1740            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
1741        let plan = LogicalPlanBuilder::from(table_scan)
1742            .project(vec![similar_to_expr])?
1743            .build()?;
1744
1745        assert_optimized_plan_equal!(
1746            plan,
1747            @r#"
1748        Projection: test.a SIMILAR TO Utf8("[0-9]")
1749          TableScan: test projection=[a]
1750        "#
1751        )
1752    }
1753
1754    #[test]
1755    fn test_between() -> Result<()> {
1756        let table_scan = test_table_scan()?;
1757        let plan = LogicalPlanBuilder::from(table_scan)
1758            .project(vec![col("a").between(lit(1), lit(3))])?
1759            .build()?;
1760
1761        assert_optimized_plan_equal!(
1762            plan,
1763            @r"
1764        Projection: test.a BETWEEN Int32(1) AND Int32(3)
1765          TableScan: test projection=[a]
1766        "
1767        )
1768    }
1769
1770    // Test Case expression
1771    #[test]
1772    fn test_case_merged() -> Result<()> {
1773        let table_scan = test_table_scan()?;
1774        let plan = LogicalPlanBuilder::from(table_scan)
1775            .project(vec![col("a"), lit(0).alias("d")])?
1776            .project(vec![
1777                col("a"),
1778                when(col("a").eq(lit(1)), lit(10))
1779                    .otherwise(col("d"))?
1780                    .alias("d"),
1781            ])?
1782            .build()?;
1783
1784        assert_optimized_plan_equal!(
1785            plan,
1786            @r"
1787        Projection: test.a, CASE WHEN test.a = Int32(1) THEN Int32(10) ELSE Int32(0) END AS d
1788          TableScan: test projection=[a]
1789        "
1790        )
1791    }
1792
1793    // Test outer projection isn't discarded despite the same schema as inner
1794    // https://github.com/apache/datafusion/issues/8942
1795    #[test]
1796    fn test_derived_column() -> Result<()> {
1797        let table_scan = test_table_scan()?;
1798        let plan = LogicalPlanBuilder::from(table_scan)
1799            .project(vec![col("a").add(lit(1)).alias("a"), lit(0).alias("d")])?
1800            .project(vec![
1801                col("a"),
1802                when(col("a").eq(lit(1)), lit(10))
1803                    .otherwise(col("d"))?
1804                    .alias("d"),
1805            ])?
1806            .build()?;
1807
1808        assert_optimized_plan_equal!(
1809            plan,
1810            @r"
1811        Projection: a, CASE WHEN a = Int32(1) THEN Int32(10) ELSE d END AS d
1812          Projection: test.a + Int32(1) AS a, Int32(0) AS d
1813            TableScan: test projection=[a]
1814        "
1815        )
1816    }
1817
1818    // Since only column `a` is referred at the output. Scan should only contain projection=[a].
1819    // User defined node should be able to propagate necessary expressions by its parent to its child.
1820    #[test]
1821    fn test_user_defined_logical_plan_node() -> Result<()> {
1822        let table_scan = test_table_scan()?;
1823        let custom_plan = LogicalPlan::Extension(Extension {
1824            node: Arc::new(NoOpUserDefined::new(
1825                Arc::clone(table_scan.schema()),
1826                Arc::new(table_scan.clone()),
1827            )),
1828        });
1829        let plan = LogicalPlanBuilder::from(custom_plan)
1830            .project(vec![col("a"), lit(0).alias("d")])?
1831            .build()?;
1832
1833        assert_optimized_plan_equal!(
1834            plan,
1835            @r"
1836        Projection: test.a, Int32(0) AS d
1837          NoOpUserDefined
1838            TableScan: test projection=[a]
1839        "
1840        )
1841    }
1842
1843    // Only column `a` is referred at the output. However, User defined node itself uses column `b`
1844    // during its operation. Hence, scan should contain projection=[a, b].
1845    // User defined node should be able to propagate necessary expressions by its parent, as well as its own
1846    // required expressions.
1847    #[test]
1848    fn test_user_defined_logical_plan_node2() -> Result<()> {
1849        let table_scan = test_table_scan()?;
1850        let exprs = vec![Expr::Column(Column::from_qualified_name("b"))];
1851        let custom_plan = LogicalPlan::Extension(Extension {
1852            node: Arc::new(
1853                NoOpUserDefined::new(
1854                    Arc::clone(table_scan.schema()),
1855                    Arc::new(table_scan.clone()),
1856                )
1857                .with_exprs(exprs),
1858            ),
1859        });
1860        let plan = LogicalPlanBuilder::from(custom_plan)
1861            .project(vec![col("a"), lit(0).alias("d")])?
1862            .build()?;
1863
1864        assert_optimized_plan_equal!(
1865            plan,
1866            @r"
1867        Projection: test.a, Int32(0) AS d
1868          NoOpUserDefined
1869            TableScan: test projection=[a, b]
1870        "
1871        )
1872    }
1873
1874    // Only column `a` is referred at the output. However, User defined node itself uses expression `b+c`
1875    // during its operation. Hence, scan should contain projection=[a, b, c].
1876    // User defined node should be able to propagate necessary expressions by its parent, as well as its own
1877    // required expressions. Expressions doesn't have to be just column. Requirements from complex expressions
1878    // should be propagated also.
1879    #[test]
1880    fn test_user_defined_logical_plan_node3() -> Result<()> {
1881        let table_scan = test_table_scan()?;
1882        let left_expr = Expr::Column(Column::from_qualified_name("b"));
1883        let right_expr = Expr::Column(Column::from_qualified_name("c"));
1884        let binary_expr = Expr::BinaryExpr(BinaryExpr::new(
1885            Box::new(left_expr),
1886            Operator::Plus,
1887            Box::new(right_expr),
1888        ));
1889        let exprs = vec![binary_expr];
1890        let custom_plan = LogicalPlan::Extension(Extension {
1891            node: Arc::new(
1892                NoOpUserDefined::new(
1893                    Arc::clone(table_scan.schema()),
1894                    Arc::new(table_scan.clone()),
1895                )
1896                .with_exprs(exprs),
1897            ),
1898        });
1899        let plan = LogicalPlanBuilder::from(custom_plan)
1900            .project(vec![col("a"), lit(0).alias("d")])?
1901            .build()?;
1902
1903        assert_optimized_plan_equal!(
1904            plan,
1905            @r"
1906        Projection: test.a, Int32(0) AS d
1907          NoOpUserDefined
1908            TableScan: test projection=[a, b, c]
1909        "
1910        )
1911    }
1912
1913    // Columns `l.a`, `l.c`, `r.a` is referred at the output.
1914    // User defined node should be able to propagate necessary expressions by its parent, to its children.
1915    // Even if it has multiple children.
1916    // left child should have `projection=[a, c]`, and right side should have `projection=[a]`.
1917    #[test]
1918    fn test_user_defined_logical_plan_node4() -> Result<()> {
1919        let left_table = test_table_scan_with_name("l")?;
1920        let right_table = test_table_scan_with_name("r")?;
1921        let custom_plan = LogicalPlan::Extension(Extension {
1922            node: Arc::new(UserDefinedCrossJoin::new(
1923                Arc::new(left_table),
1924                Arc::new(right_table),
1925            )),
1926        });
1927        let plan = LogicalPlanBuilder::from(custom_plan)
1928            .project(vec![col("l.a"), col("l.c"), col("r.a"), lit(0).alias("d")])?
1929            .build()?;
1930
1931        assert_optimized_plan_equal!(
1932            plan,
1933            @r"
1934        Projection: l.a, l.c, r.a, Int32(0) AS d
1935          UserDefinedCrossJoin
1936            TableScan: l projection=[a, c]
1937            TableScan: r projection=[a]
1938        "
1939        )
1940    }
1941
1942    #[test]
1943    fn aggregate_no_group_by() -> Result<()> {
1944        let table_scan = test_table_scan()?;
1945
1946        let plan = LogicalPlanBuilder::from(table_scan)
1947            .aggregate(Vec::<Expr>::new(), vec![max(col("b"))])?
1948            .build()?;
1949
1950        assert_optimized_plan_equal!(
1951            plan,
1952            @r"
1953        Aggregate: groupBy=[[]], aggr=[[max(test.b)]]
1954          TableScan: test projection=[b]
1955        "
1956        )
1957    }
1958
1959    #[test]
1960    fn aggregate_group_by() -> Result<()> {
1961        let table_scan = test_table_scan()?;
1962
1963        let plan = LogicalPlanBuilder::from(table_scan)
1964            .aggregate(vec![col("c")], vec![max(col("b"))])?
1965            .build()?;
1966
1967        assert_optimized_plan_equal!(
1968            plan,
1969            @r"
1970        Aggregate: groupBy=[[test.c]], aggr=[[max(test.b)]]
1971          TableScan: test projection=[b, c]
1972        "
1973        )
1974    }
1975
1976    #[test]
1977    fn aggregate_group_by_with_table_alias() -> Result<()> {
1978        let table_scan = test_table_scan()?;
1979
1980        let plan = LogicalPlanBuilder::from(table_scan)
1981            .alias("a")?
1982            .aggregate(vec![col("c")], vec![max(col("b"))])?
1983            .build()?;
1984
1985        assert_optimized_plan_equal!(
1986            plan,
1987            @r"
1988        Aggregate: groupBy=[[a.c]], aggr=[[max(a.b)]]
1989          SubqueryAlias: a
1990            TableScan: test projection=[b, c]
1991        "
1992        )
1993    }
1994
1995    #[test]
1996    fn aggregate_no_group_by_with_filter() -> Result<()> {
1997        let table_scan = test_table_scan()?;
1998
1999        let plan = LogicalPlanBuilder::from(table_scan)
2000            .filter(col("c").gt(lit(1)))?
2001            .aggregate(Vec::<Expr>::new(), vec![max(col("b"))])?
2002            .build()?;
2003
2004        assert_optimized_plan_equal!(
2005            plan,
2006            @r"
2007        Aggregate: groupBy=[[]], aggr=[[max(test.b)]]
2008          Projection: test.b
2009            Filter: test.c > Int32(1)
2010              TableScan: test projection=[b, c]
2011        "
2012        )
2013    }
2014
2015    #[test]
2016    fn aggregate_with_periods() -> Result<()> {
2017        let schema = Schema::new(vec![Field::new("tag.one", DataType::Utf8, false)]);
2018
2019        // Build a plan that looks as follows (note "tag.one" is a column named
2020        // "tag.one", not a column named "one" in a table named "tag"):
2021        //
2022        // Projection: tag.one
2023        //   Aggregate: groupBy=[], aggr=[max("tag.one") AS "tag.one"]
2024        //    TableScan
2025        let plan = table_scan(Some("m4"), &schema, None)?
2026            .aggregate(
2027                Vec::<Expr>::new(),
2028                vec![max(col(Column::new_unqualified("tag.one"))).alias("tag.one")],
2029            )?
2030            .project([col(Column::new_unqualified("tag.one"))])?
2031            .build()?;
2032
2033        assert_optimized_plan_equal!(
2034            plan,
2035            @r"
2036        Aggregate: groupBy=[[]], aggr=[[max(m4.tag.one) AS tag.one]]
2037          TableScan: m4 projection=[tag.one]
2038        "
2039        )
2040    }
2041
2042    #[test]
2043    fn redundant_project() -> Result<()> {
2044        let table_scan = test_table_scan()?;
2045
2046        let plan = LogicalPlanBuilder::from(table_scan)
2047            .project(vec![col("a"), col("b"), col("c")])?
2048            .project(vec![col("a"), col("c"), col("b")])?
2049            .build()?;
2050        assert_optimized_plan_equal!(
2051            plan,
2052            @r"
2053        Projection: test.a, test.c, test.b
2054          TableScan: test projection=[a, b, c]
2055        "
2056        )
2057    }
2058
2059    #[test]
2060    fn reorder_scan() -> Result<()> {
2061        let schema = Schema::new(test_table_scan_fields());
2062
2063        let plan = table_scan(Some("test"), &schema, Some(vec![1, 0, 2]))?.build()?;
2064        assert_optimized_plan_equal!(
2065            plan,
2066            @"TableScan: test projection=[b, a, c]"
2067        )
2068    }
2069
2070    #[test]
2071    fn reorder_scan_projection() -> Result<()> {
2072        let schema = Schema::new(test_table_scan_fields());
2073
2074        let plan = table_scan(Some("test"), &schema, Some(vec![1, 0, 2]))?
2075            .project(vec![col("a"), col("b")])?
2076            .build()?;
2077        assert_optimized_plan_equal!(
2078            plan,
2079            @r"
2080        Projection: test.a, test.b
2081          TableScan: test projection=[b, a]
2082        "
2083        )
2084    }
2085
2086    #[test]
2087    fn reorder_projection() -> Result<()> {
2088        let table_scan = test_table_scan()?;
2089
2090        let plan = LogicalPlanBuilder::from(table_scan)
2091            .project(vec![col("c"), col("b"), col("a")])?
2092            .build()?;
2093        assert_optimized_plan_equal!(
2094            plan,
2095            @r"
2096        Projection: test.c, test.b, test.a
2097          TableScan: test projection=[a, b, c]
2098        "
2099        )
2100    }
2101
2102    #[test]
2103    fn noncontinuous_redundant_projection() -> Result<()> {
2104        let table_scan = test_table_scan()?;
2105
2106        let plan = LogicalPlanBuilder::from(table_scan)
2107            .project(vec![col("c"), col("b"), col("a")])?
2108            .filter(col("c").gt(lit(1)))?
2109            .project(vec![col("c"), col("a"), col("b")])?
2110            .filter(col("b").gt(lit(1)))?
2111            .filter(col("a").gt(lit(1)))?
2112            .project(vec![col("a"), col("c"), col("b")])?
2113            .build()?;
2114        assert_optimized_plan_equal!(
2115            plan,
2116            @r"
2117        Projection: test.a, test.c, test.b
2118          Filter: test.a > Int32(1)
2119            Filter: test.b > Int32(1)
2120              Projection: test.c, test.a, test.b
2121                Filter: test.c > Int32(1)
2122                  Projection: test.c, test.b, test.a
2123                    TableScan: test projection=[a, b, c]
2124        "
2125        )
2126    }
2127
2128    #[test]
2129    fn join_schema_trim_full_join_column_projection() -> Result<()> {
2130        let table_scan = test_table_scan()?;
2131
2132        let schema = Schema::new(vec![Field::new("c1", DataType::UInt32, false)]);
2133        let table2_scan = scan_empty(Some("test2"), &schema, None)?.build()?;
2134
2135        let plan = LogicalPlanBuilder::from(table_scan)
2136            .join(table2_scan, JoinType::Left, (vec!["a"], vec!["c1"]), None)?
2137            .project(vec![col("a"), col("b"), col("c1")])?
2138            .build()?;
2139
2140        let optimized_plan = optimize(plan)?;
2141
2142        // make sure projections are pushed down to both table scans
2143        assert_snapshot!(
2144            optimized_plan.clone(),
2145            @r"
2146        Left Join: test.a = test2.c1
2147          TableScan: test projection=[a, b]
2148          TableScan: test2 projection=[c1]
2149        "
2150        );
2151
2152        // make sure schema for join node include both join columns
2153        let optimized_join = optimized_plan;
2154        assert_eq!(
2155            **optimized_join.schema(),
2156            DFSchema::new_with_metadata(
2157                vec![
2158                    (
2159                        Some("test".into()),
2160                        Arc::new(Field::new("a", DataType::UInt32, false))
2161                    ),
2162                    (
2163                        Some("test".into()),
2164                        Arc::new(Field::new("b", DataType::UInt32, false))
2165                    ),
2166                    (
2167                        Some("test2".into()),
2168                        Arc::new(Field::new("c1", DataType::UInt32, true))
2169                    ),
2170                ],
2171                HashMap::new()
2172            )?,
2173        );
2174
2175        Ok(())
2176    }
2177
2178    #[test]
2179    fn join_schema_trim_partial_join_column_projection() -> Result<()> {
2180        // test join column push down without explicit column projections
2181
2182        let table_scan = test_table_scan()?;
2183
2184        let schema = Schema::new(vec![Field::new("c1", DataType::UInt32, false)]);
2185        let table2_scan = scan_empty(Some("test2"), &schema, None)?.build()?;
2186
2187        let plan = LogicalPlanBuilder::from(table_scan)
2188            .join(table2_scan, JoinType::Left, (vec!["a"], vec!["c1"]), None)?
2189            // projecting joined column `a` should push the right side column `c1` projection as
2190            // well into test2 table even though `c1` is not referenced in projection.
2191            .project(vec![col("a"), col("b")])?
2192            .build()?;
2193
2194        let optimized_plan = optimize(plan)?;
2195
2196        // make sure projections are pushed down to both table scans
2197        assert_snapshot!(
2198            optimized_plan.clone(),
2199            @r"
2200        Projection: test.a, test.b
2201          Left Join: test.a = test2.c1
2202            TableScan: test projection=[a, b]
2203            TableScan: test2 projection=[c1]
2204        "
2205        );
2206
2207        // make sure schema for join node include both join columns
2208        let optimized_join = optimized_plan.inputs()[0];
2209        assert_eq!(
2210            **optimized_join.schema(),
2211            DFSchema::new_with_metadata(
2212                vec![
2213                    (
2214                        Some("test".into()),
2215                        Arc::new(Field::new("a", DataType::UInt32, false))
2216                    ),
2217                    (
2218                        Some("test".into()),
2219                        Arc::new(Field::new("b", DataType::UInt32, false))
2220                    ),
2221                    (
2222                        Some("test2".into()),
2223                        Arc::new(Field::new("c1", DataType::UInt32, true))
2224                    ),
2225                ],
2226                HashMap::new()
2227            )?,
2228        );
2229
2230        Ok(())
2231    }
2232
2233    #[test]
2234    fn join_schema_trim_using_join() -> Result<()> {
2235        // shared join columns from using join should be pushed to both sides
2236
2237        let table_scan = test_table_scan()?;
2238
2239        let schema = Schema::new(vec![Field::new("a", DataType::UInt32, false)]);
2240        let table2_scan = scan_empty(Some("test2"), &schema, None)?.build()?;
2241
2242        let plan = LogicalPlanBuilder::from(table_scan)
2243            .join_using(table2_scan, JoinType::Left, vec!["a".into()])?
2244            .project(vec![col("a"), col("b")])?
2245            .build()?;
2246
2247        let optimized_plan = optimize(plan)?;
2248
2249        // make sure projections are pushed down to table scan
2250        assert_snapshot!(
2251            optimized_plan.clone(),
2252            @r"
2253        Projection: test.a, test.b
2254          Left Join: Using test.a = test2.a
2255            TableScan: test projection=[a, b]
2256            TableScan: test2 projection=[a]
2257        "
2258        );
2259
2260        // make sure schema for join node include both join columns
2261        let optimized_join = optimized_plan.inputs()[0];
2262        assert_eq!(
2263            **optimized_join.schema(),
2264            DFSchema::new_with_metadata(
2265                vec![
2266                    (
2267                        Some("test".into()),
2268                        Arc::new(Field::new("a", DataType::UInt32, false))
2269                    ),
2270                    (
2271                        Some("test".into()),
2272                        Arc::new(Field::new("b", DataType::UInt32, false))
2273                    ),
2274                    (
2275                        Some("test2".into()),
2276                        Arc::new(Field::new("a", DataType::UInt32, true))
2277                    ),
2278                ],
2279                HashMap::new()
2280            )?,
2281        );
2282
2283        Ok(())
2284    }
2285
2286    #[test]
2287    fn cast() -> Result<()> {
2288        let table_scan = test_table_scan()?;
2289
2290        let plan = LogicalPlanBuilder::from(table_scan)
2291            .project(vec![Expr::Cast(Cast::new(
2292                Box::new(col("c")),
2293                DataType::Float64,
2294            ))])?
2295            .build()?;
2296
2297        assert_optimized_plan_equal!(
2298            plan,
2299            @r"
2300        Projection: CAST(test.c AS Float64)
2301          TableScan: test projection=[c]
2302        "
2303        )
2304    }
2305
2306    #[test]
2307    fn table_scan_projected_schema() -> Result<()> {
2308        let table_scan = test_table_scan()?;
2309        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2310            .project(vec![col("a"), col("b")])?
2311            .build()?;
2312
2313        assert_eq!(3, table_scan.schema().fields().len());
2314        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2315        assert_fields_eq(&plan, vec!["a", "b"]);
2316
2317        assert_optimized_plan_equal!(
2318            plan,
2319            @"TableScan: test projection=[a, b]"
2320        )
2321    }
2322
2323    #[test]
2324    fn table_scan_projected_schema_non_qualified_relation() -> Result<()> {
2325        let table_scan = test_table_scan()?;
2326        let input_schema = table_scan.schema();
2327        assert_eq!(3, input_schema.fields().len());
2328        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2329
2330        // Build the LogicalPlan directly (don't use PlanBuilder), so
2331        // that the Column references are unqualified (e.g. their
2332        // relation is `None`). PlanBuilder resolves the expressions
2333        let expr = vec![col("test.a"), col("test.b")];
2334        let plan =
2335            LogicalPlan::Projection(Projection::try_new(expr, Arc::new(table_scan))?);
2336
2337        assert_fields_eq(&plan, vec!["a", "b"]);
2338
2339        assert_optimized_plan_equal!(
2340            plan,
2341            @"TableScan: test projection=[a, b]"
2342        )
2343    }
2344
2345    #[test]
2346    fn table_limit() -> Result<()> {
2347        let table_scan = test_table_scan()?;
2348        assert_eq!(3, table_scan.schema().fields().len());
2349        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2350
2351        let plan = LogicalPlanBuilder::from(table_scan)
2352            .project(vec![col("c"), col("a")])?
2353            .limit(0, Some(5))?
2354            .build()?;
2355
2356        assert_fields_eq(&plan, vec!["c", "a"]);
2357
2358        assert_optimized_plan_equal!(
2359            plan,
2360            @r"
2361        Limit: skip=0, fetch=5
2362          Projection: test.c, test.a
2363            TableScan: test projection=[a, c]
2364        "
2365        )
2366    }
2367
2368    #[test]
2369    fn table_scan_without_projection() -> Result<()> {
2370        let table_scan = test_table_scan()?;
2371        let plan = LogicalPlanBuilder::from(table_scan).build()?;
2372        // should expand projection to all columns without projection
2373        assert_optimized_plan_equal!(
2374            plan,
2375            @"TableScan: test projection=[a, b, c]"
2376        )
2377    }
2378
2379    #[test]
2380    fn table_scan_with_literal_projection() -> Result<()> {
2381        let table_scan = test_table_scan()?;
2382        let plan = LogicalPlanBuilder::from(table_scan)
2383            .project(vec![lit(1_i64), lit(2_i64)])?
2384            .build()?;
2385        assert_optimized_plan_equal!(
2386            plan,
2387            @r"
2388        Projection: Int64(1), Int64(2)
2389          TableScan: test projection=[]
2390        "
2391        )
2392    }
2393
2394    /// tests that it removes unused columns in projections
2395    #[test]
2396    fn table_unused_column() -> Result<()> {
2397        let table_scan = test_table_scan()?;
2398        assert_eq!(3, table_scan.schema().fields().len());
2399        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2400
2401        // we never use "b" in the first projection => remove it
2402        let plan = LogicalPlanBuilder::from(table_scan)
2403            .project(vec![col("c"), col("a"), col("b")])?
2404            .filter(col("c").gt(lit(1)))?
2405            .aggregate(vec![col("c")], vec![max(col("a"))])?
2406            .build()?;
2407
2408        assert_fields_eq(&plan, vec!["c", "max(test.a)"]);
2409
2410        let plan = optimize(plan).expect("failed to optimize plan");
2411        assert_optimized_plan_equal!(
2412            plan,
2413            @r"
2414        Aggregate: groupBy=[[test.c]], aggr=[[max(test.a)]]
2415          Filter: test.c > Int32(1)
2416            Projection: test.c, test.a
2417              TableScan: test projection=[a, c]
2418        "
2419        )
2420    }
2421
2422    /// tests that it removes un-needed projections
2423    #[test]
2424    fn table_unused_projection() -> Result<()> {
2425        let table_scan = test_table_scan()?;
2426        assert_eq!(3, table_scan.schema().fields().len());
2427        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2428
2429        // there is no need for the first projection
2430        let plan = LogicalPlanBuilder::from(table_scan)
2431            .project(vec![col("b")])?
2432            .project(vec![lit(1).alias("a")])?
2433            .build()?;
2434
2435        assert_fields_eq(&plan, vec!["a"]);
2436
2437        assert_optimized_plan_equal!(
2438            plan,
2439            @r"
2440        Projection: Int32(1) AS a
2441          TableScan: test projection=[]
2442        "
2443        )
2444    }
2445
2446    #[test]
2447    fn table_full_filter_pushdown() -> Result<()> {
2448        let schema = Schema::new(test_table_scan_fields());
2449
2450        let table_scan = table_scan_with_filters(
2451            Some("test"),
2452            &schema,
2453            None,
2454            vec![col("b").eq(lit(1))],
2455        )?
2456        .build()?;
2457        assert_eq!(3, table_scan.schema().fields().len());
2458        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2459
2460        // there is no need for the first projection
2461        let plan = LogicalPlanBuilder::from(table_scan)
2462            .project(vec![col("b")])?
2463            .project(vec![lit(1).alias("a")])?
2464            .build()?;
2465
2466        assert_fields_eq(&plan, vec!["a"]);
2467
2468        assert_optimized_plan_equal!(
2469            plan,
2470            @r"
2471        Projection: Int32(1) AS a
2472          TableScan: test projection=[], full_filters=[b = Int32(1)]
2473        "
2474        )
2475    }
2476
2477    /// tests that optimizing twice yields same plan
2478    #[test]
2479    fn test_double_optimization() -> Result<()> {
2480        let table_scan = test_table_scan()?;
2481
2482        let plan = LogicalPlanBuilder::from(table_scan)
2483            .project(vec![col("b")])?
2484            .project(vec![lit(1).alias("a")])?
2485            .build()?;
2486
2487        let optimized_plan1 = optimize(plan).expect("failed to optimize plan");
2488        let optimized_plan2 =
2489            optimize(optimized_plan1.clone()).expect("failed to optimize plan");
2490
2491        let formatted_plan1 = format!("{optimized_plan1:?}");
2492        let formatted_plan2 = format!("{optimized_plan2:?}");
2493        assert_eq!(formatted_plan1, formatted_plan2);
2494        Ok(())
2495    }
2496
2497    #[test]
2498    fn test_continue_processing_through_extension() -> Result<()> {
2499        let table_scan = test_table_scan()?;
2500        let plan = LogicalPlanBuilder::from(table_scan.clone())
2501            .project(vec![col("a")])?
2502            .project(vec![col("a")])?
2503            .build()?;
2504        let plan = LogicalPlan::Extension(Extension {
2505            node: Arc::new(OpaqueRequirementsUserDefined {
2506                input: Arc::new(plan),
2507                schema: Arc::clone(table_scan.schema()),
2508            }),
2509        });
2510        let plan = optimize(plan).expect("failed to optimize plan");
2511        assert_optimized_plan_equal!(
2512            plan,
2513            @r"
2514        OpaqueRequirementsUserDefined
2515          TableScan: test projection=[a]
2516        "
2517        )
2518    }
2519
2520    /// tests that it removes an aggregate is never used downstream
2521    #[test]
2522    fn table_unused_aggregate() -> Result<()> {
2523        let table_scan = test_table_scan()?;
2524        assert_eq!(3, table_scan.schema().fields().len());
2525        assert_fields_eq(&table_scan, vec!["a", "b", "c"]);
2526
2527        // we never use "min(b)" => remove it
2528        let plan = LogicalPlanBuilder::from(table_scan)
2529            .aggregate(vec![col("a"), col("c")], vec![max(col("b")), min(col("b"))])?
2530            .filter(col("c").gt(lit(1)))?
2531            .project(vec![col("c"), col("a"), col("max(test.b)")])?
2532            .build()?;
2533
2534        assert_fields_eq(&plan, vec!["c", "a", "max(test.b)"]);
2535
2536        assert_optimized_plan_equal!(
2537            plan,
2538            @r"
2539        Projection: test.c, test.a, max(test.b)
2540          Filter: test.c > Int32(1)
2541            Aggregate: groupBy=[[test.a, test.c]], aggr=[[max(test.b)]]
2542              TableScan: test projection=[a, b, c]
2543        "
2544        )
2545    }
2546
2547    #[test]
2548    fn aggregate_filter_pushdown() -> Result<()> {
2549        let table_scan = test_table_scan()?;
2550        let aggr_with_filter = count_udaf()
2551            .call(vec![col("b")])
2552            .filter(col("c").gt(lit(42)))
2553            .build()?;
2554        let plan = LogicalPlanBuilder::from(table_scan)
2555            .aggregate(
2556                vec![col("a")],
2557                vec![count(col("b")), aggr_with_filter.alias("count2")],
2558            )?
2559            .build()?;
2560
2561        assert_optimized_plan_equal!(
2562            plan,
2563            @r"
2564        Aggregate: groupBy=[[test.a]], aggr=[[count(test.b), count(test.b) FILTER (WHERE test.c > Int32(42)) AS count2]]
2565          TableScan: test projection=[a, b, c]
2566        "
2567        )
2568    }
2569
2570    #[test]
2571    fn pushdown_through_distinct() -> Result<()> {
2572        let table_scan = test_table_scan()?;
2573
2574        let plan = LogicalPlanBuilder::from(table_scan)
2575            .project(vec![col("a"), col("b")])?
2576            .distinct()?
2577            .project(vec![col("a")])?
2578            .build()?;
2579
2580        assert_optimized_plan_equal!(
2581            plan,
2582            @r"
2583        Projection: test.a
2584          Distinct:
2585            TableScan: test projection=[a, b]
2586        "
2587        )
2588    }
2589
2590    #[test]
2591    fn test_window() -> Result<()> {
2592        let table_scan = test_table_scan()?;
2593
2594        let max1 = Expr::from(expr::WindowFunction::new(
2595            WindowFunctionDefinition::AggregateUDF(max_udaf()),
2596            vec![col("test.a")],
2597        ))
2598        .partition_by(vec![col("test.b")])
2599        .build()
2600        .unwrap();
2601
2602        let max2 = Expr::from(expr::WindowFunction::new(
2603            WindowFunctionDefinition::AggregateUDF(max_udaf()),
2604            vec![col("test.b")],
2605        ));
2606        let col1 = col(max1.schema_name().to_string());
2607        let col2 = col(max2.schema_name().to_string());
2608
2609        let plan = LogicalPlanBuilder::from(table_scan)
2610            .window(vec![max1])?
2611            .window(vec![max2])?
2612            .project(vec![col1, col2])?
2613            .build()?;
2614
2615        assert_optimized_plan_equal!(
2616            plan,
2617            @r"
2618        Projection: max(test.a) PARTITION BY [test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, max(test.b) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
2619          WindowAggr: windowExpr=[[max(test.b) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING]]
2620            Projection: test.b, max(test.a) PARTITION BY [test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
2621              WindowAggr: windowExpr=[[max(test.a) PARTITION BY [test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING]]
2622                TableScan: test projection=[a, b]
2623        "
2624        )
2625    }
2626
2627    // Regression test for https://github.com/apache/datafusion/issues/20083
2628    // Optimizer must not fail when LeftMark joins from EXISTS OR EXISTS
2629    // feed into a Left join.
2630    #[test]
2631    fn optimize_projections_exists_or_exists_with_outer_join() -> Result<()> {
2632        use datafusion_expr::utils::disjunction;
2633        use datafusion_expr::{exists, out_ref_col};
2634
2635        let table_a = test_table_scan_with_name("a")?;
2636        let table_b = test_table_scan_with_name("b")?;
2637
2638        let sq_a = Arc::new(
2639            LogicalPlanBuilder::from(test_table_scan_with_name("sq_a")?)
2640                .filter(col("sq_a.a").eq(out_ref_col(DataType::UInt32, "a.a")))?
2641                .project(vec![lit(1)])?
2642                .build()?,
2643        );
2644
2645        let sq_b = Arc::new(
2646            LogicalPlanBuilder::from(test_table_scan_with_name("sq_b")?)
2647                .filter(col("sq_b.b").eq(out_ref_col(DataType::UInt32, "a.b")))?
2648                .project(vec![lit(1)])?
2649                .build()?,
2650        );
2651
2652        let plan = LogicalPlanBuilder::from(table_a)
2653            .filter(disjunction(vec![exists(sq_a), exists(sq_b)]).unwrap())?
2654            .join(table_b, JoinType::Left, (vec!["a"], vec!["a"]), None)?
2655            .build()?;
2656
2657        let optimizer = Optimizer::new();
2658        let config = OptimizerContext::new();
2659        optimizer.optimize(plan, &config, observe)?;
2660
2661        Ok(())
2662    }
2663
2664    #[test]
2665    fn optimize_projections_left_mark_join_with_projection() -> Result<()> {
2666        let table_a = test_table_scan_with_name("a")?;
2667        let table_b = test_table_scan_with_name("b")?;
2668        let table_c = test_table_scan_with_name("c")?;
2669
2670        let plan = LogicalPlanBuilder::from(table_a)
2671            .join(table_b, JoinType::LeftMark, (vec!["a"], vec!["a"]), None)?
2672            .project(vec![col("a.a"), col("a.b"), col("a.c")])?
2673            .join(table_c, JoinType::Left, (vec!["a"], vec!["a"]), None)?
2674            .build()?;
2675
2676        assert_optimized_plan_equal!(
2677            plan,
2678            @r"
2679        Left Join: a.a = c.a
2680          Projection: a.a, a.b, a.c
2681            LeftMark Join: a.a = b.a
2682              TableScan: a projection=[a, b, c]
2683              TableScan: b projection=[a]
2684          TableScan: c projection=[a, b, c]
2685        "
2686        )
2687    }
2688
2689    // Stacked filter-less LeftMark joins (from `= ANY` / `<> ALL`) must keep
2690    // each `mark` qualified so they don't collide.
2691    #[test]
2692    fn optimize_projections_stacked_mark_joins_keep_qualified_mark() -> Result<()> {
2693        let person = test_table_scan_with_name("person")?;
2694
2695        let aliased_scan = |table: &str, alias: &str| -> Result<LogicalPlan> {
2696            LogicalPlanBuilder::from(test_table_scan_with_name(table)?)
2697                .project(vec![col(format!("{table}.a"))])?
2698                .alias(alias)?
2699                .build()
2700        };
2701
2702        let plan = LogicalPlanBuilder::from(person)
2703            .join_on(
2704                aliased_scan("s1", "__correlated_sq_1")?,
2705                JoinType::LeftMark,
2706                vec![lit(true)],
2707            )?
2708            .join_on(
2709                aliased_scan("s2", "__correlated_sq_2")?,
2710                JoinType::LeftMark,
2711                vec![lit(true)],
2712            )?
2713            .join_on(
2714                aliased_scan("s3", "__correlated_sq_3")?,
2715                JoinType::LeftMark,
2716                vec![lit(true)],
2717            )?
2718            .filter(
2719                col("__correlated_sq_1.mark")
2720                    .or(col("__correlated_sq_2.mark"))
2721                    .and(not(col("__correlated_sq_3.mark"))),
2722            )?
2723            .project(vec![col("person.a")])?
2724            .build()?;
2725
2726        assert_optimized_plan_equal!(
2727            plan,
2728            @r"
2729        Projection: person.a
2730          Filter: (__correlated_sq_1.mark OR __correlated_sq_2.mark) AND NOT __correlated_sq_3.mark
2731            LeftMark Join:  Filter: Boolean(true)
2732              LeftMark Join:  Filter: Boolean(true)
2733                LeftMark Join:  Filter: Boolean(true)
2734                  TableScan: person projection=[a]
2735                  SubqueryAlias: __correlated_sq_1
2736                    TableScan: s1 projection=[a]
2737                SubqueryAlias: __correlated_sq_2
2738                  TableScan: s2 projection=[a]
2739              SubqueryAlias: __correlated_sq_3
2740                TableScan: s3 projection=[a]
2741        "
2742        )
2743    }
2744
2745    /// Returns `schema` with the field called `name` marked nullable.
2746    fn with_nullable_field(schema: &DFSchema, name: &str) -> Result<DFSchemaRef> {
2747        let fields = schema
2748            .iter()
2749            .map(|(qualifier, field)| {
2750                let field = if field.name() == name {
2751                    Arc::new(field.as_ref().clone().with_nullable(true))
2752                } else {
2753                    Arc::clone(field)
2754                };
2755                (qualifier.cloned(), field)
2756            })
2757            .collect();
2758        Ok(Arc::new(DFSchema::new_with_metadata(
2759            fields,
2760            HashMap::new(),
2761        )?))
2762    }
2763
2764    /// Asserts that `plan` is a projection whose schema is the one its
2765    /// expressions derive.
2766    fn assert_projection_schema_derived(plan: &LogicalPlan) -> Result<()> {
2767        use datafusion_expr::logical_plan::projection_schema;
2768
2769        let LogicalPlan::Projection(projection) = plan else {
2770            panic!("expected a projection, got {plan}");
2771        };
2772        let derived = projection_schema(&projection.input, &projection.expr)?;
2773        assert_eq!(projection.schema.as_ref(), derived.as_ref());
2774        Ok(())
2775    }
2776
2777    /// When rewriting the input changes a field the projection reads, the
2778    /// projection's schema is derived again instead of reused.
2779    #[test]
2780    fn projection_schema_follows_rewritten_input() -> Result<()> {
2781        use datafusion_expr::Aggregate;
2782
2783        let table_scan = Arc::new(test_table_scan()?);
2784        let group_expr = vec![lit(1u32).alias("g")];
2785        let aggr_expr = vec![count(col("b")).alias("cnt")];
2786        let aggregate = Aggregate::try_new(
2787            Arc::clone(&table_scan),
2788            group_expr.clone(),
2789            aggr_expr.clone(),
2790        )?;
2791        // A non-null group column stored as nullable, as a rule that keeps a
2792        // node's schema while folding its expressions can leave it.
2793        let stale = with_nullable_field(&aggregate.schema, "g")?;
2794        let aggregate =
2795            Aggregate::try_new_with_schema(table_scan, group_expr, aggr_expr, stale)?;
2796        let plan = LogicalPlanBuilder::from(LogicalPlan::Aggregate(aggregate))
2797            .project(vec![col("g").alias("x")])?
2798            .build()?;
2799        assert!(plan.schema().field(0).is_nullable());
2800
2801        // Pruning `cnt` rebuilds the aggregate, which derives `g` as non-null.
2802        let optimized = optimize(plan)?;
2803        assert!(!optimized.schema().field(0).is_nullable());
2804        assert_projection_schema_derived(&optimized)
2805    }
2806
2807    /// A projection over a subquery derives its schema again instead of
2808    /// reusing one that may be stale.
2809    #[test]
2810    fn projection_schema_follows_subquery() -> Result<()> {
2811        let subquery = LogicalPlanBuilder::from(test_table_scan()?)
2812            .project(vec![col("a")])?
2813            .limit(0, Some(1))?
2814            .build()?;
2815        let input = Arc::new(test_table_scan()?);
2816        let exprs = vec![
2817            col("b"),
2818            datafusion_expr::scalar_subquery(Arc::new(subquery)).alias("s"),
2819        ];
2820        let derived = Projection::try_new(exprs.clone(), Arc::clone(&input))?;
2821        // Mark `b` nullable so a reused schema would differ from the derived one.
2822        let stale = with_nullable_field(&derived.schema, "b")?;
2823        let plan = LogicalPlan::Projection(Projection::try_new_with_schema(
2824            exprs, input, stale,
2825        )?);
2826
2827        let optimized = optimize(plan)?;
2828        assert_projection_schema_derived(&optimized)
2829    }
2830
2831    /// A downstream rule that rewrites `a AS x` into
2832    /// `CASE WHEN a > 0 THEN a END AS x` via `map_expressions`, so `x` becomes
2833    /// nullable. With `transform` false it rewrites nothing.
2834    #[derive(Debug)]
2835    struct RewriteToCase {
2836        transform: bool,
2837    }
2838
2839    impl OptimizerRule for RewriteToCase {
2840        fn name(&self) -> &str {
2841            "rewrite_to_case"
2842        }
2843
2844        fn apply_order(&self) -> Option<ApplyOrder> {
2845            Some(ApplyOrder::BottomUp)
2846        }
2847
2848        fn rewrite(
2849            &self,
2850            plan: LogicalPlan,
2851            _config: &dyn OptimizerConfig,
2852        ) -> Result<Transformed<LogicalPlan>> {
2853            if !self.transform || !matches!(plan, LogicalPlan::Projection(_)) {
2854                return Ok(Transformed::no(plan));
2855            }
2856            plan.map_expressions(|e| match e {
2857                Expr::Alias(Alias {
2858                    expr,
2859                    relation,
2860                    name,
2861                    metadata,
2862                }) if name == "x" && matches!(*expr, Expr::Column(_)) => {
2863                    let new = when(expr.as_ref().clone().gt(lit(0u32)), *expr).end()?;
2864                    Ok(Transformed::yes(Expr::Alias(Alias {
2865                        expr: Box::new(new),
2866                        relation,
2867                        name,
2868                        metadata,
2869                    })))
2870                }
2871                e => Ok(Transformed::no(e)),
2872            })
2873        }
2874    }
2875
2876    /// `SELECT DISTINCT x FROM (SELECT a AS x, b + 1 AS y FROM test)`
2877    fn distinct_over_x_and_y() -> Result<LogicalPlan> {
2878        LogicalPlanBuilder::from(test_table_scan()?)
2879            .project(vec![col("a").alias("x"), (col("b") + lit(1u32)).alias("y")])?
2880            .distinct()?
2881            .project(vec![col("x")])?
2882            .build()
2883    }
2884
2885    /// A projection whose expressions a downstream rule rewrote carries the
2886    /// schema the new expressions derive, even after `OptimizeProjections`
2887    /// prunes it and reuses its schema.
2888    #[test]
2889    fn projection_schema_follows_rule_rewrite() -> Result<()> {
2890        let plan = distinct_over_x_and_y()?;
2891        assert!(!plan.schema().field(0).is_nullable());
2892
2893        let optimizer = Optimizer::with_rules(vec![
2894            Arc::new(RewriteToCase { transform: true }),
2895            Arc::new(OptimizeProjections::new()),
2896        ]);
2897        let optimized = optimizer.optimize(plan, &OptimizerContext::new(), observe)?;
2898
2899        let mut projections = 0;
2900        optimized.apply(|plan| {
2901            if let LogicalPlan::Projection(_) = plan {
2902                assert_projection_schema_derived(plan)?;
2903                projections += 1;
2904            }
2905            Ok(TreeNodeRecursion::Continue)
2906        })?;
2907        assert!(projections > 0, "expected a projection in {optimized}");
2908        assert!(optimized.schema().field(0).is_nullable());
2909        Ok(())
2910    }
2911
2912    /// A rule that rewrites nothing keeps the projection's schema as is.
2913    #[test]
2914    fn projection_schema_kept_without_rule_rewrite() -> Result<()> {
2915        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2916            .project(vec![col("a").alias("x"), (col("b") + lit(1u32)).alias("y")])?
2917            .build()?;
2918        let schema = Arc::clone(plan.schema());
2919
2920        let rewritten =
2921            RewriteToCase { transform: false }.rewrite(plan, &OptimizerContext::new())?;
2922        assert!(!rewritten.transformed);
2923        assert!(Arc::ptr_eq(&schema, rewritten.data.schema()));
2924
2925        // Expressions visited but left unchanged also keep the schema.
2926        let rewritten = rewritten.data.map_expressions(|e| Ok(Transformed::no(e)))?;
2927        assert!(!rewritten.transformed);
2928        assert!(Arc::ptr_eq(&schema, rewritten.data.schema()));
2929        Ok(())
2930    }
2931
2932    fn observe(_plan: &LogicalPlan, _rule: &dyn OptimizerRule) {}
2933
2934    fn optimize(plan: LogicalPlan) -> Result<LogicalPlan> {
2935        let optimizer = Optimizer::with_rules(vec![Arc::new(OptimizeProjections::new())]);
2936        let optimized_plan =
2937            optimizer.optimize(plan, &OptimizerContext::new(), observe)?;
2938        Ok(optimized_plan)
2939    }
2940}