Skip to main content

query/dist_plan/analyzer/
utils.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
16use std::sync::Arc;
17
18use arrow::array::ArrayRef;
19use arrow_schema::{ArrowError, DataType};
20use chrono::{DateTime, Utc};
21use datafusion::common::alias::AliasGenerator;
22use datafusion::config::ConfigOptions;
23use datafusion::error::Result as DfResult;
24use datafusion_common::Column;
25use datafusion_common::tree_node::{Transformed, TreeNode as _, TreeNodeRewriter};
26use datafusion_expr::expr::Alias;
27use datafusion_expr::{Expr, Extension, LogicalPlan};
28use datafusion_optimizer::simplify_expressions::SimplifyExpressions;
29use datafusion_optimizer::{OptimizerConfig, OptimizerRule as _};
30
31use crate::dist_plan::merge_sort::MergeSortLogicalPlan;
32use crate::plan::ExtractExpr as _;
33
34/// The `ConstEvaluator` in `SimplifyExpressions` might evaluate some UDFs early in the
35/// planning stage, by executing them directly. For example, the `database()` function.
36/// So the `ConfigOptions` here (which is set from the session context) should be present
37/// in the UDF's `ScalarFunctionArgs`. However, the default implementation in DataFusion
38/// seems to lost track on it: the `ConfigOptions` is recreated with its default values again.
39/// So we create a custom `OptimizerConfig` with the desired `ConfigOptions`
40/// to walk around the issue.
41/// TODO(LFC): Maybe use DataFusion's `OptimizerContext` again
42///   once https://github.com/apache/datafusion/pull/17742 is merged.
43pub(crate) struct PatchOptimizerContext {
44    pub(crate) inner: datafusion_optimizer::OptimizerContext,
45    pub(crate) config: Arc<ConfigOptions>,
46    /// Override for `query_execution_start_time()` — used during scheduled Flow
47    /// evaluation so that `SimplifyExpressions` does not constant-fold `now()`
48    /// into wall-clock literals.  When `None`, falls back to the inner context.
49    pub(crate) scheduled_time: Option<DateTime<Utc>>,
50}
51
52impl OptimizerConfig for PatchOptimizerContext {
53    fn query_execution_start_time(&self) -> Option<DateTime<Utc>> {
54        self.scheduled_time
55            .or_else(|| self.inner.query_execution_start_time())
56    }
57
58    fn alias_generator(&self) -> &Arc<AliasGenerator> {
59        self.inner.alias_generator()
60    }
61
62    fn options(&self) -> Arc<ConfigOptions> {
63        self.config.clone()
64    }
65}
66
67/// Simplify all expressions recursively in the plan tree
68/// which keeping the output schema unchanged
69pub(crate) struct PlanTreeExpressionSimplifier {
70    optimizer_context: PatchOptimizerContext,
71}
72
73impl PlanTreeExpressionSimplifier {
74    pub fn new(optimizer_context: PatchOptimizerContext) -> Self {
75        Self { optimizer_context }
76    }
77}
78
79impl TreeNodeRewriter for PlanTreeExpressionSimplifier {
80    type Node = LogicalPlan;
81    fn f_down(&mut self, plan: Self::Node) -> DfResult<Transformed<Self::Node>> {
82        let simp = SimplifyExpressions::new()
83            .rewrite(plan, &self.optimizer_context)?
84            .data;
85        Ok(Transformed::yes(simp))
86    }
87}
88
89/// A patch for substrait simply throw timezone away, so when decoding, if columns have different timezone then expected schema, use expected schema's timezone
90pub fn patch_batch_timezone(
91    expected_schema: arrow_schema::SchemaRef,
92    columns: Vec<ArrayRef>,
93) -> Result<arrow::record_batch::RecordBatch, ArrowError> {
94    let patched_columns: Vec<ArrayRef> = expected_schema
95        .fields()
96        .iter()
97        .zip(columns)
98        .map(|(expected_field, column)| {
99            let expected_type = expected_field.data_type();
100            let actual_type = column.data_type();
101
102            // Check if both are timestamp types with different timezones
103            match (expected_type, actual_type) {
104                (
105                    DataType::Timestamp(expected_unit, expected_tz),
106                    DataType::Timestamp(actual_unit, actual_tz),
107                ) if expected_unit == actual_unit && expected_tz != actual_tz => {
108                    // Cast the column to the expected timezone
109                    arrow::compute::cast(&column, expected_type)
110                }
111                _ => Ok(column),
112            }
113        })
114        .collect::<Result<Vec<_>, _>>()?;
115
116    arrow::record_batch::RecordBatch::try_new(expected_schema.clone(), patched_columns)
117}
118
119fn rewrite_column(
120    mapping: &BTreeMap<Column, BTreeSet<Column>>,
121    original_node: &LogicalPlan,
122    alias_node: &LogicalPlan,
123) -> impl Fn(Expr) -> DfResult<Transformed<Expr>> {
124    move |e: Expr| {
125        if let Expr::Column(col) = e {
126            if let Some(aliased_cols) = mapping.get(&col) {
127                // if multiple alias is available, just use first one
128                if let Some(aliased_col) = aliased_cols.iter().next() {
129                    Ok(Transformed::yes(Expr::Column(aliased_col.clone())))
130                } else {
131                    Err(datafusion_common::DataFusionError::Internal(format!(
132                        "PlanRewriter: expand: column {col} from {original_node}\n has empty alias set in plan: {alias_node}\n but expect at least one alias",
133                    )))
134                }
135            } else {
136                Err(datafusion_common::DataFusionError::Internal(format!(
137                    "PlanRewriter: expand: column {col} from {original_node}\n has no alias in plan: {alias_node}",
138                )))
139            }
140        } else {
141            Ok(Transformed::no(e))
142        }
143    }
144}
145
146/// Rewrite the expressions of the given merge sort plan from original columns(at merge sort's input plan) to aliased columns at the given aliased node
147pub fn rewrite_merge_sort_exprs(
148    merge_sort: &MergeSortLogicalPlan,
149    aliased_node: &LogicalPlan,
150) -> DfResult<LogicalPlan> {
151    let merge_sort = LogicalPlan::Extension(Extension {
152        node: Arc::new(merge_sort.clone()),
153    });
154
155    // tracking alias for sort exprs,
156    let sort_input = merge_sort.inputs().first().cloned().ok_or_else(|| {
157        datafusion_common::DataFusionError::Internal(format!(
158            "PlanRewriter: expand: merge sort stage has no input: {merge_sort}"
159        ))
160    })?;
161    let sort_exprs = merge_sort.expressions_consider_join();
162    let column_refs = sort_exprs
163        .iter()
164        .flat_map(|e| e.column_refs().into_iter().cloned())
165        .collect::<BTreeSet<_>>();
166    let column_alias_mapping = aliased_columns_for(&column_refs, aliased_node, Some(sort_input))?;
167    let aliased_sort_exprs = sort_exprs
168        .into_iter()
169        .map(|e| {
170            e.transform(rewrite_column(
171                &column_alias_mapping,
172                &merge_sort,
173                aliased_node,
174            ))
175        })
176        .map(|e| e.map(|e| e.data))
177        .collect::<DfResult<Vec<_>>>()?;
178    let new_merge_sort = merge_sort.with_new_exprs(
179        aliased_sort_exprs,
180        merge_sort.inputs().into_iter().cloned().collect(),
181    )?;
182    Ok(new_merge_sort)
183}
184
185/// Return all the aliased columns(at aliased node) for the given original columns(at original node)
186///
187/// if `original_node` is None, it means original columns are from leaf node
188///
189/// Return value use `BTreeMap` to have deterministic order for choose first alias when multiple alias exist
190pub fn aliased_columns_for(
191    original_columns: &BTreeSet<Column>,
192    aliased_node: &LogicalPlan,
193    original_node: Option<&LogicalPlan>,
194) -> DfResult<BTreeMap<Column, BTreeSet<Column>>> {
195    let initial_aliases: BTreeMap<Column, BTreeSet<Column>> = {
196        if let Some(original) = &original_node {
197            let schema_cols: BTreeSet<Column> = original.schema().columns().into_iter().collect();
198            original_columns
199                .iter()
200                .filter(|c| schema_cols.contains(c))
201                .map(|c| (c.clone(), [c.clone()].into()))
202                .collect()
203        } else {
204            original_columns
205                .iter()
206                .map(|c| (c.clone(), [c.clone()].into()))
207                .collect()
208        }
209    };
210
211    if initial_aliases.is_empty() {
212        return Ok(BTreeMap::new());
213    }
214
215    aliased_columns_for_inner(initial_aliases, aliased_node, original_node)
216}
217
218fn aliased_columns_for_inner(
219    cur_aliases: BTreeMap<Column, BTreeSet<Column>>,
220    node: &LogicalPlan,
221    original_node: Option<&LogicalPlan>,
222) -> DfResult<BTreeMap<Column, BTreeSet<Column>>> {
223    // First, collect the path from current node to the target node
224    let mut path = Vec::new();
225    let mut current_node = node;
226
227    // Descend to the target node, collecting nodes along the way
228    loop {
229        // Base case: check if we've reached the target node
230        if let Some(original_node) = original_node
231            && *current_node == *original_node
232        {
233            break;
234        } else if current_node.inputs().is_empty() {
235            // leaf node reached
236            break;
237        }
238
239        // Validate node has exactly one child
240        if current_node.inputs().len() != 1 {
241            return Err(datafusion::error::DataFusionError::Internal(format!(
242                "only accept plan with at most one child, found: {}",
243                current_node
244            )));
245        }
246
247        // Add current node to path and move to child
248        path.push(current_node);
249        current_node = current_node.inputs()[0];
250    }
251
252    // Now apply alias layers in reverse order (from original to aliased)
253    let mut result = cur_aliases;
254    for &node_in_path in path.iter().rev() {
255        let layer = get_alias_layer_from_node(node_in_path)?;
256        let mut new_aliases = BTreeMap::new();
257        for (original_column, cur_alias_set) in result {
258            let mut new_alias_set = BTreeSet::new();
259            for cur_alias in cur_alias_set {
260                new_alias_set.extend(layer.get_new_from_old(cur_alias.clone()));
261            }
262            if !new_alias_set.is_empty() {
263                new_aliases.insert(original_column, new_alias_set);
264            }
265        }
266        result = new_aliases;
267    }
268
269    Ok(result)
270}
271
272/// Return a mapping of original column to all the aliased columns in current node of the plan
273/// TODO(discord9): also support merge scan node
274fn get_alias_layer_from_node(node: &LogicalPlan) -> DfResult<AliasLayer> {
275    match node {
276        LogicalPlan::Projection(proj) => Ok(get_alias_layer_from_exprs(&proj.expr)),
277        LogicalPlan::Aggregate(aggr) => Ok(get_alias_layer_from_exprs(&aggr.group_expr)),
278        LogicalPlan::SubqueryAlias(subquery_alias) => {
279            let mut layer = AliasLayer::default();
280            let old_columns = subquery_alias.input.schema().columns();
281            for old_column in old_columns {
282                let new_column = Column::new(
283                    Some(subquery_alias.alias.clone()),
284                    old_column.name().to_string(),
285                );
286                // mapping from old_column to new_column
287                layer.insert_alias(old_column, [new_column].into());
288            }
289            Ok(layer)
290        }
291        LogicalPlan::TableScan(scan) => {
292            let columns = scan.projected_schema.columns();
293            let mut layer = AliasLayer::default();
294            for col in columns {
295                layer.insert_alias(col.clone(), [col.clone()].into());
296            }
297            Ok(layer)
298        }
299        _ => {
300            let input_schema = node
301                .inputs()
302                .first()
303                .ok_or_else(|| {
304                    datafusion::error::DataFusionError::Internal(format!(
305                        "only accept plan with at most one child, found: {}",
306                        node
307                    ))
308                })?
309                .schema();
310            let output_schema = node.schema();
311            // only accept at most one child plan, and if not one of the above nodes,
312            // also shouldn't modify the schema or else alias scope tracker can't support them
313            if node.inputs().len() > 1 {
314                Err(datafusion::error::DataFusionError::Internal(format!(
315                    "only accept plan with at most one child, found: {}",
316                    node
317                )))
318            } else if node.inputs().len() == 1 {
319                if input_schema != output_schema {
320                    let input_columns = input_schema.columns();
321                    let all_input_is_in_output = input_columns
322                        .iter()
323                        .all(|c| output_schema.is_column_from_schema(c));
324                    if all_input_is_in_output {
325                        // all input is in output, so it's just adding some columns, we can do identity mapping for input columns
326                        let mut layer = AliasLayer::default();
327                        for col in input_columns {
328                            layer.insert_alias(col.clone(), [col.clone()].into());
329                        }
330                        Ok(layer)
331                    } else {
332                        // otherwise use the intersection of input and output
333                        // TODO(discord9): maybe just make this case unsupported for now?
334                        common_telemetry::debug!(
335                            "Might be unsupported plan for alias tracking, track alias anyway: {}",
336                            node
337                        );
338                        let input_columns = input_schema.columns();
339                        let output_columns =
340                            output_schema.columns().into_iter().collect::<HashSet<_>>();
341                        let common_columns: HashSet<Column> = input_columns
342                            .iter()
343                            .filter(|c| output_columns.contains(c))
344                            .cloned()
345                            .collect();
346
347                        let mut layer = AliasLayer::default();
348                        for col in &common_columns {
349                            layer.insert_alias(col.clone(), [col.clone()].into());
350                        }
351                        Ok(layer)
352                    }
353                } else {
354                    // identity mapping
355                    let mut layer = AliasLayer::default();
356                    for col in output_schema.columns() {
357                        layer.insert_alias(col.clone(), [col.clone()].into());
358                    }
359                    Ok(layer)
360                }
361            } else {
362                // unknown plan with no input, error msg
363                Err(datafusion::error::DataFusionError::Internal(format!(
364                    "Unsupported plan with no input: {}",
365                    node
366                )))
367            }
368        }
369    }
370}
371
372fn get_alias_layer_from_exprs(exprs: &[Expr]) -> AliasLayer {
373    let mut alias_mapping: HashMap<Column, HashSet<Column>> = HashMap::new();
374    for expr in exprs {
375        if let Expr::Alias(alias) = expr {
376            if let Some(column) = get_alias_original_column(alias) {
377                alias_mapping
378                    .entry(column.clone())
379                    .or_default()
380                    .insert(Column::new(alias.relation.clone(), alias.name.clone()));
381            }
382        } else if let Expr::Column(column) = expr {
383            // identity mapping
384            alias_mapping
385                .entry(column.clone())
386                .or_default()
387                .insert(column.clone());
388        }
389    }
390    let mut layer = AliasLayer::default();
391    for (old_column, new_columns) in alias_mapping {
392        layer.insert_alias(old_column, new_columns);
393    }
394    layer
395}
396
397#[derive(Default, Debug, Clone)]
398struct AliasLayer {
399    /// for convenient of querying, key is field's name
400    old_to_new: BTreeMap<Column, HashSet<Column>>,
401}
402
403impl AliasLayer {
404    pub fn insert_alias(&mut self, old_column: Column, new_columns: HashSet<Column>) {
405        self.old_to_new
406            .entry(old_column)
407            .or_default()
408            .extend(new_columns);
409    }
410
411    pub fn get_new_from_old(&self, old_column: Column) -> HashSet<Column> {
412        let mut res_cols = HashSet::new();
413        for (old, new_cols) in self.old_to_new.iter() {
414            if old.name() == old_column.name() {
415                match (&old.relation, &old_column.relation) {
416                    (Some(o), Some(c)) => {
417                        if o.resolved_eq(c) {
418                            res_cols.extend(new_cols.clone());
419                        }
420                    }
421                    _ => {
422                        // if any of the two relation is None, meaning not fully qualified, just match name
423                        res_cols.extend(new_cols.clone());
424                    }
425                }
426            }
427        }
428        res_cols
429    }
430}
431
432fn get_alias_original_column(alias: &Alias) -> Option<Column> {
433    let mut cur_alias = alias;
434    while let Expr::Alias(inner_alias) = cur_alias.expr.as_ref() {
435        cur_alias = inner_alias;
436    }
437    if let Expr::Column(column) = cur_alias.expr.as_ref() {
438        return Some(column.clone());
439    }
440
441    None
442}
443
444/// Mapping of original column in table to all the alias at current node
445pub type AliasMapping = BTreeMap<String, BTreeSet<Column>>;
446
447#[cfg(test)]
448mod tests {
449    use std::sync::Arc;
450
451    use common_telemetry::init_default_ut_logging;
452    use datafusion::datasource::DefaultTableSource;
453    use datafusion::functions_aggregate::min_max::{max, min};
454    use datafusion_expr::{LogicalPlanBuilder, col};
455    use pretty_assertions::assert_eq;
456    use table::table::adapter::DfTableProviderAdapter;
457
458    use super::*;
459    use crate::dist_plan::analyzer::test::TestTable;
460
461    fn qcol(name: &str) -> Column {
462        Column::from_qualified_name(name)
463    }
464
465    #[test]
466    fn proj_multi_layered_alias_tracker() {
467        // use logging for better debugging
468        init_default_ut_logging();
469        let test_table = TestTable::table_with_name(0, "t".to_string());
470        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
471            DfTableProviderAdapter::new(test_table),
472        )));
473        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
474            .unwrap()
475            .project(vec![
476                col("number"),
477                col("pk3").alias("pk1"),
478                col("pk3").alias("pk2"),
479            ])
480            .unwrap()
481            .project(vec![
482                col("number"),
483                col("pk2").alias("pk4"),
484                col("pk1").alias("pk5"),
485            ])
486            .unwrap()
487            .build()
488            .unwrap();
489
490        let child = plan.inputs()[0].clone();
491
492        assert_eq!(
493            aliased_columns_for(&[qcol("pk1"), qcol("pk2")].into(), &plan, Some(&child)).unwrap(),
494            [
495                (qcol("pk1"), [qcol("pk5")].into()),
496                (qcol("pk2"), [qcol("pk4")].into())
497            ]
498            .into()
499        );
500
501        // columns not in the plan should return empty mapping
502        assert_eq!(
503            aliased_columns_for(&[qcol("pk1"), qcol("pk2")].into(), &plan, Some(&plan)).unwrap(),
504            [].into()
505        );
506
507        assert_eq!(
508            aliased_columns_for(&[qcol("t.pk3")].into(), &plan, Some(&child)).unwrap(),
509            [].into()
510        );
511
512        assert_eq!(
513            aliased_columns_for(&[qcol("pk3")].into(), &plan, None).unwrap(),
514            [(qcol("pk3"), [qcol("pk5"), qcol("pk4")].into())].into()
515        );
516
517        assert_eq!(
518            aliased_columns_for(&[qcol("pk3")].into(), &child, None).unwrap(),
519            [(qcol("pk3"), [qcol("pk1"), qcol("pk2")].into())].into()
520        );
521    }
522
523    #[test]
524    fn sort_subquery_alias_layered_tracker() {
525        let test_table = TestTable::table_with_name(0, "t".to_string());
526        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
527            DfTableProviderAdapter::new(test_table),
528        )));
529
530        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
531            .unwrap()
532            .sort(vec![col("t.number").sort(true, false)])
533            .unwrap()
534            .alias("a")
535            .unwrap()
536            .build()
537            .unwrap();
538
539        let sort_plan = plan.inputs()[0].clone();
540        let scan_plan = sort_plan.inputs()[0].clone();
541
542        // Test aliased_columns_for from scan to final plan
543        assert_eq!(
544            aliased_columns_for(&[qcol("t.number")].into(), &plan, Some(&scan_plan)).unwrap(),
545            [(qcol("t.number"), [qcol("a.number")].into())].into()
546        );
547
548        // Test aliased_columns_for from sort to final plan
549        assert_eq!(
550            aliased_columns_for(&[qcol("t.number")].into(), &plan, Some(&sort_plan)).unwrap(),
551            [(qcol("t.number"), [qcol("a.number")].into())].into()
552        );
553
554        // Test aliased_columns_for from leaf to final plan
555        assert_eq!(
556            aliased_columns_for(&[qcol("t.number")].into(), &plan, None).unwrap(),
557            [(qcol("t.number"), [qcol("a.number")].into())].into()
558        );
559    }
560
561    #[test]
562    fn proj_alias_layered_tracker() {
563        // use logging for better debugging
564        init_default_ut_logging();
565        let test_table = TestTable::table_with_name(0, "t".to_string());
566        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
567            DfTableProviderAdapter::new(test_table),
568        )));
569        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
570            .unwrap()
571            .project(vec![
572                col("number"),
573                col("pk3").alias("pk1"),
574                col("pk2").alias("pk3"),
575            ])
576            .unwrap()
577            .project(vec![
578                col("number"),
579                col("pk1").alias("pk2"),
580                col("pk3").alias("pk1"),
581            ])
582            .unwrap()
583            .build()
584            .unwrap();
585
586        let first_proj = plan.inputs()[0].clone();
587        let scan_plan = first_proj.inputs()[0].clone();
588
589        // Test aliased_columns_for from scan to first projection
590        assert_eq!(
591            aliased_columns_for(&[qcol("t.pk2")].into(), &first_proj, Some(&scan_plan)).unwrap(),
592            [(qcol("t.pk2"), [qcol("pk3")].into())].into()
593        );
594
595        // Test aliased_columns_for from first projection to final plan
596        assert_eq!(
597            aliased_columns_for(&[qcol("pk3")].into(), &plan, Some(&first_proj)).unwrap(),
598            [(qcol("pk3"), [qcol("pk1")].into())].into()
599        );
600
601        // Test aliased_columns_for from scan to final plan
602        assert_eq!(
603            aliased_columns_for(&[qcol("t.pk2")].into(), &plan, Some(&scan_plan)).unwrap(),
604            [(qcol("t.pk2"), [qcol("pk1")].into())].into()
605        );
606
607        // Test aliased_columns_for from leaf to final plan
608        assert_eq!(
609            aliased_columns_for(&[qcol("pk2")].into(), &plan, None).unwrap(),
610            [(qcol("pk2"), [qcol("pk1")].into())].into()
611        );
612    }
613
614    #[test]
615    fn proj_alias_relation_layered_tracker() {
616        // use logging for better debugging
617        init_default_ut_logging();
618        let test_table = TestTable::table_with_name(0, "t".to_string());
619        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
620            DfTableProviderAdapter::new(test_table),
621        )));
622        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
623            .unwrap()
624            .project(vec![
625                col("number"),
626                col("pk3").alias_qualified(Some("b"), "pk1"),
627                col("pk2").alias_qualified(Some("a"), "pk1"),
628            ])
629            .unwrap()
630            .build()
631            .unwrap();
632
633        let scan_plan = plan.inputs()[0].clone();
634
635        // Test aliased_columns_for from scan to projection
636        assert_eq!(
637            aliased_columns_for(&[qcol("t.pk2")].into(), &plan, Some(&scan_plan)).unwrap(),
638            [(qcol("t.pk2"), [qcol("a.pk1")].into())].into()
639        );
640    }
641
642    #[test]
643    fn proj_alias_aliased_aggr() {
644        // use logging for better debugging
645        init_default_ut_logging();
646        let test_table = TestTable::table_with_name(0, "t".to_string());
647        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
648            DfTableProviderAdapter::new(test_table),
649        )));
650        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
651            .unwrap()
652            .project(vec![
653                col("number"),
654                col("pk1").alias("pk3"),
655                col("pk2").alias("pk4"),
656            ])
657            .unwrap()
658            .project(vec![
659                col("number"),
660                col("pk3").alias("pk42"),
661                col("pk4").alias("pk43"),
662            ])
663            .unwrap()
664            .aggregate(vec![col("pk42"), col("pk43")], vec![min(col("number"))])
665            .unwrap()
666            .build()
667            .unwrap();
668
669        let aggr_plan = plan.clone();
670        let second_proj = aggr_plan.inputs()[0].clone();
671        let first_proj = second_proj.inputs()[0].clone();
672        let scan_plan = first_proj.inputs()[0].clone();
673
674        // Test aliased_columns_for from scan to final plan
675        assert_eq!(
676            aliased_columns_for(&[qcol("t.pk1")].into(), &plan, Some(&scan_plan)).unwrap(),
677            [(qcol("t.pk1"), [qcol("pk42")].into())].into()
678        );
679
680        // Test aliased_columns_for from scan to first projection
681        assert_eq!(
682            aliased_columns_for(&[Column::from_name("pk1")].into(), &first_proj, None).unwrap(),
683            [(Column::from_name("pk1"), [qcol("pk3")].into())].into()
684        );
685    }
686
687    #[test]
688    fn aggr_aggr_alias() {
689        // use logging for better debugging
690        init_default_ut_logging();
691        let test_table = TestTable::table_with_name(0, "t".to_string());
692        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
693            DfTableProviderAdapter::new(test_table),
694        )));
695        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
696            .unwrap()
697            .aggregate(vec![col("pk1"), col("pk2")], vec![max(col("number"))])
698            .unwrap()
699            .aggregate(
700                vec![col("pk1"), col("pk2")],
701                vec![min(col("max(t.number)"))],
702            )
703            .unwrap()
704            .build()
705            .unwrap();
706
707        let second_aggr = plan.clone();
708        let first_aggr = second_aggr.inputs()[0].clone();
709        let scan_plan = first_aggr.inputs()[0].clone();
710
711        // Test aliased_columns_for from scan to final plan (identity mapping for aggregates)
712        assert_eq!(
713            aliased_columns_for(&[qcol("t.pk1")].into(), &plan, Some(&scan_plan)).unwrap(),
714            [(qcol("t.pk1"), [qcol("t.pk1")].into())].into()
715        );
716
717        // Test aliased_columns_for from scan to first aggregate
718        assert_eq!(
719            aliased_columns_for(&[qcol("t.pk1")].into(), &first_aggr, Some(&scan_plan)).unwrap(),
720            [(qcol("t.pk1"), [qcol("t.pk1")].into())].into()
721        );
722
723        // Test aliased_columns_for from first aggregate to final plan
724        assert_eq!(
725            aliased_columns_for(&[qcol("t.pk1")].into(), &plan, Some(&first_aggr)).unwrap(),
726            [(qcol("t.pk1"), [qcol("t.pk1")].into())].into()
727        );
728
729        // Test aliased_columns_for from leaf to final plan
730        assert_eq!(
731            aliased_columns_for(&[Column::from_name("pk1")].into(), &plan, None).unwrap(),
732            [(Column::from_name("pk1"), [qcol("t.pk1")].into())].into()
733        );
734    }
735
736    #[test]
737    fn aggr_aggr_alias_projection() {
738        // use logging for better debugging
739        init_default_ut_logging();
740        let test_table = TestTable::table_with_name(0, "t".to_string());
741        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
742            DfTableProviderAdapter::new(test_table),
743        )));
744        let plan = LogicalPlanBuilder::scan_with_filters("t", table_source, None, vec![])
745            .unwrap()
746            .aggregate(vec![col("pk1"), col("pk2")], vec![max(col("number"))])
747            .unwrap()
748            .aggregate(
749                vec![col("pk1"), col("pk2")],
750                vec![min(col("max(t.number)"))],
751            )
752            .unwrap()
753            .project(vec![
754                col("pk1").alias("pk11"),
755                col("pk2").alias("pk22"),
756                col("min(max(t.number))").alias("min_max_number"),
757            ])
758            .unwrap()
759            .build()
760            .unwrap();
761
762        let proj_plan = plan.clone();
763        let second_aggr = proj_plan.inputs()[0].clone();
764
765        // Test aliased_columns_for from second aggregate to projection
766        assert_eq!(
767            aliased_columns_for(
768                &[Column::from_name("min(max(t.number))")].into(),
769                &plan,
770                Some(&second_aggr)
771            )
772            .unwrap(),
773            [(
774                Column::from_name("min(max(t.number))"),
775                [Column::from_name("min_max_number")].into()
776            )]
777            .into()
778        );
779    }
780}