1use 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#[derive(Debug, Clone)]
43pub struct ProjectionExpr {
44 pub expr: Arc<dyn PhysicalExpr>,
46 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
59impl 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 pub fn new(expr: Arc<dyn PhysicalExpr>, alias: impl Into<String>) -> Self {
80 let alias = alias.into();
81 Self { expr, alias }
82 }
83
84 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#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct ProjectionExprs {
125 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 pub fn new(exprs: impl IntoIterator<Item = ProjectionExpr>) -> Self {
169 Self {
170 exprs: exprs.into_iter().collect(),
171 }
172 }
173
174 pub fn from_expressions(exprs: impl Into<Arc<[ProjectionExpr]>>) -> Self {
176 Self {
177 exprs: exprs.into(),
178 }
179 }
180
181 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 pub fn iter(&self) -> impl Iterator<Item = &ProjectionExpr> {
238 self.exprs.iter()
239 }
240
241 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 pub fn expr_iter(&self) -> impl Iterator<Item = Arc<dyn PhysicalExpr>> + '_ {
256 self.exprs.iter().map(|e| Arc::clone(&e.expr))
257 }
258
259 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 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 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 #[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 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 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 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 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 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 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 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 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 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 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
856fn 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 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 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
940fn 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#[derive(Clone, Debug)]
985pub struct Projector {
986 projection: ProjectionExprs,
987 output_schema: SchemaRef,
988 expression_metrics: Option<ExpressionEvaluatorMetrics>,
990}
991
992impl Projector {
993 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 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
1049pub type ProjectionRef = Arc<[usize]>;
1054
1055pub 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
1097pub 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 Unchanged,
1151 RewrittenValid,
1153 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 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 state = RewriteState::RewrittenInvalid;
1192 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 RewriteState::Unchanged | RewriteState::RewrittenValid => Ok(Some(new_expr)),
1222 }
1223}
1224
1225#[derive(Clone, Debug, Default)]
1228pub struct ProjectionTargets {
1229 exprs_indices: Vec<(Arc<dyn PhysicalExpr>, usize)>,
1233}
1234
1235impl ProjectionTargets {
1236 pub fn first(&self) -> &(Arc<dyn PhysicalExpr>, usize) {
1238 self.exprs_indices.first().unwrap()
1240 }
1241
1242 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#[derive(Clone, Debug)]
1265pub struct ProjectionMapping {
1266 map: IndexMap<Arc<dyn PhysicalExpr>, ProjectionTargets>,
1269}
1270
1271impl ProjectionMapping {
1272 pub fn try_new(
1286 expr: impl IntoIterator<Item = (Arc<dyn PhysicalExpr>, String)>,
1287 input_schema: &SchemaRef,
1288 ) -> Result<Self> {
1289 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 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 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 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 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 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
1411pub 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
1436pub 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 Ok(Transformed::yes(Arc::new(Column::new(name, idx))))
1480 } else {
1481 plan_err!("")
1484 }
1485 });
1486
1487 match transformed {
1488 Ok(transformed) => {
1489 projected_exprs.push(PhysicalSortExpr::new(transformed.data, *options));
1490 }
1491 Err(_) => {
1492 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 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 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 (
1594 vec![
1596 vec![(col_b, option_asc)],
1598 ],
1599 vec![(col_b, "b_new".to_string()), (col_a, "a_new".to_string())],
1601 vec![
1603 vec![("b_new", option_asc)],
1605 ],
1606 ),
1607 (
1609 vec![
1611 ],
1613 vec![(col_c, "c_new".to_string()), (col_b, "b_new".to_string())],
1615 vec![
1617 ],
1619 ),
1620 (
1622 vec![
1624 vec![(col_ts, option_asc)],
1626 ],
1627 vec![
1629 (col_b, "b_new".to_string()),
1630 (col_a, "a_new".to_string()),
1631 (col_ts, "ts_new".to_string()),
1632 ],
1633 vec![
1635 vec![("ts_new", option_asc)],
1637 ],
1638 ),
1639 (
1641 vec![
1643 vec![(col_a, option_asc), (col_ts, option_asc)],
1645 vec![(col_b, option_asc), (col_ts, option_asc)],
1647 ],
1648 vec![
1650 (col_b, "b_new".to_string()),
1651 (col_a, "a_new".to_string()),
1652 (col_ts, "ts_new".to_string()),
1653 ],
1654 vec![
1656 vec![("a_new", option_asc), ("ts_new", option_asc)],
1658 vec![("b_new", option_asc), ("ts_new", option_asc)],
1660 ],
1661 ),
1662 (
1664 vec![
1666 vec![(&a_plus_b, option_asc)],
1668 ],
1669 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 vec![
1677 vec![("a+b", option_asc)],
1679 ],
1680 ),
1681 (
1683 vec![
1685 vec![(&a_plus_b, option_asc), (col_c, option_asc)],
1687 ],
1688 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 vec![
1697 vec![("a+b", option_asc), ("c_new", option_asc)],
1699 ],
1700 ),
1701 (
1703 vec![
1704 vec![(col_a, option_asc), (col_b, option_asc)],
1706 vec![(col_a, option_asc), (col_d, option_asc)],
1708 ],
1709 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 vec![
1718 vec![("a_new", option_asc), ("b_new", option_asc)],
1720 vec![("a_new", option_asc), ("d_new", option_asc)],
1722 ],
1723 ),
1724 (
1726 vec![
1728 vec![(&b_plus_d, option_asc)],
1730 ],
1731 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 vec![
1740 vec![("b+d", option_asc)],
1742 ],
1743 ),
1744 (
1746 vec![
1748 vec![
1750 (col_a, option_asc),
1751 (col_d, option_asc),
1752 (col_b, option_asc),
1753 ],
1754 vec![(col_c, option_asc)],
1756 ],
1757 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 vec![
1766 vec![
1768 ("a_new", option_asc),
1769 ("d_new", option_asc),
1770 ("b_new", option_asc),
1771 ],
1772 vec![("c_new", option_asc)],
1774 ],
1775 ),
1776 (
1778 vec![
1779 vec![
1781 (col_a, option_asc),
1782 (col_b, option_asc),
1783 (col_c, option_asc),
1784 ],
1785 vec![(col_a, option_asc), (col_d, option_asc)],
1787 ],
1788 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 vec![
1797 vec![
1799 ("a_new", option_asc),
1800 ("b_new", option_asc),
1801 ("c_new", option_asc),
1802 ],
1803 ],
1804 ),
1805 (
1807 vec![
1809 vec![(col_a, option_asc), (col_b, option_asc)],
1811 vec![(col_a, option_asc), (col_d, option_asc)],
1813 ],
1814 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 vec![
1822 vec![("a_new", option_asc), ("b_new", option_asc)],
1824 ],
1825 ),
1826 (
1828 vec![
1830 vec![
1832 (col_a, option_asc),
1833 (col_b, option_asc),
1834 (col_c, option_asc),
1835 ],
1836 ],
1837 vec![(col_c, "c_new".to_string()), (col_a, "a_new".to_string())],
1839 vec![
1841 vec![("a_new", option_asc)],
1843 ],
1844 ),
1845 (
1847 vec![
1849 vec![
1851 (col_a, option_asc),
1852 (col_b, option_asc),
1853 (col_c, option_asc),
1854 ],
1855 vec![
1857 (col_a, option_asc),
1858 (&a_plus_b, option_asc),
1859 (col_c, option_asc),
1860 ],
1861 ],
1862 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 vec![
1871 vec![
1873 ("a_new", option_asc),
1874 ("b_new", option_asc),
1875 ("c_new", option_asc),
1876 ],
1877 vec![
1879 ("a_new", option_asc),
1880 ("a+b", option_asc),
1881 ("c_new", option_asc),
1882 ],
1883 ],
1884 ),
1885 (
1887 vec![
1889 vec![(col_a, option_asc), (col_b, option_asc)],
1891 vec![(col_c, option_asc), (col_b, option_asc)],
1893 vec![(col_d, option_asc), (col_e, option_asc)],
1895 ],
1896 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 vec![
1905 vec![("a_new", option_asc)],
1907 vec![("c_new", option_asc)],
1909 vec![("d_new", option_asc)],
1911 ],
1912 ),
1913 (
1915 vec![
1917 vec![
1919 (col_a, option_asc),
1920 (col_c, option_asc),
1921 (col_b, option_asc),
1922 ],
1923 ],
1924 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 vec![
1932 vec![("a_new", option_asc), ("c_new", option_asc)],
1934 ],
1935 ),
1936 (
1938 vec![
1940 vec![(col_a, option_asc), (col_b, option_asc)],
1942 vec![(col_c, option_asc), (col_b, option_desc)],
1944 vec![(col_e, option_asc)],
1946 ],
1947 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 vec![
1956 vec![("a_new", option_asc), ("b_new", option_asc)],
1958 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 (
2064 vec![
2066 vec![(col_a, option_asc)],
2068 ],
2069 vec![
2071 vec![(col_a_new, option_asc)],
2073 ],
2074 ),
2075 (
2077 vec![
2079 vec![(&a_plus_b, option_asc)],
2081 ],
2082 vec![
2084 vec![(&a_new_plus_b_new, option_asc)],
2086 ],
2087 ),
2088 (
2090 vec![
2092 vec![(col_a, option_asc), (col_ts, option_asc)],
2094 ],
2095 vec![
2097 vec![(col_a_new, option_asc)],
2099 ],
2100 ),
2101 (
2103 vec![
2105 vec![
2107 (col_a, option_asc),
2108 (col_ts, option_asc),
2109 (col_b, option_asc),
2110 ],
2111 ],
2112 vec![
2114 vec![(col_a_new, option_asc)],
2116 ],
2117 ),
2118 (
2120 vec![
2122 vec![(col_a, option_asc), (col_c, option_asc)],
2124 ],
2125 vec![
2127 vec![(col_a_new, option_asc), (col_round_c_res, option_asc)],
2129 vec![(col_a_new, option_asc), (col_c_new, option_asc)],
2131 ],
2132 ),
2133 (
2135 vec![
2137 vec![(col_c, option_asc), (col_b, option_asc)],
2139 ],
2140 vec![
2142 vec![(col_round_c_res, option_asc)],
2144 vec![(col_c_new, option_asc), (col_b_new, option_asc)],
2146 ],
2147 ),
2148 (
2150 vec![
2152 vec![(&a_plus_b, option_asc), (col_c, option_asc)],
2154 ],
2155 vec![
2157 vec![
2159 (&a_new_plus_b_new, option_asc),
2160 (col_round_c_res, option_asc),
2161 ],
2162 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 (
2236 vec![
2238 vec![(col_d, option_asc), (col_b, option_asc)],
2240 vec![(col_c, option_asc), (col_a, option_asc)],
2242 ],
2243 vec![],
2245 vec![
2247 vec![(col_c_new, option_asc)],
2249 vec![(col_d_new, option_asc)],
2251 ],
2252 ),
2253 (
2255 vec![
2257 vec![(col_d, option_asc), (col_b, option_asc)],
2259 vec![(col_c, option_asc), (col_e, option_asc)],
2261 ],
2262 vec![(col_e, col_a)],
2264 vec![
2266 vec![(col_c_new, option_asc)],
2268 vec![(col_d_new, option_asc)],
2270 ],
2271 ),
2272 (
2274 vec![
2276 vec![(col_d, option_asc), (col_b, option_asc)],
2278 vec![(col_c, option_asc), (col_e, option_asc)],
2280 ],
2281 vec![(col_a, col_f)],
2283 vec![
2285 vec![(col_d_new, option_asc)],
2287 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 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 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 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 #[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 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 assert_eq!(projection.column_indices(), vec![0, 2, 5]);
2854 Ok(())
2855 }
2856
2857 #[test]
2858 fn test_column_indices_duplicates() -> Result<()> {
2859 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)), 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 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 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 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 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 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 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 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 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 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 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 let top = ProjectionExprs::new(vec![ProjectionExpr {
3027 expr: Arc::new(Column::new("z", 5)), alias: "result".to_string(),
3029 }]);
3030
3031 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 let base_projection = ProjectionExprs::new(vec![]);
3048
3049 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 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 let literal_expr: Arc<dyn PhysicalExpr> =
3067 Arc::new(Literal::new(ScalarValue::Int64(Some(42))));
3068 let empty_projection: Vec<ProjectionExpr> = vec![];
3069
3070 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 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 let base_projection = vec![ProjectionExpr {
3095 expr: Arc::new(Column::new("a", 5)),
3096 alias: "x".to_string(),
3097 }];
3098
3099 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 assert!(binary.left().downcast_ref::<Literal>().is_some());
3110
3111 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 let input_schema = get_schema();
3125
3126 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 assert_eq!(output_schema.fields().len(), 2);
3142
3143 assert_eq!(output_schema.field(0).name(), "c");
3145 assert_eq!(output_schema.field(0).data_type(), &DataType::Float32);
3146
3147 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 let input_schema = get_schema();
3158
3159 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 assert_eq!(output_schema.fields().len(), 1);
3173
3174 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 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 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 assert_eq!(output_schema.fields().len(), 1);
3203
3204 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 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3247
3248 assert_eq!(output_stats.column_statistics.len(), 2);
3250
3251 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 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 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3302
3303 assert_eq!(output_stats.column_statistics.len(), 2);
3305
3306 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 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 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 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 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 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3511
3512 assert_eq!(output_stats.total_byte_size, Precision::Exact(60));
3515
3516 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3536
3537 assert_eq!(output_stats.column_statistics.len(), 0);
3539
3540 assert_eq!(output_stats.total_byte_size, Precision::Exact(0));
3542
3543 Ok(())
3544 }
3545
3546 #[test]
3548 fn test_project_statistics_with_literal() -> Result<()> {
3549 let input_stats = get_stats();
3550 let input_schema = get_schema();
3551
3552 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3571
3572 assert_eq!(output_stats.column_statistics.len(), 2);
3574
3575 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 assert_eq!(
3594 output_stats.column_statistics[0].byte_size,
3595 Precision::Exact(40)
3596 );
3597 assert_eq!(
3599 output_stats.column_statistics[0].sum_value,
3600 Precision::Exact(ScalarValue::Int64(Some(210)))
3601 );
3602
3603 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]
3647 fn test_project_statistics_with_null_literal() -> Result<()> {
3648 let input_stats = get_stats();
3649 let input_schema = get_schema();
3650
3651 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3670
3671 assert_eq!(output_stats.column_statistics.len(), 2);
3673
3674 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) );
3687 assert_eq!(
3688 output_stats.column_statistics[0].null_count,
3689 Precision::Exact(5) );
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 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 #[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]
3762 fn test_project_statistics_with_complex_type_literal() -> Result<()> {
3763 let input_stats = get_stats();
3764 let input_schema = get_schema();
3765
3766 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 assert_eq!(output_stats.num_rows, Precision::Exact(5));
3787
3788 assert_eq!(output_stats.column_statistics.len(), 2);
3790
3791 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 assert_eq!(
3812 output_stats.column_statistics[0].byte_size,
3813 Precision::Absent
3814 );
3815 assert_eq!(
3818 output_stats.column_statistics[0].sum_value,
3819 Precision::Absent
3820 );
3821
3822 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}