Skip to main content

datafusion_physical_expr/
projection.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//! [`ProjectionExpr`] and [`ProjectionExprs`] for representing projections.
6
7use std::ops::Deref;
8use std::sync::Arc;
9
10use crate::PhysicalExpr;
11use crate::expressions::{CastExpr, Column, Literal};
12use crate::scalar_function::ScalarFunctionExpr;
13use crate::utils::collect_columns;
14
15use arrow::array::{RecordBatch, RecordBatchOptions};
16use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
17use datafusion_common::stats::{ColumnStatistics, Precision};
18use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
19use datafusion_common::{
20    Result, ScalarValue, Statistics, assert_or_internal_err, internal_datafusion_err,
21    plan_err,
22};
23
24use datafusion_physical_expr_common::metrics::ExecutionPlanMetricsSet;
25use datafusion_physical_expr_common::metrics::ExpressionEvaluatorMetrics;
26use datafusion_physical_expr_common::physical_expr::fmt_sql;
27use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
28use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays_with_metrics;
29use indexmap::IndexMap;
30use itertools::Itertools;
31
32/// An expression used by projection operations.
33///
34/// The expression is evaluated and the result is stored in a column
35/// with the name specified by `alias`.
36///
37/// For example, the SQL expression `a + b AS sum_ab` would be represented
38/// as a `ProjectionExpr` where `expr` is the expression `a + b`
39/// and `alias` is the string `sum_ab`.
40///
41/// See [`ProjectionExprs`] for a collection of projection expressions.
42#[derive(Debug, Clone)]
43pub struct ProjectionExpr {
44    /// The expression that will be evaluated.
45    pub expr: Arc<dyn PhysicalExpr>,
46    /// The name of the output column for use an output schema.
47    pub alias: String,
48}
49
50impl PartialEq for ProjectionExpr {
51    fn eq(&self, other: &Self) -> bool {
52        let ProjectionExpr { expr, alias } = self;
53        expr.eq(&other.expr) && *alias == other.alias
54    }
55}
56
57impl Eq for ProjectionExpr {}
58
59/// Enables [`ProjectionExpr`] to be treated as a reference to its wrapped
60/// [`Arc<dyn PhysicalExpr>`] using [`AsRef::as_ref`].
61impl AsRef<Arc<dyn PhysicalExpr>> for ProjectionExpr {
62    fn as_ref(&self) -> &Arc<dyn PhysicalExpr> {
63        &self.expr
64    }
65}
66
67impl std::fmt::Display for ProjectionExpr {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        if self.expr.to_string() == self.alias {
70            write!(f, "{}", self.alias)
71        } else {
72            write!(f, "{} AS {}", self.expr, self.alias)
73        }
74    }
75}
76
77impl ProjectionExpr {
78    /// Create a new projection expression
79    pub fn new(expr: Arc<dyn PhysicalExpr>, alias: impl Into<String>) -> Self {
80        let alias = alias.into();
81        Self { expr, alias }
82    }
83
84    /// Create a new projection expression from an expression and a schema using the expression's output field name as alias.
85    pub fn new_from_expression(
86        expr: Arc<dyn PhysicalExpr>,
87        schema: &Schema,
88    ) -> Result<Self> {
89        let field = expr.return_field(schema)?;
90        Ok(Self {
91            expr,
92            alias: field.name().to_string(),
93        })
94    }
95}
96
97impl From<(Arc<dyn PhysicalExpr>, String)> for ProjectionExpr {
98    fn from(value: (Arc<dyn PhysicalExpr>, String)) -> Self {
99        Self::new(value.0, value.1)
100    }
101}
102
103impl From<&(Arc<dyn PhysicalExpr>, String)> for ProjectionExpr {
104    fn from(value: &(Arc<dyn PhysicalExpr>, String)) -> Self {
105        Self::new(Arc::clone(&value.0), value.1.clone())
106    }
107}
108
109impl From<ProjectionExpr> for (Arc<dyn PhysicalExpr>, String) {
110    fn from(value: ProjectionExpr) -> Self {
111        (value.expr, value.alias)
112    }
113}
114
115/// A collection of  [`ProjectionExpr`] instances, representing a complete
116/// projection operation.
117///
118/// Projection operations are used in query plans to select specific columns or
119/// compute new columns based on existing ones.
120///
121/// See [`ProjectionExprs::from_indices`] to select a subset of columns by
122/// indices.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct ProjectionExprs {
125    /// [`Arc`] used for a cheap clone, which improves physical plan optimization performance.
126    exprs: Arc<[ProjectionExpr]>,
127}
128
129impl std::fmt::Display for ProjectionExprs {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        let exprs: Vec<String> = self.exprs.iter().map(|e| e.to_string()).collect();
132        write!(f, "Projection[{}]", exprs.join(", "))
133    }
134}
135
136impl From<Vec<ProjectionExpr>> for ProjectionExprs {
137    fn from(value: Vec<ProjectionExpr>) -> Self {
138        Self {
139            exprs: value.into(),
140        }
141    }
142}
143
144impl From<&[ProjectionExpr]> for ProjectionExprs {
145    fn from(value: &[ProjectionExpr]) -> Self {
146        Self {
147            exprs: value.iter().cloned().collect(),
148        }
149    }
150}
151
152impl FromIterator<ProjectionExpr> for ProjectionExprs {
153    fn from_iter<T: IntoIterator<Item = ProjectionExpr>>(exprs: T) -> Self {
154        Self {
155            exprs: exprs.into_iter().collect(),
156        }
157    }
158}
159
160impl AsRef<[ProjectionExpr]> for ProjectionExprs {
161    fn as_ref(&self) -> &[ProjectionExpr] {
162        &self.exprs
163    }
164}
165
166impl ProjectionExprs {
167    /// Make a new [`ProjectionExprs`] from expressions iterator.
168    pub fn new(exprs: impl IntoIterator<Item = ProjectionExpr>) -> Self {
169        Self {
170            exprs: exprs.into_iter().collect(),
171        }
172    }
173
174    /// Make a new [`ProjectionExprs`] from expressions.
175    pub fn from_expressions(exprs: impl Into<Arc<[ProjectionExpr]>>) -> Self {
176        Self {
177            exprs: exprs.into(),
178        }
179    }
180
181    /// Creates a [`ProjectionExpr`] from a list of column indices.
182    ///
183    /// This is a convenience method for creating simple column-only projections, where each projection expression is a reference to a column
184    /// in the input schema.
185    ///
186    /// # Behavior
187    /// - Ordering: the output projection preserves the exact order of indices provided in the input slice
188    ///   For example, `[2, 0, 1]` will produce projections for columns 2, 0, then 1 in that order
189    /// - Duplicates: Duplicate indices are allowed and will create multiple projection expressions referencing the same source column
190    ///   For example, `[0, 0]` creates 2 separate projections both referencing column 0
191    ///
192    /// # Panics
193    /// Panics if any index in `indices` is out of bounds for the provided schema.
194    ///
195    /// # Example
196    ///
197    /// ```rust
198    /// use arrow::datatypes::{DataType, Field, Schema};
199    /// use datafusion_physical_expr::projection::ProjectionExprs;
200    /// use std::sync::Arc;
201    ///
202    /// // Create a schema with three columns
203    /// let schema = Arc::new(Schema::new(vec![
204    ///     Field::new("a", DataType::Int32, false),
205    ///     Field::new("b", DataType::Utf8, false),
206    ///     Field::new("c", DataType::Float64, false),
207    /// ]));
208    ///
209    /// // Project columns at indices 2 and 0 (c and a) - ordering is preserved
210    /// let projection = ProjectionExprs::from_indices(&[2, 0], &schema);
211    ///
212    /// // This creates: SELECT c@2 AS c, a@0 AS a
213    /// assert_eq!(projection.as_ref().len(), 2);
214    /// assert_eq!(projection.as_ref()[0].alias, "c");
215    /// assert_eq!(projection.as_ref()[1].alias, "a");
216    ///
217    /// // Duplicate indices are allowed
218    /// let projection_with_dups = ProjectionExprs::from_indices(&[0, 0, 1], &schema);
219    /// assert_eq!(projection_with_dups.as_ref().len(), 3);
220    /// assert_eq!(projection_with_dups.as_ref()[0].alias, "a");
221    /// assert_eq!(projection_with_dups.as_ref()[1].alias, "a"); // duplicate
222    /// assert_eq!(projection_with_dups.as_ref()[2].alias, "b");
223    /// ```
224    pub fn from_indices(indices: &[usize], schema: &Schema) -> Self {
225        let projection_exprs = indices.iter().map(|&i| {
226            let field = schema.field(i);
227            ProjectionExpr {
228                expr: Arc::new(Column::new(field.name(), i)),
229                alias: field.name().clone(),
230            }
231        });
232
233        Self::from_iter(projection_exprs)
234    }
235
236    /// Returns an iterator over the projection expressions
237    pub fn iter(&self) -> impl Iterator<Item = &ProjectionExpr> {
238        self.exprs.iter()
239    }
240
241    /// Creates a ProjectionMapping from this projection
242    pub fn projection_mapping(
243        &self,
244        input_schema: &SchemaRef,
245    ) -> Result<ProjectionMapping> {
246        ProjectionMapping::try_new(
247            self.exprs
248                .iter()
249                .map(|p| (Arc::clone(&p.expr), p.alias.clone())),
250            input_schema,
251        )
252    }
253
254    /// Iterate over a clone of the projection expressions.
255    pub fn expr_iter(&self) -> impl Iterator<Item = Arc<dyn PhysicalExpr>> + '_ {
256        self.exprs.iter().map(|e| Arc::clone(&e.expr))
257    }
258
259    /// Apply a fallible transformation to the [`PhysicalExpr`] of each projection.
260    ///
261    /// This method transforms the expression in each [`ProjectionExpr`] while preserving
262    /// the alias. This is useful for rewriting expressions, such as when adapting
263    /// expressions to a different schema.
264    ///
265    /// # Example
266    ///
267    /// ```rust
268    /// use std::sync::Arc;
269    /// use arrow::datatypes::{DataType, Field, Schema};
270    /// use datafusion_common::Result;
271    /// use datafusion_physical_expr::expressions::Column;
272    /// use datafusion_physical_expr::projection::ProjectionExprs;
273    /// use datafusion_physical_expr::PhysicalExpr;
274    ///
275    /// // Create a schema and projection
276    /// let schema = Arc::new(Schema::new(vec![
277    ///     Field::new("a", DataType::Int32, false),
278    ///     Field::new("b", DataType::Int32, false),
279    /// ]));
280    /// let projection = ProjectionExprs::from_indices(&[0, 1], &schema);
281    ///
282    /// // Transform each expression (this example just clones them)
283    /// let transformed = projection.try_map_exprs(|expr| Ok(expr))?;
284    /// assert_eq!(transformed.as_ref().len(), 2);
285    /// # Ok::<(), datafusion_common::DataFusionError>(())
286    /// ```
287    pub fn try_map_exprs<F>(self, mut f: F) -> Result<Self>
288    where
289        F: FnMut(Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>>,
290    {
291        let exprs = self
292            .exprs
293            .iter()
294            .cloned()
295            .map(|mut proj| {
296                proj.expr = f(proj.expr)?;
297                Ok(proj)
298            })
299            .collect::<Result<Arc<_>>>()?;
300        Ok(Self::from_expressions(exprs))
301    }
302
303    /// Apply another projection on top of this projection, returning the combined projection.
304    /// For example, if this projection is `SELECT c@2 AS x, b@1 AS y, a@0 as z` and the other projection is `SELECT x@0 + 1 AS c1, y@1 + z@2 as c2`,
305    /// we return a projection equivalent to `SELECT c@2 + 1 AS c1, b@1 + a@0 as c2`.
306    ///
307    /// # Example
308    ///
309    /// ```rust
310    /// use datafusion_common::{Result, ScalarValue};
311    /// use datafusion_expr::Operator;
312    /// use datafusion_physical_expr::expressions::{BinaryExpr, Column, Literal};
313    /// use datafusion_physical_expr::projection::{ProjectionExpr, ProjectionExprs};
314    /// use std::sync::Arc;
315    ///
316    /// fn main() -> Result<()> {
317    ///     // Example from the docstring:
318    ///     // Base projection: SELECT c@2 AS x, b@1 AS y, a@0 AS z
319    ///     let base = ProjectionExprs::new(vec![
320    ///         ProjectionExpr {
321    ///             expr: Arc::new(Column::new("c", 2)),
322    ///             alias: "x".to_string(),
323    ///         },
324    ///         ProjectionExpr {
325    ///             expr: Arc::new(Column::new("b", 1)),
326    ///             alias: "y".to_string(),
327    ///         },
328    ///         ProjectionExpr {
329    ///             expr: Arc::new(Column::new("a", 0)),
330    ///             alias: "z".to_string(),
331    ///         },
332    ///     ]);
333    ///
334    ///     // Top projection: SELECT x@0 + 1 AS c1, y@1 + z@2 AS c2
335    ///     let top = ProjectionExprs::new(vec![
336    ///         ProjectionExpr {
337    ///             expr: Arc::new(BinaryExpr::new(
338    ///                 Arc::new(Column::new("x", 0)),
339    ///                 Operator::Plus,
340    ///                 Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
341    ///             )),
342    ///             alias: "c1".to_string(),
343    ///         },
344    ///         ProjectionExpr {
345    ///             expr: Arc::new(BinaryExpr::new(
346    ///                 Arc::new(Column::new("y", 1)),
347    ///                 Operator::Plus,
348    ///                 Arc::new(Column::new("z", 2)),
349    ///             )),
350    ///             alias: "c2".to_string(),
351    ///         },
352    ///     ]);
353    ///
354    ///     // Expected result: SELECT c@2 + 1 AS c1, b@1 + a@0 AS c2
355    ///     let result = base.try_merge(&top)?;
356    ///
357    ///     assert_eq!(result.as_ref().len(), 2);
358    ///     assert_eq!(result.as_ref()[0].alias, "c1");
359    ///     assert_eq!(result.as_ref()[1].alias, "c2");
360    ///
361    ///     Ok(())
362    /// }
363    /// ```
364    ///
365    /// # Errors
366    /// This function returns an error if any expression in the `other` projection cannot be
367    /// applied on top of this projection.
368    pub fn try_merge(&self, other: &ProjectionExprs) -> Result<ProjectionExprs> {
369        let mut new_exprs = Vec::with_capacity(other.exprs.len());
370        for proj_expr in other.exprs.iter() {
371            new_exprs.push(ProjectionExpr {
372                expr: self.unproject_expr(&proj_expr.expr)?,
373                alias: proj_expr.alias.clone(),
374            });
375        }
376        Ok(ProjectionExprs::new(new_exprs))
377    }
378
379    /// Extract the column indices used in this projection.
380    /// For example, for a projection `SELECT a AS x, b + 1 AS y`, where `a` is at index 0 and `b` is at index 1,
381    /// this function would return `[0, 1]`.
382    /// Repeated indices are returned only once, and the order is ascending.
383    pub fn column_indices(&self) -> Vec<usize> {
384        self.exprs
385            .iter()
386            .flat_map(|e| collect_columns(&e.expr).into_iter().map(|col| col.index()))
387            .sorted_unstable()
388            .dedup()
389            .collect_vec()
390    }
391
392    /// Extract the ordered column indices for a column-only projection.
393    ///
394    /// This function assumes that all expressions in the projection are simple column references.
395    /// It returns the column indices in the order they appear in the projection.
396    ///
397    /// # Panics
398    ///
399    /// Panics if any expression in the projection is not a simple column reference. This includes:
400    /// - Computed expressions (e.g., `a + 1`, `CAST(a AS INT)`)
401    /// - Function calls (e.g., `UPPER(name)`, `SUM(amount)`)
402    /// - Literals (e.g., `42`, `'hello'`)
403    /// - Complex nested expressions (e.g., `CASE WHEN ... THEN ... END`)
404    ///
405    /// # Returns
406    ///
407    /// A vector of column indices in projection order. Unlike [`column_indices()`](Self::column_indices),
408    /// this function:
409    /// - Preserves the projection order (does not sort)
410    /// - Preserves duplicates (does not deduplicate)
411    ///
412    /// # Example
413    ///
414    /// For a projection `SELECT c, a, c` where `a` is at index 0 and `c` is at index 2,
415    /// this function would return `[2, 0, 2]`.
416    ///
417    /// Use [`column_indices()`](Self::column_indices) instead if the projection may contain
418    /// non-column expressions or if you need a deduplicated sorted list.
419    ///
420    /// # Panics
421    ///
422    /// Panics if any expression in the projection is not a simple column reference.
423    #[deprecated(
424        since = "52.0.0",
425        note = "Use column_indices() instead. This method will be removed in 58.0.0 or 6 months after 52.0.0 is released, whichever comes first."
426    )]
427    pub fn ordered_column_indices(&self) -> Vec<usize> {
428        self.exprs
429            .iter()
430            .map(|e| {
431                e.expr
432                    .downcast_ref::<Column>()
433                    .expect("Expected column reference in projection")
434                    .index()
435            })
436            .collect()
437    }
438
439    /// Project a schema according to this projection.
440    ///
441    /// For example, given a projection:
442    /// * `SELECT a AS x, b + 1 AS y`
443    /// * where `a` is at index 0
444    /// * `b` is at index 1
445    ///
446    /// If the input schema is `[a: Int32, b: Int32, c: Int32]`, the output
447    /// schema would be `[x: Int32, y: Int32]`.
448    ///
449    /// Note that [`Field`] metadata are preserved from the input schema.
450    pub fn project_schema(&self, input_schema: &Schema) -> Result<Schema> {
451        let fields: Result<Vec<Field>> = self
452            .exprs
453            .iter()
454            .map(|proj_expr| {
455                let metadata = proj_expr
456                    .expr
457                    .return_field(input_schema)?
458                    .metadata()
459                    .clone();
460
461                let field = Field::new(
462                    &proj_expr.alias,
463                    proj_expr.expr.data_type(input_schema)?,
464                    proj_expr.expr.nullable(input_schema)?,
465                )
466                .with_metadata(metadata);
467
468                Ok(field)
469            })
470            .collect();
471
472        Ok(Schema::new_with_metadata(
473            fields?,
474            input_schema.metadata().clone(),
475        ))
476    }
477
478    /// "unproject" an expression by applying this projection in reverse,
479    /// returning a new set of expressions that reference the original input
480    /// columns.
481    ///
482    /// For example, consider
483    /// * an expression `c1_c2 > 5`, and a schema `[c1, c2]`
484    /// * a projection `c1 + c2 as c1_c2`
485    ///
486    /// This method would rewrite the expression to `c1 + c2 > 5`
487    pub fn unproject_expr(
488        &self,
489        expr: &Arc<dyn PhysicalExpr>,
490    ) -> Result<Arc<dyn PhysicalExpr>> {
491        update_expr(expr, &self.exprs, true)?.ok_or_else(|| {
492            internal_datafusion_err!(
493                "Failed to unproject an expression {} with ProjectionExprs {}",
494                expr,
495                self.exprs.iter().map(|e| format!("{e}")).join(", ")
496            )
497        })
498    }
499
500    /// "project" an expression using these projection's expressions
501    ///
502    /// For example, consider
503    /// * an expression `c1 + c2 > 5`, and a schema `[c1, c2]`
504    /// * a projection `c1 + c2 as c1_c2`
505    ///
506    /// * This method would rewrite the expression to `c1_c2 > 5`
507    pub fn project_expr(
508        &self,
509        expr: &Arc<dyn PhysicalExpr>,
510    ) -> Result<Arc<dyn PhysicalExpr>> {
511        update_expr(expr, &self.exprs, false)?.ok_or_else(|| {
512            internal_datafusion_err!(
513                "Failed to project an expression {} with ProjectionExprs {}",
514                expr,
515                self.exprs.iter().map(|e| format!("{e}")).join(", ")
516            )
517        })
518    }
519
520    /// Create a new [`Projector`] from this projection and an input schema.
521    ///
522    /// A [`Projector`] can be used to apply this projection to record batches.
523    ///
524    /// # Errors
525    /// This function returns an error if the output schema cannot be constructed from the input schema
526    /// with the given projection expressions.
527    /// For example, if an expression only works with integer columns but the input schema has a string column at that index.
528    pub fn make_projector(&self, input_schema: &Schema) -> Result<Projector> {
529        let output_schema = Arc::new(self.project_schema(input_schema)?);
530        Ok(Projector {
531            projection: self.clone(),
532            output_schema,
533            expression_metrics: None,
534        })
535    }
536
537    /// Create a new [`Projector`] using field and schema metadata from
538    /// `projected_schema`.
539    ///
540    /// Field names, data types, and nullability are still derived from the physical
541    /// projection expressions and `input_schema`; only field and schema metadata are
542    /// taken from `projected_schema`.
543    ///
544    /// # Errors
545    ///
546    /// Returns an error if the projection cannot be applied to `input_schema`, or if
547    /// `projected_schema` has a different number of fields than the projection.
548    pub fn make_projector_with_schema_metadata(
549        &self,
550        input_schema: &Schema,
551        projected_schema: &Schema,
552    ) -> Result<Projector> {
553        let output_schema = self.project_schema(input_schema)?;
554        if output_schema.fields().len() != projected_schema.fields().len() {
555            return Err(internal_datafusion_err!(
556                "Projection has {} output fields but metadata schema has {} fields",
557                output_schema.fields().len(),
558                projected_schema.fields().len()
559            ));
560        }
561
562        let fields = output_schema
563            .fields()
564            .iter()
565            .zip(projected_schema.fields())
566            .map(|(field, projected_field)| {
567                Arc::new(
568                    field
569                        .as_ref()
570                        .clone()
571                        .with_metadata(projected_field.metadata().clone()),
572                )
573            })
574            .collect::<Vec<_>>();
575        let output_schema = Arc::new(Schema::new_with_metadata(
576            fields,
577            projected_schema.metadata().clone(),
578        ));
579
580        Ok(Projector {
581            projection: self.clone(),
582            output_schema,
583            expression_metrics: None,
584        })
585    }
586
587    pub fn create_expression_metrics(
588        &self,
589        metrics: &ExecutionPlanMetricsSet,
590        partition: usize,
591    ) -> ExpressionEvaluatorMetrics {
592        let labels: Vec<String> = self
593            .exprs
594            .iter()
595            .map(|proj_expr| {
596                let expr_sql = fmt_sql(proj_expr.expr.as_ref()).to_string();
597                if proj_expr.expr.to_string() == proj_expr.alias {
598                    expr_sql
599                } else {
600                    format!("{expr_sql} AS {}", proj_expr.alias)
601                }
602            })
603            .collect();
604        ExpressionEvaluatorMetrics::new(metrics, partition, labels)
605    }
606
607    /// Project statistics according to this projection.
608    /// For example, for a projection `SELECT a AS x, b + 1 AS y`, where `a` is at index 0 and `b` is at index 1,
609    /// if the input statistics has column statistics for columns `a`, `b`, and `c`, the output statistics would have column statistics for columns `x` and `y`.
610    ///
611    /// # Example
612    ///
613    /// ```rust
614    /// use arrow::datatypes::{DataType, Field, Schema};
615    /// use datafusion_common::stats::{ColumnStatistics, Precision, Statistics};
616    /// use datafusion_physical_expr::projection::ProjectionExprs;
617    /// use datafusion_common::Result;
618    /// use datafusion_common::ScalarValue;
619    /// use std::sync::Arc;
620    ///
621    /// fn main() -> Result<()> {
622    ///     // Input schema: a: Int32, b: Int32, c: Int32
623    ///     let input_schema = Arc::new(Schema::new(vec![
624    ///         Field::new("a", DataType::Int32, false),
625    ///         Field::new("b", DataType::Int32, false),
626    ///         Field::new("c", DataType::Int32, false),
627    ///     ]));
628    ///
629    ///     // Input statistics with column stats for a, b, c
630    ///     let input_stats = Statistics {
631    ///         num_rows: Precision::Exact(100),
632    ///         total_byte_size: Precision::Exact(1200),
633    ///         column_statistics: vec![
634    ///             // Column a stats
635    ///             ColumnStatistics::new_unknown()
636    ///                 .with_null_count(Precision::Exact(0))
637    ///                 .with_min_value(Precision::Exact(ScalarValue::Int32(Some(0))))
638    ///                 .with_max_value(Precision::Exact(ScalarValue::Int32(Some(100))))
639    ///                 .with_distinct_count(Precision::Exact(100)),
640    ///             // Column b stats
641    ///             ColumnStatistics::new_unknown()
642    ///                 .with_null_count(Precision::Exact(0))
643    ///                 .with_min_value(Precision::Exact(ScalarValue::Int32(Some(10))))
644    ///                 .with_max_value(Precision::Exact(ScalarValue::Int32(Some(60))))
645    ///                 .with_distinct_count(Precision::Exact(50)),
646    ///             // Column c stats
647    ///             ColumnStatistics::new_unknown()
648    ///                 .with_null_count(Precision::Exact(5))
649    ///                 .with_min_value(Precision::Exact(ScalarValue::Int32(Some(-10))))
650    ///                 .with_max_value(Precision::Exact(ScalarValue::Int32(Some(200))))
651    ///                 .with_distinct_count(Precision::Exact(25)),
652    ///         ],
653    ///     };
654    ///
655    ///     // Create a projection that selects columns c and a (indices 2 and 0)
656    ///     let projection = ProjectionExprs::from_indices(&[2, 0], &input_schema);
657    ///
658    ///     // Compute output schema
659    ///     let output_schema = projection.project_schema(&input_schema)?;
660    ///
661    ///     // Project the statistics
662    ///     let output_stats = projection.project_statistics(input_stats, &output_schema)?;
663    ///
664    ///     // The output should have 2 column statistics (for c and a, in that order)
665    ///     assert_eq!(output_stats.column_statistics.len(), 2);
666    ///
667    ///     // First column in output is c (was at index 2)
668    ///     assert_eq!(
669    ///         output_stats.column_statistics[0].min_value,
670    ///         Precision::Exact(ScalarValue::Int32(Some(-10)))
671    ///     );
672    ///     assert_eq!(
673    ///         output_stats.column_statistics[0].null_count,
674    ///         Precision::Exact(5)
675    ///     );
676    ///
677    ///     // Second column in output is a (was at index 0)
678    ///     assert_eq!(
679    ///         output_stats.column_statistics[1].min_value,
680    ///         Precision::Exact(ScalarValue::Int32(Some(0)))
681    ///     );
682    ///     assert_eq!(
683    ///         output_stats.column_statistics[1].distinct_count,
684    ///         Precision::Exact(100)
685    ///     );
686    ///
687    ///     // Total byte size is recalculated based on projected columns
688    ///     assert_eq!(
689    ///         output_stats.total_byte_size,
690    ///         Precision::Exact(800), // each Int32 column is 4 bytes * 100 rows * 2 columns
691    ///     );
692    ///
693    ///     // Number of rows remains the same
694    ///     assert_eq!(output_stats.num_rows, Precision::Exact(100));
695    ///
696    ///     Ok(())
697    /// }
698    /// ```
699    pub fn project_statistics(
700        &self,
701        stats: Statistics,
702        output_schema: &Schema,
703    ) -> Result<Statistics> {
704        self.project_statistics_impl(stats, None, output_schema)
705    }
706
707    /// Projects `stats` using `input_schema` to identify safe casts even when
708    /// the input statistics do not contain typed minimum or maximum values.
709    pub fn project_statistics_with_input_schema(
710        &self,
711        stats: Statistics,
712        input_schema: &Schema,
713        output_schema: &Schema,
714    ) -> Result<Statistics> {
715        self.project_statistics_impl(stats, Some(input_schema), output_schema)
716    }
717
718    fn project_statistics_impl(
719        &self,
720        mut stats: Statistics,
721        input_schema: Option<&Schema>,
722        output_schema: &Schema,
723    ) -> Result<Statistics> {
724        let mut column_statistics = Vec::with_capacity(self.exprs.len());
725
726        for proj_expr in self.exprs.iter() {
727            let expr = &proj_expr.expr;
728            let col_stats = if let Some(col) = expr.downcast_ref::<Column>() {
729                column_statistics_at(&stats.column_statistics, col.index())
730            } else if let Some(literal) = expr.downcast_ref::<Literal>() {
731                // Handle literal expressions (constants) by calculating proper statistics
732                let data_type = expr.data_type(output_schema)?;
733
734                if literal.value().is_null() {
735                    let null_count = match stats.num_rows {
736                        Precision::Exact(num_rows) => Precision::Exact(num_rows),
737                        _ => Precision::Absent,
738                    };
739
740                    ColumnStatistics {
741                        min_value: Precision::Exact(literal.value().clone()),
742                        max_value: Precision::Exact(literal.value().clone()),
743                        distinct_count: Precision::Exact(0),
744                        null_count,
745                        sum_value: Precision::Exact(literal.value().clone()),
746                        byte_size: Precision::Exact(0),
747                    }
748                } else {
749                    let value = literal.value();
750                    let distinct_count = match stats.num_rows {
751                        Precision::Exact(0) | Precision::Inexact(0) => stats.num_rows,
752                        Precision::Exact(_) => Precision::Exact(1),
753                        Precision::Inexact(_) | Precision::Absent => {
754                            Precision::Inexact(1)
755                        }
756                    };
757                    let null_count = Precision::Exact(0);
758
759                    let byte_size = if let Some(byte_width) = data_type.primitive_width()
760                    {
761                        stats.num_rows.multiply(&Precision::Exact(byte_width))
762                    } else {
763                        // Complex types depend on array encoding, so set to Absent
764                        Precision::Absent
765                    };
766
767                    let widened_sum = Precision::Exact(value.clone()).cast_to_sum_type();
768                    let sum_value = widened_sum
769                        .get_value()
770                        .and_then(|sum| {
771                            Precision::<ScalarValue>::from(stats.num_rows)
772                                .cast_to(&sum.data_type())
773                                .ok()
774                        })
775                        .map(|row_count| widened_sum.multiply(&row_count))
776                        .unwrap_or(Precision::Absent);
777
778                    ColumnStatistics {
779                        min_value: Precision::Exact(value.clone()),
780                        max_value: Precision::Exact(value.clone()),
781                        distinct_count,
782                        null_count,
783                        sum_value,
784                        byte_size,
785                    }
786                }
787            } else {
788                project_column_statistics_through_expr(
789                    expr.as_ref(),
790                    &stats.column_statistics,
791                    input_schema,
792                )
793            };
794            column_statistics.push(col_stats);
795        }
796        stats.calculate_total_byte_size(output_schema);
797        stats.column_statistics = column_statistics;
798        Ok(stats)
799    }
800
801    /// Returns the output position of `column` if this projection contains it.
802    ///
803    /// This only matches projection expressions that are exactly [`Column`] expressions.
804    /// Computed expressions, even if they reference `column`, do not match. The
805    /// comparison uses [`Column`] equality, so both the name and index must match.
806    /// If the same column appears more than once, this returns the first matching
807    /// position.
808    ///
809    /// # Example
810    ///
811    /// ```rust
812    /// use datafusion_common::ScalarValue;
813    /// use datafusion_physical_expr::expressions::{Column, Literal};
814    /// use datafusion_physical_expr::projection::{ProjectionExpr, ProjectionExprs};
815    /// use std::sync::Arc;
816    ///
817    /// let projection = ProjectionExprs::new([
818    ///     ProjectionExpr::new(Arc::new(Column::new("b", 1)), "b"),
819    ///     ProjectionExpr::new(
820    ///         Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
821    ///         "answer",
822    ///     ),
823    ///     ProjectionExpr::new(Arc::new(Column::new("a", 0)), "a"),
824    /// ]);
825    ///
826    /// assert_eq!(
827    ///     projection.projected_column_position(&Column::new("b", 1)),
828    ///     Some(0)
829    /// );
830    /// assert_eq!(
831    ///     projection.projected_column_position(&Column::new("a", 0)),
832    ///     Some(2)
833    /// );
834    ///
835    /// // The literal projection is not a Column expression.
836    /// assert_eq!(
837    ///     projection.projected_column_position(&Column::new("answer", 1)),
838    ///     None
839    /// );
840    ///
841    /// // Columns not present in the projection also return None.
842    /// assert_eq!(
843    ///     projection.projected_column_position(&Column::new("c", 2)),
844    ///     None
845    /// );
846    /// ```
847    pub fn projected_column_position(&self, column: &Column) -> Option<usize> {
848        self.iter().position(|expr| {
849            expr.expr
850                .downcast_ref::<Column>()
851                .is_some_and(|projected| projected == column)
852        })
853    }
854}
855
856/// Propagate column statistics through CAST projections. Other expressions
857/// return unknown — generalizing via [`PhysicalExpr::evaluate_bounds`] is
858/// unsafe for aggregate folding since many impls (e.g. `sin`) return a fixed
859/// envelope rather than tight bounds on the actual inputs.
860fn project_column_statistics_through_expr(
861    expr: &dyn PhysicalExpr,
862    column_stats: &[ColumnStatistics],
863    input_schema: Option<&Schema>,
864) -> ColumnStatistics {
865    if let Some(col) = expr.downcast_ref::<Column>() {
866        return column_statistics_at(column_stats, col.index());
867    }
868    let Some(cast_expr) = expr.downcast_ref::<CastExpr>() else {
869        return ColumnStatistics::new_unknown();
870    };
871    let inner_stats = project_column_statistics_through_expr(
872        cast_expr.expr.as_ref(),
873        column_stats,
874        input_schema,
875    );
876    let target_type = cast_expr.cast_type();
877    let schema_source_type =
878        input_schema.and_then(|schema| cast_expr.expr.data_type(schema).ok());
879
880    // A cast whose source values are already of the target `DataType` never
881    // changes any value -- see `cast_array_by_name`'s same-type fast path in
882    // `ColumnarValue::cast_to`. In that case every statistic, not just
883    // min/max, carries over unchanged (this is what a cast that only
884    // re-stamps a column's nullability, as `UnionExec`/`InterleaveExec`
885    // insert, looks like here).
886    let already_target_type = schema_source_type
887        .as_ref()
888        .is_some_and(|source_type| source_type == target_type)
889        || matches!(
890            (inner_stats.min_value.get_value(), inner_stats.max_value.get_value()),
891            (Some(min), Some(max))
892                if min.data_type() == *target_type && max.data_type() == *target_type
893        );
894    if already_target_type {
895        return inner_stats;
896    }
897
898    let min_value = inner_stats
899        .min_value
900        .cast_to(target_type)
901        .unwrap_or(Precision::Absent);
902    let max_value = inner_stats
903        .max_value
904        .cast_to(target_type)
905        .unwrap_or(Precision::Absent);
906    let source_type = schema_source_type.or_else(|| {
907        inner_stats
908            .min_value
909            .get_value()
910            .or_else(|| inner_stats.max_value.get_value())
911            .map(ScalarValue::data_type)
912    });
913    // Copy extrema only for casts that preserve order and cannot discard values
914    // or fail within the input domain. Copying string endpoints into a numeric
915    // domain, for example, does not bound the converted column. Merely casting
916    // a failing endpoint to NULL also cannot establish the remaining extrema.
917    let preserves_values = source_type.is_some_and(|source_type| {
918        CastExpr::check_bigger_cast(target_type, &source_type)
919            || is_within_extrema(
920                &inner_stats.min_value,
921                &inner_stats.max_value,
922                &min_value,
923                &max_value,
924            )
925    });
926    if !preserves_values {
927        return ColumnStatistics::new_unknown();
928    }
929
930    ColumnStatistics {
931        min_value,
932        max_value,
933        null_count: inner_stats.null_count,
934        distinct_count: inner_stats.distinct_count,
935        sum_value: Precision::Absent,
936        byte_size: Precision::Absent,
937    }
938}
939
940/// Whether an integer cast preserves every value between the source extrema.
941/// The converted extrema must come from casting the corresponding source bounds.
942/// Exact, non-null integer bounds that both cast successfully prove the entire
943/// range fits in the target type. For example, Int64 [-128, 127] fits in Int8,
944/// whereas [-129, 127] does not. Inexact bounds cannot establish exact extrema.
945fn is_within_extrema(
946    lower: &Precision<ScalarValue>,
947    upper: &Precision<ScalarValue>,
948    min: &Precision<ScalarValue>,
949    max: &Precision<ScalarValue>,
950) -> bool {
951    [lower, upper, min, max].into_iter().all(|bound| {
952        matches!(bound, Precision::Exact(value)
953            if value.data_type().is_integer() && !value.is_null())
954    })
955}
956
957fn column_statistics_at(
958    column_stats: &[ColumnStatistics],
959    index: usize,
960) -> ColumnStatistics {
961    column_stats
962        .get(index)
963        .cloned()
964        .unwrap_or_else(ColumnStatistics::new_unknown)
965}
966
967impl<'a> IntoIterator for &'a ProjectionExprs {
968    type Item = &'a ProjectionExpr;
969    type IntoIter = std::slice::Iter<'a, ProjectionExpr>;
970
971    fn into_iter(self) -> Self::IntoIter {
972        self.exprs.iter()
973    }
974}
975
976/// Applies a projection to record batches.
977///
978/// A [`Projector`] uses a set of projection expressions to transform
979/// and a pre-computed output schema to project record batches accordingly.
980///
981/// The main reason to use a `Projector` is to avoid repeatedly computing
982/// the output schema for each batch, which can be costly if the projection
983/// expressions are complex.
984#[derive(Clone, Debug)]
985pub struct Projector {
986    projection: ProjectionExprs,
987    output_schema: SchemaRef,
988    /// If `Some`, metrics will be tracked for projection evaluation.
989    expression_metrics: Option<ExpressionEvaluatorMetrics>,
990}
991
992impl Projector {
993    /// Construct the projector with metrics. After execution, related metrics will
994    /// be tracked inside `ExecutionPlanMetricsSet`
995    ///
996    /// See [`ExpressionEvaluatorMetrics`] for details.
997    pub fn with_metrics(
998        &self,
999        metrics: &ExecutionPlanMetricsSet,
1000        partition: usize,
1001    ) -> Self {
1002        let expr_metrics = self
1003            .projection
1004            .create_expression_metrics(metrics, partition);
1005        Self {
1006            expression_metrics: Some(expr_metrics),
1007            projection: self.projection.clone(),
1008            output_schema: Arc::clone(&self.output_schema),
1009        }
1010    }
1011
1012    /// Project a record batch according to this projector's expressions.
1013    ///
1014    /// # Errors
1015    /// This function returns an error if any expression evaluation fails
1016    /// or if the output schema of the resulting record batch does not match
1017    /// the pre-computed output schema of the projector.
1018    pub fn project_batch(&self, batch: &RecordBatch) -> Result<RecordBatch> {
1019        let arrays = evaluate_expressions_to_arrays_with_metrics(
1020            self.projection.exprs.iter().map(|p| &p.expr),
1021            batch,
1022            self.expression_metrics.as_ref(),
1023        )?;
1024
1025        if arrays.is_empty() {
1026            let options =
1027                RecordBatchOptions::new().with_row_count(Some(batch.num_rows()));
1028            RecordBatch::try_new_with_options(
1029                Arc::clone(&self.output_schema),
1030                arrays,
1031                &options,
1032            )
1033            .map_err(Into::into)
1034        } else {
1035            RecordBatch::try_new(Arc::clone(&self.output_schema), arrays)
1036                .map_err(Into::into)
1037        }
1038    }
1039
1040    pub fn output_schema(&self) -> &SchemaRef {
1041        &self.output_schema
1042    }
1043
1044    pub fn projection(&self) -> &ProjectionExprs {
1045        &self.projection
1046    }
1047}
1048
1049/// Describes an immutable reference counted projection.
1050///
1051/// This structure represents projecting a set of columns by index.
1052/// [`Arc`] is used to make it cheap to clone.
1053pub type ProjectionRef = Arc<[usize]>;
1054
1055/// Combine two projections.
1056///
1057/// If `p1` is [`None`] then there are no changes.
1058/// Otherwise, if passed `p2` is not [`None`] then it is remapped
1059/// according to the `p1`. Otherwise, there are no changes.
1060///
1061/// # Example
1062///
1063/// If stored projection is [0, 2] and we call `apply_projection([0, 2, 3])`,
1064/// then the resulting projection will be [0, 3].
1065///
1066/// # Error
1067///
1068/// Returns an internal error if `p1` contains index that is greater than `p2` len.
1069///
1070pub fn combine_projections(
1071    p1: Option<&ProjectionRef>,
1072    p2: Option<&ProjectionRef>,
1073) -> Result<Option<ProjectionRef>> {
1074    let Some(p1) = p1 else {
1075        return Ok(None);
1076    };
1077    let Some(p2) = p2 else {
1078        return Ok(Some(Arc::clone(p1)));
1079    };
1080
1081    Ok(Some(
1082        p1.iter()
1083            .map(|i| {
1084                let idx = *i;
1085                assert_or_internal_err!(
1086                    idx < p2.len(),
1087                    "unable to apply projection: index {} is greater than new projection len {}",
1088                    idx,
1089                    p2.len(),
1090                );
1091                Ok(p2[*i])
1092            })
1093            .collect::<Result<Arc<[usize]>>>()?,
1094    ))
1095}
1096
1097/// The function projects / unprojects an expression with respect to set of
1098/// projection expressions.
1099///
1100/// See also [`ProjectionExprs::unproject_expr`] and [`ProjectionExprs::project_expr`]
1101///
1102/// 1) When `unproject` is `true`:
1103///
1104///    Rewrites an expression with respect to the projection expressions,
1105///    effectively "unprojecting" it to reference the original input columns.
1106///
1107///    For example, given
1108///    * the expressions `a@1 + b@2` and `c@0`
1109///    * and projection expressions `c@2, a@0, b@1`
1110///
1111///    Then
1112///    * `a@1 + b@2` becomes `a@0 + b@1`
1113///    * `c@0` becomes `c@2`
1114///
1115/// 2) When `unproject` is `false`:
1116///
1117///    Rewrites the expression to reference the projected expressions,
1118///    effectively "projecting" it. The resulting expression will reference the
1119///    indices as they appear in the projection.
1120///
1121///    If the expression cannot be rewritten after the projection, it returns
1122///    `None`.
1123///
1124///    For example, given
1125///    * the expressions `c@0`, `a@1` and `b@2`
1126///    * the projection `a@1 as a, c@0 as c_new`,
1127///
1128///    Then
1129///    * `c@0` becomes `c_new@1`
1130///    * `a@1` becomes `a@0`
1131///    * `b@2` results in `None` since the projection does not include `b`.
1132///
1133/// # Errors
1134/// This function returns an error if `unproject` is `true` and if any expression references
1135/// an index that is out of bounds for `projected_exprs`.
1136/// For example:
1137///
1138/// - `expr` is `a@3`
1139/// - `projected_exprs` is \[`a@0`, `b@1`\]
1140///
1141/// In this case, `a@3` references index 3, which is out of bounds for `projected_exprs` (which has length 2).
1142pub fn update_expr(
1143    expr: &Arc<dyn PhysicalExpr>,
1144    projected_exprs: &[ProjectionExpr],
1145    unproject: bool,
1146) -> Result<Option<Arc<dyn PhysicalExpr>>> {
1147    #[derive(Debug, PartialEq)]
1148    enum RewriteState {
1149        /// The expression is unchanged.
1150        Unchanged,
1151        /// Some part of the expression has been rewritten
1152        RewrittenValid,
1153        /// Some part of the expression has been rewritten, but some column
1154        /// references could not be.
1155        RewrittenInvalid,
1156    }
1157
1158    let mut state = RewriteState::Unchanged;
1159
1160    let new_expr = Arc::clone(expr)
1161        .transform_up(|expr| {
1162            if state == RewriteState::RewrittenInvalid {
1163                return Ok(Transformed::no(expr));
1164            }
1165
1166            let Some(column) = expr.downcast_ref::<Column>() else {
1167                return Ok(Transformed::no(expr));
1168            };
1169            if unproject {
1170                let projected_expr = projected_exprs.get(column.index()).ok_or_else(|| {
1171                    internal_datafusion_err!(
1172                        "Column index {} out of bounds for projected expressions of length {}",
1173                        column.index(),
1174                        projected_exprs.len()
1175                    )
1176                })?;
1177                // Skip rebuilding the parent if substituting with an equal
1178                // Column (e.g. pass-through `c0@0` -> `c0@0` during chained
1179                // projection collapse). Without this, every CASE/BinaryExpr
1180                // containing such a Column is reconstructed unnecessarily.
1181                if let Some(projected_col) =
1182                    projected_expr.expr.downcast_ref::<Column>()
1183                    && projected_col == column
1184                {
1185                    return Ok(Transformed::no(expr));
1186                }
1187                state = RewriteState::RewrittenValid;
1188                Ok(Transformed::yes(Arc::clone(&projected_expr.expr)))
1189            } else {
1190                // default to invalid, in case we can't find the relevant column
1191                state = RewriteState::RewrittenInvalid;
1192                // Determine how to update `column` to accommodate `projected_exprs`
1193                projected_exprs
1194                    .iter()
1195                    .enumerate()
1196                    .find_map(|(index, proj_expr)| {
1197                        proj_expr.expr.downcast_ref::<Column>().and_then(
1198                            |projected_column| {
1199                                (column.name().eq(projected_column.name())
1200                                    && column.index() == projected_column.index())
1201                                .then(|| {
1202                                    state = RewriteState::RewrittenValid;
1203                                    Arc::new(Column::new(&proj_expr.alias, index)) as _
1204                                })
1205                            },
1206                        )
1207                    })
1208                    .map_or_else(
1209                        || Ok(Transformed::no(expr)),
1210                        |c| Ok(Transformed::yes(c)),
1211                    )
1212            }
1213        })
1214        .data()?;
1215
1216    match state {
1217        RewriteState::RewrittenInvalid => Ok(None),
1218        // Both Unchanged and RewrittenValid are valid:
1219        // - Unchanged means no columns to rewrite (e.g., literals)
1220        // - RewrittenValid means columns were successfully rewritten
1221        RewriteState::Unchanged | RewriteState::RewrittenValid => Ok(Some(new_expr)),
1222    }
1223}
1224
1225/// Stores target expressions, along with their indices, that associate with a
1226/// source expression in a projection mapping.
1227#[derive(Clone, Debug, Default)]
1228pub struct ProjectionTargets {
1229    /// A non-empty vector of pairs of target expressions and their indices.
1230    /// Consider using a special non-empty collection type in the future (e.g.
1231    /// if Rust provides one in the standard library).
1232    exprs_indices: Vec<(Arc<dyn PhysicalExpr>, usize)>,
1233}
1234
1235impl ProjectionTargets {
1236    /// Returns the first target expression and its index.
1237    pub fn first(&self) -> &(Arc<dyn PhysicalExpr>, usize) {
1238        // Since the vector is non-empty, we can safely unwrap:
1239        self.exprs_indices.first().unwrap()
1240    }
1241
1242    /// Adds a target expression and its index to the list of targets.
1243    pub fn push(&mut self, target: (Arc<dyn PhysicalExpr>, usize)) {
1244        self.exprs_indices.push(target);
1245    }
1246}
1247
1248impl Deref for ProjectionTargets {
1249    type Target = [(Arc<dyn PhysicalExpr>, usize)];
1250
1251    fn deref(&self) -> &Self::Target {
1252        &self.exprs_indices
1253    }
1254}
1255
1256impl From<Vec<(Arc<dyn PhysicalExpr>, usize)>> for ProjectionTargets {
1257    fn from(exprs_indices: Vec<(Arc<dyn PhysicalExpr>, usize)>) -> Self {
1258        Self { exprs_indices }
1259    }
1260}
1261
1262/// Stores the mapping between source expressions and target expressions for a
1263/// projection.
1264#[derive(Clone, Debug)]
1265pub struct ProjectionMapping {
1266    /// Mapping between source expressions and target expressions.
1267    /// Vector indices correspond to the indices after projection.
1268    map: IndexMap<Arc<dyn PhysicalExpr>, ProjectionTargets>,
1269}
1270
1271impl ProjectionMapping {
1272    /// Constructs the mapping between a projection's input and output
1273    /// expressions.
1274    ///
1275    /// For example, given the input projection expressions (`a + b`, `c + d`)
1276    /// and an output schema with two columns `"c + d"` and `"a + b"`, the
1277    /// projection mapping would be:
1278    ///
1279    /// ```text
1280    ///  [0]: (c + d, [(col("c + d"), 0)])
1281    ///  [1]: (a + b, [(col("a + b"), 1)])
1282    /// ```
1283    ///
1284    /// where `col("c + d")` means the column named `"c + d"`.
1285    pub fn try_new(
1286        expr: impl IntoIterator<Item = (Arc<dyn PhysicalExpr>, String)>,
1287        input_schema: &SchemaRef,
1288    ) -> Result<Self> {
1289        // Construct a map from the input expressions to the output expression of the projection:
1290        let exprs = expr.into_iter();
1291        let mut map =
1292            IndexMap::<_, ProjectionTargets>::with_capacity(exprs.size_hint().0);
1293        for (expr_idx, (expr, name)) in exprs.enumerate() {
1294            let target_expr = Arc::new(Column::new(&name, expr_idx)) as _;
1295            let source_expr = expr.transform_down(|e| match e.downcast_ref::<Column>() {
1296                Some(col) => {
1297                    // Sometimes, an expression and its name in the input_schema
1298                    // doesn't match. This can cause problems, so we make sure
1299                    // that the expression name matches with the name in `input_schema`.
1300                    // Conceptually, `source_expr` and `expression` should be the same.
1301                    let idx = col.index();
1302                    let matching_field = input_schema.field(idx);
1303                    let matching_name = matching_field.name();
1304                    assert_or_internal_err!(
1305                        col.name() == matching_name,
1306                        "Input field name {matching_name} does not match with the projection expression {}",
1307                        col.name()
1308                    );
1309                    let matching_column = Column::new(matching_name, idx);
1310                    Ok(Transformed::yes(Arc::new(matching_column)))
1311                }
1312                None => Ok(Transformed::no(e)),
1313            })
1314            .data()?;
1315            map.entry(Arc::clone(&source_expr))
1316                .or_default()
1317                .push((Arc::clone(&target_expr), expr_idx));
1318
1319            // For struct-producing functions (e.g. named_struct), decompose
1320            // into field-level mapping entries so that orderings propagate
1321            // through struct projections. For example, if the projection has
1322            // `named_struct('ticker', p.ticker, ...) AS details`, this adds:
1323            //   p.ticker → get_field(col("details"), "ticker")
1324            // enabling the optimizer to know that sorting by
1325            // `details.ticker` is equivalent to sorting by `p.ticker`.
1326            if let Some(func_expr) = source_expr.downcast_ref::<ScalarFunctionExpr>() {
1327                let literal_args: Vec<Option<ScalarValue>> = func_expr
1328                    .args()
1329                    .iter()
1330                    .map(|arg| arg.downcast_ref::<Literal>().map(|l| l.value().clone()))
1331                    .collect();
1332
1333                if let Some(field_mapping) =
1334                    func_expr.fun().struct_field_mapping(&literal_args)
1335                    && let DataType::Struct(struct_fields) = func_expr.return_type()
1336                {
1337                    for (accessor_args, source_arg_idx) in &field_mapping.fields {
1338                        let value_expr = Arc::clone(&func_expr.args()[*source_arg_idx]);
1339
1340                        // Build accessor args: [target_col, ...field_name_literals]
1341                        let mut accessor_fn_args: Vec<Arc<dyn PhysicalExpr>> =
1342                            vec![Arc::clone(&target_expr)];
1343                        accessor_fn_args.extend(accessor_args.iter().map(|sv| {
1344                            Arc::new(Literal::new(sv.clone())) as Arc<dyn PhysicalExpr>
1345                        }));
1346
1347                        // Look up the field's return type from the struct schema
1348                        let return_field = accessor_args
1349                            .first()
1350                            .and_then(|sv| sv.try_as_str().flatten())
1351                            .and_then(|field_name| {
1352                                struct_fields
1353                                    .iter()
1354                                    .find(|f| f.name() == field_name)
1355                                    .cloned()
1356                            });
1357
1358                        if let Some(return_field) = return_field {
1359                            let field_access_expr = Arc::new(ScalarFunctionExpr::new(
1360                                field_mapping.field_accessor.name(),
1361                                Arc::clone(&field_mapping.field_accessor),
1362                                accessor_fn_args,
1363                                return_field,
1364                                Arc::new(func_expr.config_options().clone()),
1365                            ))
1366                                as Arc<dyn PhysicalExpr>;
1367
1368                            map.entry(value_expr)
1369                                .or_default()
1370                                .push((field_access_expr, expr_idx));
1371                        }
1372                    }
1373                }
1374            }
1375        }
1376        Ok(Self { map })
1377    }
1378
1379    /// Constructs a subset mapping using the provided indices.
1380    ///
1381    /// This is used when the output is a subset of the input without any
1382    /// other transformations. The indices are for columns in the schema.
1383    pub fn from_indices(indices: &[usize], schema: &SchemaRef) -> Result<Self> {
1384        let projection_exprs = indices.iter().map(|index| {
1385            let field = schema.field(*index);
1386            let column = Arc::new(Column::new(field.name(), *index));
1387            (column as _, field.name().clone())
1388        });
1389        ProjectionMapping::try_new(projection_exprs, schema)
1390    }
1391}
1392
1393impl Deref for ProjectionMapping {
1394    type Target = IndexMap<Arc<dyn PhysicalExpr>, ProjectionTargets>;
1395
1396    fn deref(&self) -> &Self::Target {
1397        &self.map
1398    }
1399}
1400
1401impl FromIterator<(Arc<dyn PhysicalExpr>, ProjectionTargets)> for ProjectionMapping {
1402    fn from_iter<T: IntoIterator<Item = (Arc<dyn PhysicalExpr>, ProjectionTargets)>>(
1403        iter: T,
1404    ) -> Self {
1405        Self {
1406            map: IndexMap::from_iter(iter),
1407        }
1408    }
1409}
1410
1411/// Projects a slice of [LexOrdering]s onto the given schema.
1412///
1413/// This is a convenience wrapper that applies [project_ordering] to each
1414/// input ordering and collects the successful projections:
1415/// - For each input ordering, the result of [project_ordering] is appended to
1416///   the output if it is `Some(...)`.
1417/// - Order is preserved and no deduplication is attempted.
1418/// - If none of the input orderings can be projected, an empty `Vec` is
1419///   returned.
1420///
1421/// See [project_ordering] for the semantics of projecting a single
1422/// [LexOrdering].
1423pub fn project_orderings(
1424    orderings: &[LexOrdering],
1425    schema: &SchemaRef,
1426) -> Vec<LexOrdering> {
1427    let mut projected_orderings = Vec::with_capacity(orderings.len());
1428
1429    for ordering in orderings {
1430        projected_orderings.extend(project_ordering(ordering, schema));
1431    }
1432
1433    projected_orderings
1434}
1435
1436/// Projects a single [LexOrdering] onto the given schema.
1437///
1438/// This function attempts to rewrite every [PhysicalSortExpr] in the provided
1439/// [LexOrdering] so that any [Column] expressions point at the correct field
1440/// indices in `schema`.
1441///
1442/// Key details:
1443/// - Columns are matched by name, not by index. The index of each matched
1444///   column is looked up with [Schema::column_with_name](arrow::datatypes::Schema::column_with_name) and a new
1445///   [Column] with the correct [index](Column::index) is substituted.
1446/// - If an expression references a column name that does not exist in
1447///   `schema`, projection of the current ordering stops and only the already
1448///   rewritten prefix is kept. This models the fact that a lexicographical
1449///   ordering remains valid for any leading prefix whose expressions are
1450///   present in the projected schema.
1451/// - If no expressions can be projected (i.e. the first one is missing), the
1452///   function returns `None`.
1453///
1454/// Return value:
1455/// - `Some(LexOrdering)` if at least one sort expression could be projected.
1456///   The returned ordering may be a strict prefix of the input ordering.
1457/// - `None` if no part of the ordering can be projected onto `schema`.
1458///
1459/// Example
1460///
1461/// Suppose we have an input ordering `[col("a@0"), col("b@1")]` but the projected
1462/// schema only contains b and not a. The result will be `Some([col("a@0")])`. In other
1463/// words, the column reference is reindexed to match the projected schema.
1464/// If neither a nor b is present, the result will be None.
1465pub fn project_ordering(
1466    ordering: &LexOrdering,
1467    schema: &SchemaRef,
1468) -> Option<LexOrdering> {
1469    let mut projected_exprs = Vec::with_capacity(ordering.len());
1470    for PhysicalSortExpr { expr, options } in ordering.iter() {
1471        let transformed = Arc::clone(expr).transform_up(|expr| {
1472            let Some(col) = expr.downcast_ref::<Column>() else {
1473                return Ok(Transformed::no(expr));
1474            };
1475
1476            let name = col.name();
1477            if let Some((idx, _)) = schema.column_with_name(name) {
1478                // Compute the new column expression (with correct index) after projection:
1479                Ok(Transformed::yes(Arc::new(Column::new(name, idx))))
1480            } else {
1481                // Cannot find expression in the projected_schema,
1482                // signal this using an Err result
1483                plan_err!("")
1484            }
1485        });
1486
1487        match transformed {
1488            Ok(transformed) => {
1489                projected_exprs.push(PhysicalSortExpr::new(transformed.data, *options));
1490            }
1491            Err(_) => {
1492                // Err result indicates an expression could not be found in the
1493                // projected_schema, stop iterating since rest of the orderings are violated
1494                break;
1495            }
1496        }
1497    }
1498
1499    LexOrdering::new(projected_exprs)
1500}
1501
1502#[cfg(test)]
1503pub(crate) mod tests {
1504    use std::collections::HashMap;
1505
1506    use super::*;
1507    use crate::equivalence::{EquivalenceProperties, convert_to_orderings};
1508    use crate::expressions::{BinaryExpr, CastExpr, col};
1509    use crate::utils::tests::TestScalarUDF;
1510    use crate::{PhysicalExprRef, ScalarFunctionExpr};
1511
1512    use arrow::compute::SortOptions;
1513    use arrow::datatypes::{DataType, TimeUnit};
1514    use datafusion_common::config::ConfigOptions;
1515    use datafusion_expr::{Operator, ScalarUDF};
1516    use insta::assert_snapshot;
1517
1518    pub(crate) fn output_schema(
1519        mapping: &ProjectionMapping,
1520        input_schema: &Arc<Schema>,
1521    ) -> Result<SchemaRef> {
1522        // Calculate output schema:
1523        let mut fields = vec![];
1524        for (source, targets) in mapping.iter() {
1525            let data_type = source.data_type(input_schema)?;
1526            let nullable = source.nullable(input_schema)?;
1527            for (target, _) in targets.iter() {
1528                // Skip non-Column targets (e.g. struct field decomposition
1529                // entries which are ScalarFunctionExpr targets).
1530                let Some(column) = target.downcast_ref::<Column>() else {
1531                    continue;
1532                };
1533                fields.push(Field::new(column.name(), data_type.clone(), nullable));
1534            }
1535        }
1536
1537        let output_schema = Arc::new(Schema::new_with_metadata(
1538            fields,
1539            input_schema.metadata().clone(),
1540        ));
1541
1542        Ok(output_schema)
1543    }
1544
1545    #[test]
1546    fn project_orderings() -> Result<()> {
1547        let schema = Arc::new(Schema::new(vec![
1548            Field::new("a", DataType::Int32, true),
1549            Field::new("b", DataType::Int32, true),
1550            Field::new("c", DataType::Int32, true),
1551            Field::new("d", DataType::Int32, true),
1552            Field::new("e", DataType::Int32, true),
1553            Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),
1554        ]));
1555        let col_a = &col("a", &schema)?;
1556        let col_b = &col("b", &schema)?;
1557        let col_c = &col("c", &schema)?;
1558        let col_d = &col("d", &schema)?;
1559        let col_e = &col("e", &schema)?;
1560        let col_ts = &col("ts", &schema)?;
1561        let a_plus_b = Arc::new(BinaryExpr::new(
1562            Arc::clone(col_a),
1563            Operator::Plus,
1564            Arc::clone(col_b),
1565        )) as Arc<dyn PhysicalExpr>;
1566        let b_plus_d = Arc::new(BinaryExpr::new(
1567            Arc::clone(col_b),
1568            Operator::Plus,
1569            Arc::clone(col_d),
1570        )) as Arc<dyn PhysicalExpr>;
1571        let b_plus_e = Arc::new(BinaryExpr::new(
1572            Arc::clone(col_b),
1573            Operator::Plus,
1574            Arc::clone(col_e),
1575        )) as Arc<dyn PhysicalExpr>;
1576        let c_plus_d = Arc::new(BinaryExpr::new(
1577            Arc::clone(col_c),
1578            Operator::Plus,
1579            Arc::clone(col_d),
1580        )) as Arc<dyn PhysicalExpr>;
1581
1582        let option_asc = SortOptions {
1583            descending: false,
1584            nulls_first: false,
1585        };
1586        let option_desc = SortOptions {
1587            descending: true,
1588            nulls_first: true,
1589        };
1590
1591        let test_cases = vec![
1592            // ---------- TEST CASE 1 ------------
1593            (
1594                // orderings
1595                vec![
1596                    // [b ASC]
1597                    vec![(col_b, option_asc)],
1598                ],
1599                // projection exprs
1600                vec![(col_b, "b_new".to_string()), (col_a, "a_new".to_string())],
1601                // expected
1602                vec![
1603                    // [b_new ASC]
1604                    vec![("b_new", option_asc)],
1605                ],
1606            ),
1607            // ---------- TEST CASE 2 ------------
1608            (
1609                // orderings
1610                vec![
1611                    // empty ordering
1612                ],
1613                // projection exprs
1614                vec![(col_c, "c_new".to_string()), (col_b, "b_new".to_string())],
1615                // expected
1616                vec![
1617                    // no ordering at the output
1618                ],
1619            ),
1620            // ---------- TEST CASE 3 ------------
1621            (
1622                // orderings
1623                vec![
1624                    // [ts ASC]
1625                    vec![(col_ts, option_asc)],
1626                ],
1627                // projection exprs
1628                vec![
1629                    (col_b, "b_new".to_string()),
1630                    (col_a, "a_new".to_string()),
1631                    (col_ts, "ts_new".to_string()),
1632                ],
1633                // expected
1634                vec![
1635                    // [ts_new ASC]
1636                    vec![("ts_new", option_asc)],
1637                ],
1638            ),
1639            // ---------- TEST CASE 4 ------------
1640            (
1641                // orderings
1642                vec![
1643                    // [a ASC, ts ASC]
1644                    vec![(col_a, option_asc), (col_ts, option_asc)],
1645                    // [b ASC, ts ASC]
1646                    vec![(col_b, option_asc), (col_ts, option_asc)],
1647                ],
1648                // projection exprs
1649                vec![
1650                    (col_b, "b_new".to_string()),
1651                    (col_a, "a_new".to_string()),
1652                    (col_ts, "ts_new".to_string()),
1653                ],
1654                // expected
1655                vec![
1656                    // [a_new ASC, ts_new ASC]
1657                    vec![("a_new", option_asc), ("ts_new", option_asc)],
1658                    // [b_new ASC, ts_new ASC]
1659                    vec![("b_new", option_asc), ("ts_new", option_asc)],
1660                ],
1661            ),
1662            // ---------- TEST CASE 5 ------------
1663            (
1664                // orderings
1665                vec![
1666                    // [a + b ASC]
1667                    vec![(&a_plus_b, option_asc)],
1668                ],
1669                // projection exprs
1670                vec![
1671                    (col_b, "b_new".to_string()),
1672                    (col_a, "a_new".to_string()),
1673                    (&a_plus_b, "a+b".to_string()),
1674                ],
1675                // expected
1676                vec![
1677                    // [a + b ASC]
1678                    vec![("a+b", option_asc)],
1679                ],
1680            ),
1681            // ---------- TEST CASE 6 ------------
1682            (
1683                // orderings
1684                vec![
1685                    // [a + b ASC, c ASC]
1686                    vec![(&a_plus_b, option_asc), (col_c, option_asc)],
1687                ],
1688                // projection exprs
1689                vec![
1690                    (col_b, "b_new".to_string()),
1691                    (col_a, "a_new".to_string()),
1692                    (col_c, "c_new".to_string()),
1693                    (&a_plus_b, "a+b".to_string()),
1694                ],
1695                // expected
1696                vec![
1697                    // [a + b ASC, c_new ASC]
1698                    vec![("a+b", option_asc), ("c_new", option_asc)],
1699                ],
1700            ),
1701            // ------- TEST CASE 7 ----------
1702            (
1703                vec![
1704                    // [a ASC, b ASC, c ASC]
1705                    vec![(col_a, option_asc), (col_b, option_asc)],
1706                    // [a ASC, d ASC]
1707                    vec![(col_a, option_asc), (col_d, option_asc)],
1708                ],
1709                // b as b_new, a as a_new, d as d_new b+d
1710                vec![
1711                    (col_b, "b_new".to_string()),
1712                    (col_a, "a_new".to_string()),
1713                    (col_d, "d_new".to_string()),
1714                    (&b_plus_d, "b+d".to_string()),
1715                ],
1716                // expected
1717                vec![
1718                    // [a_new ASC, b_new ASC]
1719                    vec![("a_new", option_asc), ("b_new", option_asc)],
1720                    // [a_new ASC, d_new ASC]
1721                    vec![("a_new", option_asc), ("d_new", option_asc)],
1722                ],
1723            ),
1724            // ------- TEST CASE 8 ----------
1725            (
1726                // orderings
1727                vec![
1728                    // [b+d ASC]
1729                    vec![(&b_plus_d, option_asc)],
1730                ],
1731                // proj exprs
1732                vec![
1733                    (col_b, "b_new".to_string()),
1734                    (col_a, "a_new".to_string()),
1735                    (col_d, "d_new".to_string()),
1736                    (&b_plus_d, "b+d".to_string()),
1737                ],
1738                // expected
1739                vec![
1740                    // [b+d ASC]
1741                    vec![("b+d", option_asc)],
1742                ],
1743            ),
1744            // ------- TEST CASE 9 ----------
1745            (
1746                // orderings
1747                vec![
1748                    // [a ASC, d ASC, b ASC]
1749                    vec![
1750                        (col_a, option_asc),
1751                        (col_d, option_asc),
1752                        (col_b, option_asc),
1753                    ],
1754                    // [c ASC]
1755                    vec![(col_c, option_asc)],
1756                ],
1757                // proj exprs
1758                vec![
1759                    (col_b, "b_new".to_string()),
1760                    (col_a, "a_new".to_string()),
1761                    (col_d, "d_new".to_string()),
1762                    (col_c, "c_new".to_string()),
1763                ],
1764                // expected
1765                vec![
1766                    // [a_new ASC, d_new ASC, b_new ASC]
1767                    vec![
1768                        ("a_new", option_asc),
1769                        ("d_new", option_asc),
1770                        ("b_new", option_asc),
1771                    ],
1772                    // [c_new ASC],
1773                    vec![("c_new", option_asc)],
1774                ],
1775            ),
1776            // ------- TEST CASE 10 ----------
1777            (
1778                vec![
1779                    // [a ASC, b ASC, c ASC]
1780                    vec![
1781                        (col_a, option_asc),
1782                        (col_b, option_asc),
1783                        (col_c, option_asc),
1784                    ],
1785                    // [a ASC, d ASC]
1786                    vec![(col_a, option_asc), (col_d, option_asc)],
1787                ],
1788                // proj exprs
1789                vec![
1790                    (col_b, "b_new".to_string()),
1791                    (col_a, "a_new".to_string()),
1792                    (col_c, "c_new".to_string()),
1793                    (&c_plus_d, "c+d".to_string()),
1794                ],
1795                // expected
1796                vec![
1797                    // [a_new ASC, b_new ASC, c_new ASC]
1798                    vec![
1799                        ("a_new", option_asc),
1800                        ("b_new", option_asc),
1801                        ("c_new", option_asc),
1802                    ],
1803                ],
1804            ),
1805            // ------- TEST CASE 11 ----------
1806            (
1807                // orderings
1808                vec![
1809                    // [a ASC, b ASC]
1810                    vec![(col_a, option_asc), (col_b, option_asc)],
1811                    // [a ASC, d ASC]
1812                    vec![(col_a, option_asc), (col_d, option_asc)],
1813                ],
1814                // proj exprs
1815                vec![
1816                    (col_b, "b_new".to_string()),
1817                    (col_a, "a_new".to_string()),
1818                    (&b_plus_d, "b+d".to_string()),
1819                ],
1820                // expected
1821                vec![
1822                    // [a_new ASC, b_new ASC]
1823                    vec![("a_new", option_asc), ("b_new", option_asc)],
1824                ],
1825            ),
1826            // ------- TEST CASE 12 ----------
1827            (
1828                // orderings
1829                vec![
1830                    // [a ASC, b ASC, c ASC]
1831                    vec![
1832                        (col_a, option_asc),
1833                        (col_b, option_asc),
1834                        (col_c, option_asc),
1835                    ],
1836                ],
1837                // proj exprs
1838                vec![(col_c, "c_new".to_string()), (col_a, "a_new".to_string())],
1839                // expected
1840                vec![
1841                    // [a_new ASC]
1842                    vec![("a_new", option_asc)],
1843                ],
1844            ),
1845            // ------- TEST CASE 13 ----------
1846            (
1847                // orderings
1848                vec![
1849                    // [a ASC, b ASC, c ASC]
1850                    vec![
1851                        (col_a, option_asc),
1852                        (col_b, option_asc),
1853                        (col_c, option_asc),
1854                    ],
1855                    // [a ASC, a + b ASC, c ASC]
1856                    vec![
1857                        (col_a, option_asc),
1858                        (&a_plus_b, option_asc),
1859                        (col_c, option_asc),
1860                    ],
1861                ],
1862                // proj exprs
1863                vec![
1864                    (col_c, "c_new".to_string()),
1865                    (col_b, "b_new".to_string()),
1866                    (col_a, "a_new".to_string()),
1867                    (&a_plus_b, "a+b".to_string()),
1868                ],
1869                // expected
1870                vec![
1871                    // [a_new ASC, b_new ASC, c_new ASC]
1872                    vec![
1873                        ("a_new", option_asc),
1874                        ("b_new", option_asc),
1875                        ("c_new", option_asc),
1876                    ],
1877                    // [a_new ASC, a+b ASC, c_new ASC]
1878                    vec![
1879                        ("a_new", option_asc),
1880                        ("a+b", option_asc),
1881                        ("c_new", option_asc),
1882                    ],
1883                ],
1884            ),
1885            // ------- TEST CASE 14 ----------
1886            (
1887                // orderings
1888                vec![
1889                    // [a ASC, b ASC]
1890                    vec![(col_a, option_asc), (col_b, option_asc)],
1891                    // [c ASC, b ASC]
1892                    vec![(col_c, option_asc), (col_b, option_asc)],
1893                    // [d ASC, e ASC]
1894                    vec![(col_d, option_asc), (col_e, option_asc)],
1895                ],
1896                // proj exprs
1897                vec![
1898                    (col_c, "c_new".to_string()),
1899                    (col_d, "d_new".to_string()),
1900                    (col_a, "a_new".to_string()),
1901                    (&b_plus_e, "b+e".to_string()),
1902                ],
1903                // expected
1904                vec![
1905                    // [a_new ASC]
1906                    vec![("a_new", option_asc)],
1907                    // [c_new ASC]
1908                    vec![("c_new", option_asc)],
1909                    // [d_new ASC]
1910                    vec![("d_new", option_asc)],
1911                ],
1912            ),
1913            // ------- TEST CASE 15 ----------
1914            (
1915                // orderings
1916                vec![
1917                    // [a ASC, c ASC, b ASC]
1918                    vec![
1919                        (col_a, option_asc),
1920                        (col_c, option_asc),
1921                        (col_b, option_asc),
1922                    ],
1923                ],
1924                // proj exprs
1925                vec![
1926                    (col_c, "c_new".to_string()),
1927                    (col_a, "a_new".to_string()),
1928                    (&a_plus_b, "a+b".to_string()),
1929                ],
1930                // expected
1931                vec![
1932                    // [a_new ASC, c_new ASC]
1933                    vec![("a_new", option_asc), ("c_new", option_asc)],
1934                ],
1935            ),
1936            // ------- TEST CASE 16 ----------
1937            (
1938                // orderings
1939                vec![
1940                    // [a ASC, b ASC]
1941                    vec![(col_a, option_asc), (col_b, option_asc)],
1942                    // [c ASC, b DESC]
1943                    vec![(col_c, option_asc), (col_b, option_desc)],
1944                    // [e ASC]
1945                    vec![(col_e, option_asc)],
1946                ],
1947                // proj exprs
1948                vec![
1949                    (col_c, "c_new".to_string()),
1950                    (col_a, "a_new".to_string()),
1951                    (col_b, "b_new".to_string()),
1952                    (&b_plus_e, "b+e".to_string()),
1953                ],
1954                // expected
1955                vec![
1956                    // [a_new ASC, b_new ASC]
1957                    vec![("a_new", option_asc), ("b_new", option_asc)],
1958                    // [c_new ASC, b_new DESC]
1959                    vec![("c_new", option_asc), ("b_new", option_desc)],
1960                ],
1961            ),
1962        ];
1963
1964        for (idx, (orderings, proj_exprs, expected)) in test_cases.into_iter().enumerate()
1965        {
1966            let mut eq_properties = EquivalenceProperties::new(Arc::clone(&schema));
1967
1968            let orderings = convert_to_orderings(&orderings);
1969            eq_properties.add_orderings(orderings);
1970
1971            let proj_exprs = proj_exprs
1972                .into_iter()
1973                .map(|(expr, name)| (Arc::clone(expr), name));
1974            let projection_mapping = ProjectionMapping::try_new(proj_exprs, &schema)?;
1975            let output_schema = output_schema(&projection_mapping, &schema)?;
1976
1977            let expected = expected
1978                .into_iter()
1979                .map(|ordering| {
1980                    ordering
1981                        .into_iter()
1982                        .map(|(name, options)| {
1983                            (col(name, &output_schema).unwrap(), options)
1984                        })
1985                        .collect::<Vec<_>>()
1986                })
1987                .collect::<Vec<_>>();
1988            let expected = convert_to_orderings(&expected);
1989
1990            let projected_eq = eq_properties.project(&projection_mapping, output_schema);
1991            let orderings = projected_eq.oeq_class();
1992
1993            let err_msg = format!(
1994                "test_idx: {idx:?}, actual: {orderings:?}, expected: {expected:?}, projection_mapping: {projection_mapping:?}"
1995            );
1996
1997            assert_eq!(orderings.len(), expected.len(), "{err_msg}");
1998            for expected_ordering in &expected {
1999                assert!(orderings.contains(expected_ordering), "{}", err_msg)
2000            }
2001        }
2002
2003        Ok(())
2004    }
2005
2006    #[test]
2007    fn project_orderings2() -> Result<()> {
2008        let schema = Arc::new(Schema::new(vec![
2009            Field::new("a", DataType::Int32, true),
2010            Field::new("b", DataType::Int32, true),
2011            Field::new("c", DataType::Int32, true),
2012            Field::new("d", DataType::Int32, true),
2013            Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),
2014        ]));
2015        let col_a = &col("a", &schema)?;
2016        let col_b = &col("b", &schema)?;
2017        let col_c = &col("c", &schema)?;
2018        let col_ts = &col("ts", &schema)?;
2019        let a_plus_b = Arc::new(BinaryExpr::new(
2020            Arc::clone(col_a),
2021            Operator::Plus,
2022            Arc::clone(col_b),
2023        )) as Arc<dyn PhysicalExpr>;
2024
2025        let test_fun = Arc::new(ScalarUDF::new_from_impl(TestScalarUDF::new()));
2026
2027        let round_c = Arc::new(ScalarFunctionExpr::try_new(
2028            test_fun,
2029            vec![Arc::clone(col_c)],
2030            &schema,
2031            Arc::new(ConfigOptions::default()),
2032        )?) as PhysicalExprRef;
2033
2034        let option_asc = SortOptions {
2035            descending: false,
2036            nulls_first: false,
2037        };
2038
2039        let proj_exprs = vec![
2040            (col_b, "b_new".to_string()),
2041            (col_a, "a_new".to_string()),
2042            (col_c, "c_new".to_string()),
2043            (&round_c, "round_c_res".to_string()),
2044        ];
2045        let proj_exprs = proj_exprs
2046            .into_iter()
2047            .map(|(expr, name)| (Arc::clone(expr), name));
2048        let projection_mapping = ProjectionMapping::try_new(proj_exprs, &schema)?;
2049        let output_schema = output_schema(&projection_mapping, &schema)?;
2050
2051        let col_a_new = &col("a_new", &output_schema)?;
2052        let col_b_new = &col("b_new", &output_schema)?;
2053        let col_c_new = &col("c_new", &output_schema)?;
2054        let col_round_c_res = &col("round_c_res", &output_schema)?;
2055        let a_new_plus_b_new = Arc::new(BinaryExpr::new(
2056            Arc::clone(col_a_new),
2057            Operator::Plus,
2058            Arc::clone(col_b_new),
2059        )) as Arc<dyn PhysicalExpr>;
2060
2061        let test_cases = [
2062            // ---------- TEST CASE 1 ------------
2063            (
2064                // orderings
2065                vec![
2066                    // [a ASC]
2067                    vec![(col_a, option_asc)],
2068                ],
2069                // expected
2070                vec![
2071                    // [b_new ASC]
2072                    vec![(col_a_new, option_asc)],
2073                ],
2074            ),
2075            // ---------- TEST CASE 2 ------------
2076            (
2077                // orderings
2078                vec![
2079                    // [a+b ASC]
2080                    vec![(&a_plus_b, option_asc)],
2081                ],
2082                // expected
2083                vec![
2084                    // [b_new ASC]
2085                    vec![(&a_new_plus_b_new, option_asc)],
2086                ],
2087            ),
2088            // ---------- TEST CASE 3 ------------
2089            (
2090                // orderings
2091                vec![
2092                    // [a ASC, ts ASC]
2093                    vec![(col_a, option_asc), (col_ts, option_asc)],
2094                ],
2095                // expected
2096                vec![
2097                    // [a_new ASC, date_bin_res ASC]
2098                    vec![(col_a_new, option_asc)],
2099                ],
2100            ),
2101            // ---------- TEST CASE 4 ------------
2102            (
2103                // orderings
2104                vec![
2105                    // [a ASC, ts ASC, b ASC]
2106                    vec![
2107                        (col_a, option_asc),
2108                        (col_ts, option_asc),
2109                        (col_b, option_asc),
2110                    ],
2111                ],
2112                // expected
2113                vec![
2114                    // [a_new ASC, date_bin_res ASC]
2115                    vec![(col_a_new, option_asc)],
2116                ],
2117            ),
2118            // ---------- TEST CASE 5 ------------
2119            (
2120                // orderings
2121                vec![
2122                    // [a ASC, c ASC]
2123                    vec![(col_a, option_asc), (col_c, option_asc)],
2124                ],
2125                // expected
2126                vec![
2127                    // [a_new ASC, round_c_res ASC, c_new ASC]
2128                    vec![(col_a_new, option_asc), (col_round_c_res, option_asc)],
2129                    // [a_new ASC, c_new ASC]
2130                    vec![(col_a_new, option_asc), (col_c_new, option_asc)],
2131                ],
2132            ),
2133            // ---------- TEST CASE 6 ------------
2134            (
2135                // orderings
2136                vec![
2137                    // [c ASC, b ASC]
2138                    vec![(col_c, option_asc), (col_b, option_asc)],
2139                ],
2140                // expected
2141                vec![
2142                    // [round_c_res ASC]
2143                    vec![(col_round_c_res, option_asc)],
2144                    // [c_new ASC, b_new ASC]
2145                    vec![(col_c_new, option_asc), (col_b_new, option_asc)],
2146                ],
2147            ),
2148            // ---------- TEST CASE 7 ------------
2149            (
2150                // orderings
2151                vec![
2152                    // [a+b ASC, c ASC]
2153                    vec![(&a_plus_b, option_asc), (col_c, option_asc)],
2154                ],
2155                // expected
2156                vec![
2157                    // [a+b ASC, round(c) ASC, c_new ASC]
2158                    vec![
2159                        (&a_new_plus_b_new, option_asc),
2160                        (col_round_c_res, option_asc),
2161                    ],
2162                    // [a+b ASC, c_new ASC]
2163                    vec![(&a_new_plus_b_new, option_asc), (col_c_new, option_asc)],
2164                ],
2165            ),
2166        ];
2167
2168        for (idx, (orderings, expected)) in test_cases.iter().enumerate() {
2169            let mut eq_properties = EquivalenceProperties::new(Arc::clone(&schema));
2170
2171            let orderings = convert_to_orderings(orderings);
2172            eq_properties.add_orderings(orderings);
2173
2174            let expected = convert_to_orderings(expected);
2175
2176            let projected_eq =
2177                eq_properties.project(&projection_mapping, Arc::clone(&output_schema));
2178            let orderings = projected_eq.oeq_class();
2179
2180            let err_msg = format!(
2181                "test idx: {idx:?}, actual: {orderings:?}, expected: {expected:?}, projection_mapping: {projection_mapping:?}"
2182            );
2183
2184            assert_eq!(orderings.len(), expected.len(), "{err_msg}");
2185            for expected_ordering in &expected {
2186                assert!(orderings.contains(expected_ordering), "{}", err_msg)
2187            }
2188        }
2189        Ok(())
2190    }
2191
2192    #[test]
2193    fn project_orderings3() -> Result<()> {
2194        let schema = Arc::new(Schema::new(vec![
2195            Field::new("a", DataType::Int32, true),
2196            Field::new("b", DataType::Int32, true),
2197            Field::new("c", DataType::Int32, true),
2198            Field::new("d", DataType::Int32, true),
2199            Field::new("e", DataType::Int32, true),
2200            Field::new("f", DataType::Int32, true),
2201        ]));
2202        let col_a = &col("a", &schema)?;
2203        let col_b = &col("b", &schema)?;
2204        let col_c = &col("c", &schema)?;
2205        let col_d = &col("d", &schema)?;
2206        let col_e = &col("e", &schema)?;
2207        let col_f = &col("f", &schema)?;
2208        let a_plus_b = Arc::new(BinaryExpr::new(
2209            Arc::clone(col_a),
2210            Operator::Plus,
2211            Arc::clone(col_b),
2212        )) as Arc<dyn PhysicalExpr>;
2213
2214        let option_asc = SortOptions {
2215            descending: false,
2216            nulls_first: false,
2217        };
2218
2219        let proj_exprs = vec![
2220            (col_c, "c_new".to_string()),
2221            (col_d, "d_new".to_string()),
2222            (&a_plus_b, "a+b".to_string()),
2223        ];
2224        let proj_exprs = proj_exprs
2225            .into_iter()
2226            .map(|(expr, name)| (Arc::clone(expr), name));
2227        let projection_mapping = ProjectionMapping::try_new(proj_exprs, &schema)?;
2228        let output_schema = output_schema(&projection_mapping, &schema)?;
2229
2230        let col_c_new = &col("c_new", &output_schema)?;
2231        let col_d_new = &col("d_new", &output_schema)?;
2232
2233        let test_cases = vec![
2234            // ---------- TEST CASE 1 ------------
2235            (
2236                // orderings
2237                vec![
2238                    // [d ASC, b ASC]
2239                    vec![(col_d, option_asc), (col_b, option_asc)],
2240                    // [c ASC, a ASC]
2241                    vec![(col_c, option_asc), (col_a, option_asc)],
2242                ],
2243                // equal conditions
2244                vec![],
2245                // expected
2246                vec![
2247                    // [c_new ASC]
2248                    vec![(col_c_new, option_asc)],
2249                    // [d_new ASC]
2250                    vec![(col_d_new, option_asc)],
2251                ],
2252            ),
2253            // ---------- TEST CASE 2 ------------
2254            (
2255                // orderings
2256                vec![
2257                    // [d ASC, b ASC]
2258                    vec![(col_d, option_asc), (col_b, option_asc)],
2259                    // [c ASC, e ASC], Please note that a=e
2260                    vec![(col_c, option_asc), (col_e, option_asc)],
2261                ],
2262                // equal conditions
2263                vec![(col_e, col_a)],
2264                // expected
2265                vec![
2266                    // [c_new ASC]
2267                    vec![(col_c_new, option_asc)],
2268                    // [d_new ASC]
2269                    vec![(col_d_new, option_asc)],
2270                ],
2271            ),
2272            // ---------- TEST CASE 3 ------------
2273            (
2274                // orderings
2275                vec![
2276                    // [d ASC, b ASC]
2277                    vec![(col_d, option_asc), (col_b, option_asc)],
2278                    // [c ASC, e ASC], Please note that a=f
2279                    vec![(col_c, option_asc), (col_e, option_asc)],
2280                ],
2281                // equal conditions
2282                vec![(col_a, col_f)],
2283                // expected
2284                vec![
2285                    // [d_new ASC]
2286                    vec![(col_d_new, option_asc)],
2287                    // [c_new ASC]
2288                    vec![(col_c_new, option_asc)],
2289                ],
2290            ),
2291        ];
2292        for (orderings, equal_columns, expected) in test_cases {
2293            let mut eq_properties = EquivalenceProperties::new(Arc::clone(&schema));
2294            for (lhs, rhs) in equal_columns {
2295                eq_properties.add_equal_conditions(Arc::clone(lhs), Arc::clone(rhs))?;
2296            }
2297
2298            let orderings = convert_to_orderings(&orderings);
2299            eq_properties.add_orderings(orderings);
2300
2301            let expected = convert_to_orderings(&expected);
2302
2303            let projected_eq =
2304                eq_properties.project(&projection_mapping, Arc::clone(&output_schema));
2305            let orderings = projected_eq.oeq_class();
2306
2307            let err_msg = format!(
2308                "actual: {orderings:?}, expected: {expected:?}, projection_mapping: {projection_mapping:?}"
2309            );
2310
2311            assert_eq!(orderings.len(), expected.len(), "{err_msg}");
2312            for expected_ordering in &expected {
2313                assert!(orderings.contains(expected_ordering), "{}", err_msg)
2314            }
2315        }
2316
2317        Ok(())
2318    }
2319
2320    #[test]
2321    fn test_project_statistics_safe_cast_without_extrema() {
2322        let input_schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
2323        let mut stats = Statistics::new_unknown(&input_schema);
2324        stats.num_rows = Precision::Exact(5);
2325        stats.column_statistics[0].null_count = Precision::Exact(3);
2326        stats.column_statistics[0].distinct_count = Precision::Exact(2);
2327        let projection = ProjectionExprs::new(vec![ProjectionExpr::new(
2328            Arc::new(CastExpr::new(
2329                Arc::new(Column::new("a", 0)),
2330                DataType::Int64,
2331                None,
2332            )),
2333            "a",
2334        )]);
2335        let output_schema = projection
2336            .project_schema(&input_schema)
2337            .expect("valid projection schema");
2338
2339        let output = projection
2340            .project_statistics_with_input_schema(stats, &input_schema, &output_schema)
2341            .expect("statistics projection succeeds");
2342
2343        assert_eq!(output.column_statistics[0].null_count, Precision::Exact(3));
2344        assert_eq!(
2345            output.column_statistics[0].distinct_count,
2346            Precision::Exact(2)
2347        );
2348    }
2349
2350    #[test]
2351    fn test_project_statistics_non_monotonic_cast() {
2352        let input_schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
2353        let mut stats = Statistics::new_unknown(&input_schema);
2354        stats.num_rows = Precision::Exact(3);
2355        stats.column_statistics[0].min_value = Precision::Exact(ScalarValue::from("1"));
2356        stats.column_statistics[0].max_value = Precision::Exact(ScalarValue::from("2"));
2357        let expr: Arc<dyn PhysicalExpr> = Arc::new(CastExpr::new(
2358            Arc::new(Column::new("a", 0)),
2359            DataType::Int32,
2360            None,
2361        ));
2362        let projection = ProjectionExprs::new(vec![ProjectionExpr {
2363            expr: Arc::clone(&expr),
2364            alias: "x".to_string(),
2365        }]);
2366        let out = projection
2367            .project_statistics(
2368                stats,
2369                &projection
2370                    .project_schema(&input_schema)
2371                    .expect("valid projection schema"),
2372            )
2373            .expect("statistics projection succeeds");
2374        let batch = RecordBatch::try_new(
2375            Arc::new(input_schema),
2376            vec![Arc::new(arrow::array::StringArray::from(vec![
2377                "1", "100", "2",
2378            ]))],
2379        )
2380        .expect("valid input batch");
2381        let actual = expr
2382            .evaluate(&batch)
2383            .expect("cast succeeds")
2384            .into_array(3)
2385            .expect("array result");
2386        assert_eq!(out.column_statistics[0].max_value, Precision::Absent);
2387        assert_eq!(out.column_statistics[0].min_value, Precision::Absent);
2388        assert_eq!(
2389            ScalarValue::try_from_array(&actual, 1).expect("valid scalar value"),
2390            ScalarValue::Int32(Some(100))
2391        );
2392    }
2393
2394    #[test]
2395    fn test_is_within_extrema() {
2396        use Precision::{Absent, Exact, Inexact};
2397        use ScalarValue::{Int8, Int64, UInt8};
2398
2399        for (lower, upper, target_type, expected) in [
2400            (
2401                Exact(Int64(Some(-128))),
2402                Exact(Int64(Some(127))),
2403                DataType::Int8,
2404                true,
2405            ),
2406            (
2407                Exact(Int64(Some(-129))),
2408                Exact(Int64(Some(127))),
2409                DataType::Int8,
2410                false,
2411            ),
2412            (
2413                Exact(Int64(Some(-128))),
2414                Exact(Int64(Some(128))),
2415                DataType::Int8,
2416                false,
2417            ),
2418            (
2419                Exact(Int64(Some(0))),
2420                Exact(Int64(Some(255))),
2421                DataType::UInt8,
2422                true,
2423            ),
2424            (
2425                Exact(Int64(Some(-1))),
2426                Exact(Int64(Some(255))),
2427                DataType::UInt8,
2428                false,
2429            ),
2430            (
2431                Exact(UInt8(Some(0))),
2432                Exact(UInt8(Some(127))),
2433                DataType::Int8,
2434                true,
2435            ),
2436            (
2437                Exact(UInt8(Some(0))),
2438                Exact(UInt8(Some(128))),
2439                DataType::Int8,
2440                false,
2441            ),
2442            (
2443                Exact(ScalarValue::from("1")),
2444                Exact(ScalarValue::from("2")),
2445                DataType::Int8,
2446                false,
2447            ),
2448            (
2449                Exact(Int64(Some(1))),
2450                Exact(Int64(Some(2))),
2451                DataType::Utf8,
2452                false,
2453            ),
2454        ] {
2455            let min = lower.cast_to(&target_type).unwrap_or(Absent);
2456            let max = upper.cast_to(&target_type).unwrap_or(Absent);
2457            assert_eq!(
2458                is_within_extrema(&lower, &upper, &min, &max),
2459                expected,
2460                "{lower:?}..{upper:?} -> {target_type:?}",
2461            );
2462        }
2463
2464        // Every bound must be exact and non-null, including converted endpoints.
2465        let bounds = [
2466            Exact(Int64(Some(-128))),
2467            Exact(Int64(Some(127))),
2468            Exact(Int8(Some(-128))),
2469            Exact(Int8(Some(127))),
2470        ];
2471        for index in 0..bounds.len() {
2472            for invalid in [
2473                Absent,
2474                Inexact(bounds[index].get_value().unwrap().clone()),
2475                Exact(
2476                    ScalarValue::try_from(
2477                        &bounds[index].get_value().unwrap().data_type(),
2478                    )
2479                    .unwrap(),
2480                ),
2481            ] {
2482                let mut bounds = bounds.clone();
2483                bounds[index] = invalid;
2484                assert!(!is_within_extrema(
2485                    &bounds[0], &bounds[1], &bounds[2], &bounds[3],
2486                ));
2487            }
2488        }
2489    }
2490
2491    #[test]
2492    fn test_project_statistics_lossless_cast() {
2493        use Precision::{Absent, Exact, Inexact};
2494
2495        for (lower, upper, targets) in [
2496            (
2497                ScalarValue::UInt8(Some(0)),
2498                ScalarValue::UInt8(Some(u8::MAX)),
2499                vec![DataType::Int16, DataType::Int32, DataType::Int64],
2500            ),
2501            (
2502                ScalarValue::UInt16(Some(0)),
2503                ScalarValue::UInt16(Some(u16::MAX)),
2504                vec![DataType::Int32, DataType::Int64],
2505            ),
2506            (
2507                ScalarValue::UInt32(Some(0)),
2508                ScalarValue::UInt32(Some(u32::MAX)),
2509                vec![DataType::Int64],
2510            ),
2511            (
2512                ScalarValue::Utf8(Some(String::new())),
2513                ScalarValue::Utf8(Some("🦀".to_string())),
2514                vec![DataType::Utf8View],
2515            ),
2516            (
2517                ScalarValue::Binary(Some(vec![])),
2518                ScalarValue::Binary(Some(vec![0xff])),
2519                vec![DataType::LargeBinary, DataType::BinaryView],
2520            ),
2521        ] {
2522            for target in targets {
2523                // A globally safe cast does not need two exact extrema. Preserve
2524                // whichever bounds are available without upgrading their precision.
2525                for (min_value, max_value) in [
2526                    (Exact(lower.clone()), Exact(upper.clone())),
2527                    (Exact(lower.clone()), Absent),
2528                    (Absent, Exact(upper.clone())),
2529                    (Inexact(lower.clone()), Inexact(upper.clone())),
2530                    (Inexact(lower.clone()), Absent),
2531                    (Absent, Inexact(upper.clone())),
2532                ] {
2533                    let input = ColumnStatistics {
2534                        min_value: min_value.clone(),
2535                        max_value: max_value.clone(),
2536                        null_count: Exact(1),
2537                        distinct_count: Inexact(3),
2538                        sum_value: Absent,
2539                        byte_size: Absent,
2540                    };
2541                    let expr = CastExpr::new(
2542                        Arc::new(Column::new("a", 0)),
2543                        target.clone(),
2544                        None,
2545                    );
2546                    let output =
2547                        project_column_statistics_through_expr(&expr, &[input], None);
2548                    assert_eq!(
2549                        output,
2550                        ColumnStatistics {
2551                            min_value: min_value.cast_to(&target).unwrap(),
2552                            max_value: max_value.cast_to(&target).unwrap(),
2553                            null_count: Exact(1),
2554                            distinct_count: Inexact(3),
2555                            sum_value: Absent,
2556                            byte_size: Absent,
2557                        },
2558                        "{} -> {target}, {min_value:?}..{max_value:?}",
2559                        lower.data_type()
2560                    );
2561                }
2562            }
2563        }
2564    }
2565
2566    #[test]
2567    fn test_project_statistics_narrowing_cast_requires_safe_bounds() {
2568        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
2569        for (lower, upper, exact, safe) in [
2570            (-100, 100, true, true),
2571            (-200, 100, true, false),
2572            (-100, 200, true, false),
2573            (-100, 100, false, false),
2574        ] {
2575            let precision = |v| {
2576                if exact {
2577                    Precision::Exact(ScalarValue::Int32(Some(v)))
2578                } else {
2579                    Precision::Inexact(ScalarValue::Int32(Some(v)))
2580                }
2581            };
2582            let mut stats = Statistics::new_unknown(&schema);
2583            stats.column_statistics[0].min_value = precision(lower);
2584            stats.column_statistics[0].max_value = precision(upper);
2585            let projection = ProjectionExprs::new(vec![ProjectionExpr::new(
2586                Arc::new(CastExpr::new(
2587                    Arc::new(Column::new("a", 0)),
2588                    DataType::Int8,
2589                    None,
2590                )),
2591                "x",
2592            )]);
2593            let output = projection
2594                .project_statistics(
2595                    stats,
2596                    &projection
2597                        .project_schema(&schema)
2598                        .expect("valid projection schema"),
2599                )
2600                .expect("statistics projection succeeds");
2601            if safe {
2602                assert_eq!(
2603                    output.column_statistics[0].min_value,
2604                    Precision::Exact(ScalarValue::Int8(Some(-100)))
2605                );
2606                assert_eq!(
2607                    output.column_statistics[0].max_value,
2608                    Precision::Exact(ScalarValue::Int8(Some(100)))
2609                );
2610            } else {
2611                assert_eq!(output.column_statistics[0], ColumnStatistics::new_unknown());
2612            }
2613        }
2614    }
2615
2616    fn get_stats() -> Statistics {
2617        Statistics {
2618            num_rows: Precision::Exact(5),
2619            total_byte_size: Precision::Exact(23),
2620            column_statistics: vec![
2621                ColumnStatistics {
2622                    distinct_count: Precision::Exact(5),
2623                    max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
2624                    min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
2625                    sum_value: Precision::Exact(ScalarValue::Int64(Some(42))),
2626                    null_count: Precision::Exact(0),
2627                    byte_size: Precision::Absent,
2628                },
2629                ColumnStatistics {
2630                    distinct_count: Precision::Exact(1),
2631                    max_value: Precision::Exact(ScalarValue::from("x")),
2632                    min_value: Precision::Exact(ScalarValue::from("a")),
2633                    sum_value: Precision::Absent,
2634                    null_count: Precision::Exact(3),
2635                    byte_size: Precision::Absent,
2636                },
2637                ColumnStatistics {
2638                    distinct_count: Precision::Absent,
2639                    max_value: Precision::Exact(ScalarValue::Float32(Some(1.1))),
2640                    min_value: Precision::Exact(ScalarValue::Float32(Some(0.1))),
2641                    sum_value: Precision::Exact(ScalarValue::Float32(Some(5.5))),
2642                    null_count: Precision::Absent,
2643                    byte_size: Precision::Absent,
2644                },
2645            ],
2646        }
2647    }
2648
2649    fn get_schema() -> Schema {
2650        let field_0 = Field::new("col0", DataType::Int64, false);
2651        let field_1 = Field::new("col1", DataType::Utf8, false);
2652        let field_2 = Field::new("col2", DataType::Float32, false);
2653        Schema::new(vec![field_0, field_1, field_2])
2654    }
2655
2656    #[test]
2657    fn test_projected_column_position_returns_output_position() {
2658        let projection = ProjectionExprs::new([
2659            ProjectionExpr::new(Arc::new(Column::new("col2", 2)), "col2"),
2660            ProjectionExpr::new(Arc::new(Column::new("col0", 0)), "col0"),
2661        ]);
2662
2663        assert_eq!(
2664            projection.projected_column_position(&Column::new("col2", 2)),
2665            Some(0)
2666        );
2667        assert_eq!(
2668            projection.projected_column_position(&Column::new("col0", 0)),
2669            Some(1)
2670        );
2671    }
2672
2673    #[test]
2674    fn test_projected_column_position_returns_none_for_non_column_or_missing() {
2675        let projection = ProjectionExprs::new([
2676            ProjectionExpr::new(
2677                Arc::new(Literal::new(ScalarValue::Int64(Some(42)))),
2678                "col1",
2679            ),
2680            ProjectionExpr::new(Arc::new(Column::new("col0", 0)), "col0"),
2681        ]);
2682
2683        assert_eq!(
2684            projection.projected_column_position(&Column::new("col1", 1)),
2685            None
2686        );
2687        assert_eq!(
2688            projection.projected_column_position(&Column::new("col2", 2)),
2689            None
2690        );
2691    }
2692
2693    #[test]
2694    fn test_stats_projection_columns_only() {
2695        let source = get_stats();
2696        let schema = get_schema();
2697
2698        let projection = ProjectionExprs::new(vec![
2699            ProjectionExpr {
2700                expr: Arc::new(Column::new("col1", 1)),
2701                alias: "col1".to_string(),
2702            },
2703            ProjectionExpr {
2704                expr: Arc::new(Column::new("col0", 0)),
2705                alias: "col0".to_string(),
2706            },
2707        ]);
2708
2709        let result = projection
2710            .project_statistics(source, &projection.project_schema(&schema).unwrap())
2711            .unwrap();
2712
2713        let expected = Statistics {
2714            num_rows: Precision::Exact(5),
2715            // Because there is a variable length Utf8 column we cannot calculate exact byte size after projection
2716            // Thus we set it to Inexact (originally it was Exact(23))
2717            total_byte_size: Precision::Inexact(23),
2718            column_statistics: vec![
2719                ColumnStatistics {
2720                    distinct_count: Precision::Exact(1),
2721                    max_value: Precision::Exact(ScalarValue::from("x")),
2722                    min_value: Precision::Exact(ScalarValue::from("a")),
2723                    sum_value: Precision::Absent,
2724                    null_count: Precision::Exact(3),
2725                    byte_size: Precision::Absent,
2726                },
2727                ColumnStatistics {
2728                    distinct_count: Precision::Exact(5),
2729                    max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
2730                    min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
2731                    sum_value: Precision::Exact(ScalarValue::Int64(Some(42))),
2732                    null_count: Precision::Exact(0),
2733                    byte_size: Precision::Absent,
2734                },
2735            ],
2736        };
2737
2738        assert_eq!(result, expected);
2739    }
2740
2741    #[test]
2742    fn test_stats_projection_column_with_primitive_width_only() {
2743        let source = get_stats();
2744        let schema = get_schema();
2745
2746        let projection = ProjectionExprs::new(vec![
2747            ProjectionExpr {
2748                expr: Arc::new(Column::new("col2", 2)),
2749                alias: "col2".to_string(),
2750            },
2751            ProjectionExpr {
2752                expr: Arc::new(Column::new("col0", 0)),
2753                alias: "col0".to_string(),
2754            },
2755        ]);
2756
2757        let result = projection
2758            .project_statistics(source, &projection.project_schema(&schema).unwrap())
2759            .unwrap();
2760
2761        let expected = Statistics {
2762            num_rows: Precision::Exact(5),
2763            total_byte_size: Precision::Exact(60),
2764            column_statistics: vec![
2765                ColumnStatistics {
2766                    distinct_count: Precision::Absent,
2767                    max_value: Precision::Exact(ScalarValue::Float32(Some(1.1))),
2768                    min_value: Precision::Exact(ScalarValue::Float32(Some(0.1))),
2769                    sum_value: Precision::Exact(ScalarValue::Float32(Some(5.5))),
2770                    null_count: Precision::Absent,
2771                    byte_size: Precision::Absent,
2772                },
2773                ColumnStatistics {
2774                    distinct_count: Precision::Exact(5),
2775                    max_value: Precision::Exact(ScalarValue::Int64(Some(21))),
2776                    min_value: Precision::Exact(ScalarValue::Int64(Some(-4))),
2777                    sum_value: Precision::Exact(ScalarValue::Int64(Some(42))),
2778                    null_count: Precision::Exact(0),
2779                    byte_size: Precision::Absent,
2780                },
2781            ],
2782        };
2783
2784        assert_eq!(result, expected);
2785    }
2786
2787    // Tests for Projection struct
2788
2789    #[test]
2790    fn test_projection_new() -> Result<()> {
2791        let exprs = vec![
2792            ProjectionExpr {
2793                expr: Arc::new(Column::new("a", 0)),
2794                alias: "a".to_string(),
2795            },
2796            ProjectionExpr {
2797                expr: Arc::new(Column::new("b", 1)),
2798                alias: "b".to_string(),
2799            },
2800        ];
2801        let projection = ProjectionExprs::new(exprs.clone());
2802        assert_eq!(projection.as_ref().len(), 2);
2803        Ok(())
2804    }
2805
2806    #[test]
2807    fn test_projection_from_vec() -> Result<()> {
2808        let exprs = vec![ProjectionExpr {
2809            expr: Arc::new(Column::new("x", 0)),
2810            alias: "x".to_string(),
2811        }];
2812        let projection: ProjectionExprs = exprs.clone().into();
2813        assert_eq!(projection.as_ref().len(), 1);
2814        Ok(())
2815    }
2816
2817    #[test]
2818    fn test_projection_as_ref() -> Result<()> {
2819        let exprs = vec![
2820            ProjectionExpr {
2821                expr: Arc::new(Column::new("col1", 0)),
2822                alias: "col1".to_string(),
2823            },
2824            ProjectionExpr {
2825                expr: Arc::new(Column::new("col2", 1)),
2826                alias: "col2".to_string(),
2827            },
2828        ];
2829        let projection = ProjectionExprs::new(exprs);
2830        let as_ref: &[ProjectionExpr] = projection.as_ref();
2831        assert_eq!(as_ref.len(), 2);
2832        Ok(())
2833    }
2834
2835    #[test]
2836    fn test_column_indices_multiple_columns() -> Result<()> {
2837        // Test with reversed column order to ensure proper reordering
2838        let projection = ProjectionExprs::new(vec![
2839            ProjectionExpr {
2840                expr: Arc::new(Column::new("c", 5)),
2841                alias: "c".to_string(),
2842            },
2843            ProjectionExpr {
2844                expr: Arc::new(Column::new("b", 2)),
2845                alias: "b".to_string(),
2846            },
2847            ProjectionExpr {
2848                expr: Arc::new(Column::new("a", 0)),
2849                alias: "a".to_string(),
2850            },
2851        ]);
2852        // Should return sorted indices regardless of projection order
2853        assert_eq!(projection.column_indices(), vec![0, 2, 5]);
2854        Ok(())
2855    }
2856
2857    #[test]
2858    fn test_column_indices_duplicates() -> Result<()> {
2859        // Test that duplicate column indices appear only once
2860        let projection = ProjectionExprs::new(vec![
2861            ProjectionExpr {
2862                expr: Arc::new(Column::new("a", 1)),
2863                alias: "a".to_string(),
2864            },
2865            ProjectionExpr {
2866                expr: Arc::new(Column::new("b", 3)),
2867                alias: "b".to_string(),
2868            },
2869            ProjectionExpr {
2870                expr: Arc::new(Column::new("a2", 1)), // duplicate index
2871                alias: "a2".to_string(),
2872            },
2873        ]);
2874        assert_eq!(projection.column_indices(), vec![1, 3]);
2875        Ok(())
2876    }
2877
2878    #[test]
2879    fn test_column_indices_unsorted() -> Result<()> {
2880        // Test that column indices are sorted in the output
2881        let projection = ProjectionExprs::new(vec![
2882            ProjectionExpr {
2883                expr: Arc::new(Column::new("c", 5)),
2884                alias: "c".to_string(),
2885            },
2886            ProjectionExpr {
2887                expr: Arc::new(Column::new("a", 1)),
2888                alias: "a".to_string(),
2889            },
2890            ProjectionExpr {
2891                expr: Arc::new(Column::new("b", 3)),
2892                alias: "b".to_string(),
2893            },
2894        ]);
2895        assert_eq!(projection.column_indices(), vec![1, 3, 5]);
2896        Ok(())
2897    }
2898
2899    #[test]
2900    fn test_column_indices_complex_expr() -> Result<()> {
2901        // Test with complex expressions containing multiple columns
2902        let expr = Arc::new(BinaryExpr::new(
2903            Arc::new(Column::new("a", 1)),
2904            Operator::Plus,
2905            Arc::new(Column::new("b", 4)),
2906        ));
2907        let projection = ProjectionExprs::new(vec![
2908            ProjectionExpr {
2909                expr,
2910                alias: "sum".to_string(),
2911            },
2912            ProjectionExpr {
2913                expr: Arc::new(Column::new("c", 2)),
2914                alias: "c".to_string(),
2915            },
2916        ]);
2917        // Should return [1, 2, 4] - all columns used, sorted and deduplicated
2918        assert_eq!(projection.column_indices(), vec![1, 2, 4]);
2919        Ok(())
2920    }
2921
2922    #[test]
2923    fn test_column_indices_empty() -> Result<()> {
2924        let projection = ProjectionExprs::new(vec![]);
2925        assert_eq!(projection.column_indices(), Vec::<usize>::new());
2926        Ok(())
2927    }
2928
2929    #[test]
2930    fn test_merge_simple_columns() -> Result<()> {
2931        // First projection: SELECT c@2 AS x, b@1 AS y, a@0 AS z
2932        let base_projection = ProjectionExprs::new(vec![
2933            ProjectionExpr {
2934                expr: Arc::new(Column::new("c", 2)),
2935                alias: "x".to_string(),
2936            },
2937            ProjectionExpr {
2938                expr: Arc::new(Column::new("b", 1)),
2939                alias: "y".to_string(),
2940            },
2941            ProjectionExpr {
2942                expr: Arc::new(Column::new("a", 0)),
2943                alias: "z".to_string(),
2944            },
2945        ]);
2946
2947        // Second projection: SELECT y@1 AS col2, x@0 AS col1
2948        let top_projection = ProjectionExprs::new(vec![
2949            ProjectionExpr {
2950                expr: Arc::new(Column::new("y", 1)),
2951                alias: "col2".to_string(),
2952            },
2953            ProjectionExpr {
2954                expr: Arc::new(Column::new("x", 0)),
2955                alias: "col1".to_string(),
2956            },
2957        ]);
2958
2959        // Merge should produce: SELECT b@1 AS col2, c@2 AS col1
2960        let merged = base_projection.try_merge(&top_projection)?;
2961        assert_snapshot!(format!("{merged}"), @"Projection[b@1 AS col2, c@2 AS col1]");
2962
2963        Ok(())
2964    }
2965
2966    #[test]
2967    fn test_merge_with_expressions() -> Result<()> {
2968        // First projection: SELECT c@2 AS x, b@1 AS y, a@0 AS z
2969        let base_projection = ProjectionExprs::new(vec![
2970            ProjectionExpr {
2971                expr: Arc::new(Column::new("c", 2)),
2972                alias: "x".to_string(),
2973            },
2974            ProjectionExpr {
2975                expr: Arc::new(Column::new("b", 1)),
2976                alias: "y".to_string(),
2977            },
2978            ProjectionExpr {
2979                expr: Arc::new(Column::new("a", 0)),
2980                alias: "z".to_string(),
2981            },
2982        ]);
2983
2984        // Second projection: SELECT y@1 + z@2 AS c2, x@0 + 1 AS c1
2985        let top_projection = ProjectionExprs::new(vec![
2986            ProjectionExpr {
2987                expr: Arc::new(BinaryExpr::new(
2988                    Arc::new(Column::new("y", 1)),
2989                    Operator::Plus,
2990                    Arc::new(Column::new("z", 2)),
2991                )),
2992                alias: "c2".to_string(),
2993            },
2994            ProjectionExpr {
2995                expr: Arc::new(BinaryExpr::new(
2996                    Arc::new(Column::new("x", 0)),
2997                    Operator::Plus,
2998                    Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
2999                )),
3000                alias: "c1".to_string(),
3001            },
3002        ]);
3003
3004        // Merge should produce: SELECT b@1 + a@0 AS c2, c@2 + 1 AS c1
3005        let merged = base_projection.try_merge(&top_projection)?;
3006        assert_snapshot!(format!("{merged}"), @"Projection[b@1 + a@0 AS c2, c@2 + 1 AS c1]");
3007
3008        Ok(())
3009    }
3010
3011    #[test]
3012    fn try_merge_error() {
3013        // Create a base projection
3014        let base = ProjectionExprs::new(vec![
3015            ProjectionExpr {
3016                expr: Arc::new(Column::new("a", 0)),
3017                alias: "x".to_string(),
3018            },
3019            ProjectionExpr {
3020                expr: Arc::new(Column::new("b", 1)),
3021                alias: "y".to_string(),
3022            },
3023        ]);
3024
3025        // Create a top projection that references a non-existent column index
3026        let top = ProjectionExprs::new(vec![ProjectionExpr {
3027            expr: Arc::new(Column::new("z", 5)), // Invalid index
3028            alias: "result".to_string(),
3029        }]);
3030
3031        // Attempt to merge and expect an error
3032        let err_msg = base.try_merge(&top).unwrap_err().to_string();
3033        assert!(
3034            err_msg.contains("Internal error: Column index 5 out of bounds for projected expressions of length 2"),
3035            "Unexpected error message: {err_msg}",
3036        );
3037    }
3038
3039    #[test]
3040    fn test_merge_empty_projection_with_literal() -> Result<()> {
3041        // This test reproduces the issue from roundtrip_empty_projection test
3042        // Query like: SELECT 1 FROM table
3043        // where the file scan needs no columns (empty projection)
3044        // but we project a literal on top
3045
3046        // Empty base projection (no columns needed from file)
3047        let base_projection = ProjectionExprs::new(vec![]);
3048
3049        // Top projection with a literal expression: SELECT 1
3050        let top_projection = ProjectionExprs::new(vec![ProjectionExpr {
3051            expr: Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
3052            alias: "Int64(1)".to_string(),
3053        }]);
3054
3055        // This should succeed - literals don't reference columns so they should
3056        // pass through unchanged when merged with an empty projection
3057        let merged = base_projection.try_merge(&top_projection)?;
3058        assert_snapshot!(format!("{merged}"), @"Projection[1 AS Int64(1)]");
3059
3060        Ok(())
3061    }
3062
3063    #[test]
3064    fn test_update_expr_with_literal() -> Result<()> {
3065        // Test that update_expr correctly handles expressions without column references
3066        let literal_expr: Arc<dyn PhysicalExpr> =
3067            Arc::new(Literal::new(ScalarValue::Int64(Some(42))));
3068        let empty_projection: Vec<ProjectionExpr> = vec![];
3069
3070        // Updating a literal with an empty projection should return the literal unchanged
3071        let result = update_expr(&literal_expr, &empty_projection, true)?;
3072        assert!(result.is_some(), "Literal expression should be valid");
3073
3074        let result_expr = result.unwrap();
3075        assert_eq!(
3076            result_expr.downcast_ref::<Literal>().unwrap().value(),
3077            &ScalarValue::Int64(Some(42))
3078        );
3079
3080        Ok(())
3081    }
3082
3083    #[test]
3084    fn test_update_expr_with_complex_literal_expr() -> Result<()> {
3085        // Test update_expr with an expression containing both literals and a column
3086        // This tests the case where we have: literal + column
3087        let expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
3088            Arc::new(Literal::new(ScalarValue::Int64(Some(10)))),
3089            Operator::Plus,
3090            Arc::new(Column::new("x", 0)),
3091        ));
3092
3093        // Base projection that maps column 0 to a different expression
3094        let base_projection = vec![ProjectionExpr {
3095            expr: Arc::new(Column::new("a", 5)),
3096            alias: "x".to_string(),
3097        }];
3098
3099        // The expression should be updated: 10 + x@0 becomes 10 + a@5
3100        let result = update_expr(&expr, &base_projection, true)?;
3101        assert!(result.is_some(), "Expression should be valid");
3102
3103        let result_expr = result.unwrap();
3104        let binary = result_expr
3105            .downcast_ref::<BinaryExpr>()
3106            .expect("Should be a BinaryExpr");
3107
3108        // Left side should still be the literal
3109        assert!(binary.left().downcast_ref::<Literal>().is_some());
3110
3111        // Right side should be updated to reference column at index 5
3112        let right_col = binary
3113            .right()
3114            .downcast_ref::<Column>()
3115            .expect("Right should be a Column");
3116        assert_eq!(right_col.index(), 5);
3117
3118        Ok(())
3119    }
3120
3121    #[test]
3122    fn test_project_schema_simple_columns() -> Result<()> {
3123        // Input schema: [col0: Int64, col1: Utf8, col2: Float32]
3124        let input_schema = get_schema();
3125
3126        // Projection: SELECT col2 AS c, col0 AS a
3127        let projection = ProjectionExprs::new(vec![
3128            ProjectionExpr {
3129                expr: Arc::new(Column::new("col2", 2)),
3130                alias: "c".to_string(),
3131            },
3132            ProjectionExpr {
3133                expr: Arc::new(Column::new("col0", 0)),
3134                alias: "a".to_string(),
3135            },
3136        ]);
3137
3138        let output_schema = projection.project_schema(&input_schema)?;
3139
3140        // Should have 2 fields
3141        assert_eq!(output_schema.fields().len(), 2);
3142
3143        // First field should be "c" with Float32 type
3144        assert_eq!(output_schema.field(0).name(), "c");
3145        assert_eq!(output_schema.field(0).data_type(), &DataType::Float32);
3146
3147        // Second field should be "a" with Int64 type
3148        assert_eq!(output_schema.field(1).name(), "a");
3149        assert_eq!(output_schema.field(1).data_type(), &DataType::Int64);
3150
3151        Ok(())
3152    }
3153
3154    #[test]
3155    fn test_project_schema_with_expressions() -> Result<()> {
3156        // Input schema: [col0: Int64, col1: Utf8, col2: Float32]
3157        let input_schema = get_schema();
3158
3159        // Projection: SELECT col0 + 1 AS incremented
3160        let projection = ProjectionExprs::new(vec![ProjectionExpr {
3161            expr: Arc::new(BinaryExpr::new(
3162                Arc::new(Column::new("col0", 0)),
3163                Operator::Plus,
3164                Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
3165            )),
3166            alias: "incremented".to_string(),
3167        }]);
3168
3169        let output_schema = projection.project_schema(&input_schema)?;
3170
3171        // Should have 1 field
3172        assert_eq!(output_schema.fields().len(), 1);
3173
3174        // Field should be "incremented" with Int64 type
3175        assert_eq!(output_schema.field(0).name(), "incremented");
3176        assert_eq!(output_schema.field(0).data_type(), &DataType::Int64);
3177
3178        Ok(())
3179    }
3180
3181    #[test]
3182    fn test_project_schema_preserves_metadata() -> Result<()> {
3183        // Create schema with metadata
3184        let mut metadata = HashMap::new();
3185        metadata.insert("key".to_string(), "value".to_string());
3186        let field_with_metadata =
3187            Field::new("col0", DataType::Int64, false).with_metadata(metadata.clone());
3188        let input_schema = Schema::new(vec![
3189            field_with_metadata,
3190            Field::new("col1", DataType::Utf8, false),
3191        ]);
3192
3193        // Projection: SELECT col0 AS renamed
3194        let projection = ProjectionExprs::new(vec![ProjectionExpr {
3195            expr: Arc::new(Column::new("col0", 0)),
3196            alias: "renamed".to_string(),
3197        }]);
3198
3199        let output_schema = projection.project_schema(&input_schema)?;
3200
3201        // Should have 1 field
3202        assert_eq!(output_schema.fields().len(), 1);
3203
3204        // Field should be "renamed" with metadata preserved
3205        assert_eq!(output_schema.field(0).name(), "renamed");
3206        assert_eq!(output_schema.field(0).metadata(), &metadata);
3207
3208        Ok(())
3209    }
3210
3211    #[test]
3212    fn test_project_schema_empty() -> Result<()> {
3213        let input_schema = get_schema();
3214        let projection = ProjectionExprs::new(vec![]);
3215
3216        let output_schema = projection.project_schema(&input_schema)?;
3217
3218        assert_eq!(output_schema.fields().len(), 0);
3219
3220        Ok(())
3221    }
3222
3223    #[test]
3224    fn test_project_statistics_columns_only() -> Result<()> {
3225        let input_stats = get_stats();
3226        let input_schema = get_schema();
3227
3228        // Projection: SELECT col1 AS text, col0 AS num
3229        let projection = ProjectionExprs::new(vec![
3230            ProjectionExpr {
3231                expr: Arc::new(Column::new("col1", 1)),
3232                alias: "text".to_string(),
3233            },
3234            ProjectionExpr {
3235                expr: Arc::new(Column::new("col0", 0)),
3236                alias: "num".to_string(),
3237            },
3238        ]);
3239
3240        let output_stats = projection.project_statistics(
3241            input_stats,
3242            &projection.project_schema(&input_schema)?,
3243        )?;
3244
3245        // Row count should be preserved
3246        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3247
3248        // Should have 2 column statistics (reordered from input)
3249        assert_eq!(output_stats.column_statistics.len(), 2);
3250
3251        // First column (col1 from input)
3252        assert_eq!(
3253            output_stats.column_statistics[0].distinct_count,
3254            Precision::Exact(1)
3255        );
3256        assert_eq!(
3257            output_stats.column_statistics[0].max_value,
3258            Precision::Exact(ScalarValue::from("x"))
3259        );
3260
3261        // Second column (col0 from input)
3262        assert_eq!(
3263            output_stats.column_statistics[1].distinct_count,
3264            Precision::Exact(5)
3265        );
3266        assert_eq!(
3267            output_stats.column_statistics[1].max_value,
3268            Precision::Exact(ScalarValue::Int64(Some(21)))
3269        );
3270
3271        Ok(())
3272    }
3273
3274    #[test]
3275    fn test_project_statistics_with_expressions() -> Result<()> {
3276        let input_stats = get_stats();
3277        let input_schema = get_schema();
3278
3279        // Projection with expression: SELECT col0 + 1 AS incremented, col1 AS text
3280        let projection = ProjectionExprs::new(vec![
3281            ProjectionExpr {
3282                expr: Arc::new(BinaryExpr::new(
3283                    Arc::new(Column::new("col0", 0)),
3284                    Operator::Plus,
3285                    Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
3286                )),
3287                alias: "incremented".to_string(),
3288            },
3289            ProjectionExpr {
3290                expr: Arc::new(Column::new("col1", 1)),
3291                alias: "text".to_string(),
3292            },
3293        ]);
3294
3295        let output_stats = projection.project_statistics(
3296            input_stats,
3297            &projection.project_schema(&input_schema)?,
3298        )?;
3299
3300        // Row count should be preserved
3301        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3302
3303        // Should have 2 column statistics
3304        assert_eq!(output_stats.column_statistics.len(), 2);
3305
3306        // First column (expression) should have unknown statistics
3307        assert_eq!(
3308            output_stats.column_statistics[0].distinct_count,
3309            Precision::Absent
3310        );
3311        assert_eq!(
3312            output_stats.column_statistics[0].max_value,
3313            Precision::Absent
3314        );
3315
3316        // Second column (col1) should preserve statistics
3317        assert_eq!(
3318            output_stats.column_statistics[1].distinct_count,
3319            Precision::Exact(1)
3320        );
3321
3322        Ok(())
3323    }
3324
3325    #[test]
3326    fn test_project_statistics_with_same_type_cast_is_exact_passthrough() -> Result<()> {
3327        // A cast to the column's own `DataType` (e.g. one that only re-stamps
3328        // nullability via `CastExpr::new_with_target_field`, as `UnionExec`/
3329        // `InterleaveExec` insert) never changes any value, so every
3330        // statistic -- not just min/max -- should carry over unchanged.
3331        let input_stats = get_stats();
3332        let col0_stats = input_stats.column_statistics[0].clone();
3333        let input_schema = get_schema();
3334
3335        let projection = ProjectionExprs::new(vec![ProjectionExpr {
3336            expr: Arc::new(CastExpr::new(
3337                Arc::new(Column::new("col0", 0)),
3338                DataType::Int64,
3339                None,
3340            )),
3341            alias: "casted".to_string(),
3342        }]);
3343
3344        let output_stats = projection.project_statistics(
3345            input_stats,
3346            &projection.project_schema(&input_schema)?,
3347        )?;
3348
3349        assert_eq!(output_stats.column_statistics[0], col0_stats);
3350
3351        Ok(())
3352    }
3353
3354    #[test]
3355    fn test_project_statistics_with_cast() -> Result<()> {
3356        let input_stats = get_stats();
3357        let input_schema = get_schema();
3358
3359        // SELECT CAST(col0 AS Int32) AS casted
3360        let projection = ProjectionExprs::new(vec![ProjectionExpr {
3361            expr: Arc::new(CastExpr::new(
3362                Arc::new(Column::new("col0", 0)),
3363                DataType::Int32,
3364                None,
3365            )),
3366            alias: "casted".to_string(),
3367        }]);
3368
3369        let output_stats = projection.project_statistics(
3370            input_stats,
3371            &projection.project_schema(&input_schema)?,
3372        )?;
3373
3374        assert_eq!(
3375            output_stats.column_statistics[0].min_value,
3376            Precision::Exact(ScalarValue::Int32(Some(-4)))
3377        );
3378        assert_eq!(
3379            output_stats.column_statistics[0].max_value,
3380            Precision::Exact(ScalarValue::Int32(Some(21)))
3381        );
3382
3383        Ok(())
3384    }
3385
3386    #[test]
3387    fn test_project_statistics_duplicate_column() -> Result<()> {
3388        let input_stats = get_stats();
3389        let col0 = input_stats.column_statistics[0].clone();
3390        let projection = ProjectionExprs::new([
3391            ProjectionExpr::new(Arc::new(Column::new("col0", 0)), "a"),
3392            ProjectionExpr::new(Arc::new(Column::new("col0", 0)), "b"),
3393        ]);
3394
3395        let output_schema = projection.project_schema(&get_schema())?;
3396        let output_stats = projection.project_statistics(input_stats, &output_schema)?;
3397
3398        assert_eq!(output_stats.column_statistics, vec![col0.clone(), col0]);
3399        Ok(())
3400    }
3401
3402    #[test]
3403    fn test_project_statistics_column_and_cast() -> Result<()> {
3404        let input_stats = get_stats();
3405        let col0 = input_stats.column_statistics[0].clone();
3406        let projection = ProjectionExprs::new([
3407            ProjectionExpr::new(Arc::new(Column::new("col0", 0)), "num"),
3408            ProjectionExpr::new(
3409                Arc::new(CastExpr::new(
3410                    Arc::new(Column::new("col0", 0)),
3411                    DataType::Int32,
3412                    None,
3413                )),
3414                "casted",
3415            ),
3416        ]);
3417
3418        let output_schema = projection.project_schema(&get_schema())?;
3419        let output_stats = projection.project_statistics(input_stats, &output_schema)?;
3420
3421        assert_eq!(output_stats.column_statistics[0], col0);
3422        assert_eq!(
3423            output_stats.column_statistics[1],
3424            ColumnStatistics {
3425                min_value: Precision::Exact(ScalarValue::Int32(Some(-4))),
3426                max_value: Precision::Exact(ScalarValue::Int32(Some(21))),
3427                distinct_count: Precision::Exact(5),
3428                null_count: Precision::Exact(0),
3429                sum_value: Precision::Absent,
3430                byte_size: Precision::Absent,
3431            }
3432        );
3433
3434        Ok(())
3435    }
3436
3437    #[test]
3438    fn test_project_statistics_missing_column_stats_are_unknown() -> Result<()> {
3439        let mut input_stats = get_stats();
3440        let input_schema = get_schema();
3441        input_stats.column_statistics.truncate(2);
3442
3443        // The schema has col2, but the statistics do not. This can happen for
3444        // source-provided virtual columns that are available at execution time
3445        // but not represented in file-level statistics.
3446        let projection = ProjectionExprs::new(vec![
3447            ProjectionExpr {
3448                expr: Arc::new(Column::new("col2", 2)),
3449                alias: "virtual_col".to_string(),
3450            },
3451            ProjectionExpr {
3452                expr: Arc::new(CastExpr::new(
3453                    Arc::new(Column::new("col2", 2)),
3454                    DataType::Float64,
3455                    None,
3456                )),
3457                alias: "casted_virtual_col".to_string(),
3458            },
3459            ProjectionExpr {
3460                expr: Arc::new(Column::new("col0", 0)),
3461                alias: "physical_col".to_string(),
3462            },
3463        ]);
3464
3465        let output_stats = projection.project_statistics(
3466            input_stats,
3467            &projection.project_schema(&input_schema)?,
3468        )?;
3469
3470        assert_eq!(output_stats.column_statistics.len(), 3);
3471        assert_eq!(
3472            output_stats.column_statistics[0],
3473            ColumnStatistics::new_unknown()
3474        );
3475        assert_eq!(
3476            output_stats.column_statistics[1],
3477            ColumnStatistics::new_unknown()
3478        );
3479        assert_eq!(
3480            output_stats.column_statistics[2].max_value,
3481            Precision::Exact(ScalarValue::Int64(Some(21)))
3482        );
3483
3484        Ok(())
3485    }
3486
3487    #[test]
3488    fn test_project_statistics_primitive_width_only() -> Result<()> {
3489        let input_stats = get_stats();
3490        let input_schema = get_schema();
3491
3492        // Projection with only primitive width columns: SELECT col2 AS f, col0 AS i
3493        let projection = ProjectionExprs::new(vec![
3494            ProjectionExpr {
3495                expr: Arc::new(Column::new("col2", 2)),
3496                alias: "f".to_string(),
3497            },
3498            ProjectionExpr {
3499                expr: Arc::new(Column::new("col0", 0)),
3500                alias: "i".to_string(),
3501            },
3502        ]);
3503
3504        let output_stats = projection.project_statistics(
3505            input_stats,
3506            &projection.project_schema(&input_schema)?,
3507        )?;
3508
3509        // Row count should be preserved
3510        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3511
3512        // Total byte size should be recalculated for primitive types
3513        // Float32 (4 bytes) + Int64 (8 bytes) = 12 bytes per row, 5 rows = 60 bytes
3514        assert_eq!(output_stats.total_byte_size, Precision::Exact(60));
3515
3516        // Should have 2 column statistics
3517        assert_eq!(output_stats.column_statistics.len(), 2);
3518
3519        Ok(())
3520    }
3521
3522    #[test]
3523    fn test_project_statistics_empty() -> Result<()> {
3524        let input_stats = get_stats();
3525        let input_schema = get_schema();
3526
3527        let projection = ProjectionExprs::new(vec![]);
3528
3529        let output_stats = projection.project_statistics(
3530            input_stats,
3531            &projection.project_schema(&input_schema)?,
3532        )?;
3533
3534        // Row count should be preserved
3535        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3536
3537        // Should have no column statistics
3538        assert_eq!(output_stats.column_statistics.len(), 0);
3539
3540        // Total byte size should be 0 for empty projection
3541        assert_eq!(output_stats.total_byte_size, Precision::Exact(0));
3542
3543        Ok(())
3544    }
3545
3546    // Test statistics calculation for non-null literal (numeric constant)
3547    #[test]
3548    fn test_project_statistics_with_literal() -> Result<()> {
3549        let input_stats = get_stats();
3550        let input_schema = get_schema();
3551
3552        // Projection with literal: SELECT 42 AS constant, col0 AS num
3553        let projection = ProjectionExprs::new(vec![
3554            ProjectionExpr {
3555                expr: Arc::new(Literal::new(ScalarValue::Int64(Some(42)))),
3556                alias: "constant".to_string(),
3557            },
3558            ProjectionExpr {
3559                expr: Arc::new(Column::new("col0", 0)),
3560                alias: "num".to_string(),
3561            },
3562        ]);
3563
3564        let output_stats = projection.project_statistics(
3565            input_stats,
3566            &projection.project_schema(&input_schema)?,
3567        )?;
3568
3569        // Row count should be preserved
3570        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3571
3572        // Should have 2 column statistics
3573        assert_eq!(output_stats.column_statistics.len(), 2);
3574
3575        // First column (literal 42) should have proper constant statistics
3576        assert_eq!(
3577            output_stats.column_statistics[0].min_value,
3578            Precision::Exact(ScalarValue::Int64(Some(42)))
3579        );
3580        assert_eq!(
3581            output_stats.column_statistics[0].max_value,
3582            Precision::Exact(ScalarValue::Int64(Some(42)))
3583        );
3584        assert_eq!(
3585            output_stats.column_statistics[0].distinct_count,
3586            Precision::Exact(1)
3587        );
3588        assert_eq!(
3589            output_stats.column_statistics[0].null_count,
3590            Precision::Exact(0)
3591        );
3592        // Int64 is 8 bytes, 5 rows = 40 bytes
3593        assert_eq!(
3594            output_stats.column_statistics[0].byte_size,
3595            Precision::Exact(40)
3596        );
3597        // For a constant column, sum_value = value * num_rows = 42 * 5 = 210
3598        assert_eq!(
3599            output_stats.column_statistics[0].sum_value,
3600            Precision::Exact(ScalarValue::Int64(Some(210)))
3601        );
3602
3603        // Second column (col0) should preserve statistics
3604        assert_eq!(
3605            output_stats.column_statistics[1].distinct_count,
3606            Precision::Exact(5)
3607        );
3608        assert_eq!(
3609            output_stats.column_statistics[1].max_value,
3610            Precision::Exact(ScalarValue::Int64(Some(21)))
3611        );
3612
3613        Ok(())
3614    }
3615
3616    #[test]
3617    fn test_project_statistics_with_i32_literal_sum_widens_to_i64() -> Result<()> {
3618        let input_stats = get_stats();
3619        let input_schema = get_schema();
3620
3621        let projection = ProjectionExprs::new(vec![
3622            ProjectionExpr {
3623                expr: Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
3624                alias: "constant".to_string(),
3625            },
3626            ProjectionExpr {
3627                expr: Arc::new(Column::new("col0", 0)),
3628                alias: "num".to_string(),
3629            },
3630        ]);
3631
3632        let output_stats = projection.project_statistics(
3633            input_stats,
3634            &projection.project_schema(&input_schema)?,
3635        )?;
3636
3637        assert_eq!(
3638            output_stats.column_statistics[0].sum_value,
3639            Precision::Exact(ScalarValue::Int64(Some(50)))
3640        );
3641
3642        Ok(())
3643    }
3644
3645    // Test statistics calculation for NULL literal (constant NULL column)
3646    #[test]
3647    fn test_project_statistics_with_null_literal() -> Result<()> {
3648        let input_stats = get_stats();
3649        let input_schema = get_schema();
3650
3651        // Projection with NULL literal: SELECT NULL AS null_col, col0 AS num
3652        let projection = ProjectionExprs::new(vec![
3653            ProjectionExpr {
3654                expr: Arc::new(Literal::new(ScalarValue::Int64(None))),
3655                alias: "null_col".to_string(),
3656            },
3657            ProjectionExpr {
3658                expr: Arc::new(Column::new("col0", 0)),
3659                alias: "num".to_string(),
3660            },
3661        ]);
3662
3663        let output_stats = projection.project_statistics(
3664            input_stats,
3665            &projection.project_schema(&input_schema)?,
3666        )?;
3667
3668        // Row count should be preserved
3669        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3670
3671        // Should have 2 column statistics
3672        assert_eq!(output_stats.column_statistics.len(), 2);
3673
3674        // First column (NULL literal) should have proper constant NULL statistics
3675        assert_eq!(
3676            output_stats.column_statistics[0].min_value,
3677            Precision::Exact(ScalarValue::Int64(None))
3678        );
3679        assert_eq!(
3680            output_stats.column_statistics[0].max_value,
3681            Precision::Exact(ScalarValue::Int64(None))
3682        );
3683        assert_eq!(
3684            output_stats.column_statistics[0].distinct_count,
3685            Precision::Exact(0) // NULLs are not counted as distinct values
3686        );
3687        assert_eq!(
3688            output_stats.column_statistics[0].null_count,
3689            Precision::Exact(5) // All rows are NULL
3690        );
3691        assert_eq!(
3692            output_stats.column_statistics[0].byte_size,
3693            Precision::Exact(0)
3694        );
3695        assert_eq!(
3696            output_stats.column_statistics[0].sum_value,
3697            Precision::Exact(ScalarValue::Int64(None))
3698        );
3699
3700        // Second column (col0) should preserve statistics
3701        assert_eq!(
3702            output_stats.column_statistics[1].distinct_count,
3703            Precision::Exact(5)
3704        );
3705        assert_eq!(
3706            output_stats.column_statistics[1].max_value,
3707            Precision::Exact(ScalarValue::Int64(Some(21)))
3708        );
3709
3710        Ok(())
3711    }
3712
3713    // A literal's distinct count depends on whether any row is present: an
3714    // estimated row count cannot prove the value appears. NULLs are not
3715    // counted as distinct values, matching `COUNT(DISTINCT)`.
3716    #[test]
3717    fn test_project_statistics_literal_distinct_count_by_row_count() -> Result<()> {
3718        let input_schema = get_schema();
3719        let projection = ProjectionExprs::new(vec![
3720            ProjectionExpr {
3721                expr: Arc::new(Literal::new(ScalarValue::Int64(Some(42)))),
3722                alias: "constant".to_string(),
3723            },
3724            ProjectionExpr {
3725                expr: Arc::new(Literal::new(ScalarValue::Int64(None))),
3726                alias: "null_col".to_string(),
3727            },
3728        ]);
3729        let output_schema = projection.project_schema(&input_schema)?;
3730
3731        let cases = [
3732            (Precision::Exact(0), Precision::Exact(0)),
3733            (Precision::Exact(5), Precision::Exact(1)),
3734            (Precision::Inexact(0), Precision::Inexact(0)),
3735            (Precision::Inexact(5), Precision::Inexact(1)),
3736            (Precision::Absent, Precision::Inexact(1)),
3737        ];
3738        for (num_rows, expected) in cases {
3739            let input_stats = Statistics {
3740                num_rows,
3741                total_byte_size: Precision::Absent,
3742                column_statistics: Statistics::unknown_column(&input_schema),
3743            };
3744            let output_stats =
3745                projection.project_statistics(input_stats, &output_schema)?;
3746            assert_eq!(
3747                output_stats.column_statistics[0].distinct_count, expected,
3748                "non-null literal, num_rows={num_rows:?}"
3749            );
3750            assert_eq!(
3751                output_stats.column_statistics[1].distinct_count,
3752                Precision::Exact(0),
3753                "NULL literal, num_rows={num_rows:?}"
3754            );
3755        }
3756
3757        Ok(())
3758    }
3759
3760    // Test statistics calculation for complex type literal (e.g., Utf8 string)
3761    #[test]
3762    fn test_project_statistics_with_complex_type_literal() -> Result<()> {
3763        let input_stats = get_stats();
3764        let input_schema = get_schema();
3765
3766        // Projection with Utf8 literal (complex type): SELECT 'hello' AS text, col0 AS num
3767        let projection = ProjectionExprs::new(vec![
3768            ProjectionExpr {
3769                expr: Arc::new(Literal::new(ScalarValue::Utf8(Some(
3770                    "hello".to_string(),
3771                )))),
3772                alias: "text".to_string(),
3773            },
3774            ProjectionExpr {
3775                expr: Arc::new(Column::new("col0", 0)),
3776                alias: "num".to_string(),
3777            },
3778        ]);
3779
3780        let output_stats = projection.project_statistics(
3781            input_stats,
3782            &projection.project_schema(&input_schema)?,
3783        )?;
3784
3785        // Row count should be preserved
3786        assert_eq!(output_stats.num_rows, Precision::Exact(5));
3787
3788        // Should have 2 column statistics
3789        assert_eq!(output_stats.column_statistics.len(), 2);
3790
3791        // First column (Utf8 literal 'hello') should have proper constant statistics
3792        // but byte_size should be Absent for complex types
3793        assert_eq!(
3794            output_stats.column_statistics[0].min_value,
3795            Precision::Exact(ScalarValue::Utf8(Some("hello".to_string())))
3796        );
3797        assert_eq!(
3798            output_stats.column_statistics[0].max_value,
3799            Precision::Exact(ScalarValue::Utf8(Some("hello".to_string())))
3800        );
3801        assert_eq!(
3802            output_stats.column_statistics[0].distinct_count,
3803            Precision::Exact(1)
3804        );
3805        assert_eq!(
3806            output_stats.column_statistics[0].null_count,
3807            Precision::Exact(0)
3808        );
3809        // Complex types (Utf8, List, etc.) should have byte_size = Absent
3810        // because we can't calculate exact size without knowing the actual data
3811        assert_eq!(
3812            output_stats.column_statistics[0].byte_size,
3813            Precision::Absent
3814        );
3815        // Non-numeric types (Utf8) should have sum_value = Absent
3816        // because sum is only meaningful for numeric types
3817        assert_eq!(
3818            output_stats.column_statistics[0].sum_value,
3819            Precision::Absent
3820        );
3821
3822        // Second column (col0) should preserve statistics
3823        assert_eq!(
3824            output_stats.column_statistics[1].distinct_count,
3825            Precision::Exact(5)
3826        );
3827        assert_eq!(
3828            output_stats.column_statistics[1].max_value,
3829            Precision::Exact(ScalarValue::Int64(Some(21)))
3830        );
3831
3832        Ok(())
3833    }
3834}