1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use crate::optimizer::ApplyOrder;
use datafusion_common::Result;
use datafusion_expr::{Expr, LogicalPlan, Projection};
use std::collections::HashMap;
use crate::push_down_filter::replace_cols_by_name;
use crate::{OptimizerConfig, OptimizerRule};
#[derive(Default)]
pub struct MergeProjection;
impl MergeProjection {
#[allow(missing_docs)]
pub fn new() -> Self {
Self {}
}
}
impl OptimizerRule for MergeProjection {
fn try_optimize(
&self,
plan: &LogicalPlan,
_config: &dyn OptimizerConfig,
) -> Result<Option<LogicalPlan>> {
match plan {
LogicalPlan::Projection(parent_projection) => {
match parent_projection.input.as_ref() {
LogicalPlan::Projection(child_projection) => {
let replace_map = collect_projection_expr(child_projection);
let new_exprs = parent_projection
.expr
.iter()
.map(|expr| replace_cols_by_name(expr.clone(), &replace_map))
.enumerate()
.map(|(i, e)| match e {
Ok(e) => {
let parent_expr = parent_projection.schema.fields()
[i]
.qualified_name();
if e.display_name()? == parent_expr {
Ok(e)
} else {
Ok(e.alias(parent_expr))
}
}
Err(e) => Err(e),
})
.collect::<Result<Vec<_>>>()?;
let new_plan =
LogicalPlan::Projection(Projection::try_new_with_schema(
new_exprs,
child_projection.input.clone(),
parent_projection.schema.clone(),
)?);
Ok(Some(
self.try_optimize(&new_plan, _config)?.unwrap_or(new_plan),
))
}
_ => Ok(None),
}
}
_ => Ok(None),
}
}
fn name(&self) -> &str {
"merge_projection"
}
fn apply_order(&self) -> Option<ApplyOrder> {
Some(ApplyOrder::TopDown)
}
}
pub fn collect_projection_expr(projection: &Projection) -> HashMap<String, Expr> {
projection
.schema
.fields()
.iter()
.enumerate()
.flat_map(|(i, field)| {
let expr = projection.expr[i].clone().unalias();
[
(field.name().clone(), expr.clone()),
(field.qualified_name(), expr),
]
})
.collect::<HashMap<_, _>>()
}
#[cfg(test)]
mod tests {
use crate::merge_projection::MergeProjection;
use datafusion_common::Result;
use datafusion_expr::{
binary_expr, col, lit, logical_plan::builder::LogicalPlanBuilder, LogicalPlan,
Operator,
};
use std::sync::Arc;
use crate::test::*;
fn assert_optimized_plan_equal(plan: &LogicalPlan, expected: &str) -> Result<()> {
assert_optimized_plan_eq(Arc::new(MergeProjection::new()), plan, expected)
}
#[test]
fn merge_two_projection() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.project(vec![col("a")])?
.project(vec![binary_expr(lit(1), Operator::Plus, col("a"))])?
.build()?;
let expected = "Projection: Int32(1) + test.a\
\n TableScan: test";
assert_optimized_plan_equal(&plan, expected)
}
#[test]
fn merge_three_projection() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.project(vec![col("a"), col("b")])?
.project(vec![col("a")])?
.project(vec![binary_expr(lit(1), Operator::Plus, col("a"))])?
.build()?;
let expected = "Projection: Int32(1) + test.a\
\n TableScan: test";
assert_optimized_plan_equal(&plan, expected)
}
#[test]
fn merge_alias() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.project(vec![col("a")])?
.project(vec![col("a").alias("alias")])?
.build()?;
let expected = "Projection: test.a AS alias\
\n TableScan: test";
assert_optimized_plan_equal(&plan, expected)
}
}