-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mod.rs
487 lines (434 loc) · 15.3 KB
/
mod.rs
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Expression rewriter
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use crate::expr::{Alias, Unnest};
use crate::logical_plan::Projection;
use crate::{Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder};
use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::{
Transformed, TransformedResult, TreeNode, TreeNodeRewriter,
};
use datafusion_common::{Column, DFSchema, Result};
mod order_by;
pub use order_by::rewrite_sort_cols_by_aggs;
/// Trait for rewriting [`Expr`]s into function calls.
///
/// This trait is used with `FunctionRegistry::register_function_rewrite` to
/// to evaluating `Expr`s using functions that may not be built in to DataFusion
///
/// For example, concatenating arrays `a || b` is represented as
/// `Operator::ArrowAt`, but can be implemented by calling a function
/// `array_concat` from the `functions-array` crate.
pub trait FunctionRewrite {
/// Return a human readable name for this rewrite
fn name(&self) -> &str;
/// Potentially rewrite `expr` to some other expression
///
/// Note that recursion is handled by the caller -- this method should only
/// handle `expr`, not recurse to its children.
fn rewrite(
&self,
expr: Expr,
schema: &DFSchema,
config: &ConfigOptions,
) -> Result<Transformed<Expr>>;
}
/// Recursively call [`Column::normalize_with_schemas`] on all [`Column`] expressions
/// in the `expr` expression tree.
pub fn normalize_col(expr: Expr, plan: &LogicalPlan) -> Result<Expr> {
expr.transform(&|expr| {
Ok({
if let Expr::Column(c) = expr {
let col = LogicalPlanBuilder::normalize(plan, c)?;
Transformed::yes(Expr::Column(col))
} else {
Transformed::no(expr)
}
})
})
.data()
}
/// See [`Column::normalize_with_schemas_and_ambiguity_check`] for usage
pub fn normalize_col_with_schemas_and_ambiguity_check(
expr: Expr,
schemas: &[&[&DFSchema]],
using_columns: &[HashSet<Column>],
) -> Result<Expr> {
// Normalize column inside Unnest
if let Expr::Unnest(Unnest { exprs }) = expr {
let e = normalize_col_with_schemas_and_ambiguity_check(
exprs[0].clone(),
schemas,
using_columns,
)?;
return Ok(Expr::Unnest(Unnest { exprs: vec![e] }));
}
expr.transform(&|expr| {
Ok({
if let Expr::Column(c) = expr {
let col =
c.normalize_with_schemas_and_ambiguity_check(schemas, using_columns)?;
Transformed::yes(Expr::Column(col))
} else {
Transformed::no(expr)
}
})
})
.data()
}
/// Recursively normalize all [`Column`] expressions in a list of expression trees
pub fn normalize_cols(
exprs: impl IntoIterator<Item = impl Into<Expr>>,
plan: &LogicalPlan,
) -> Result<Vec<Expr>> {
exprs
.into_iter()
.map(|e| normalize_col(e.into(), plan))
.collect()
}
/// Recursively replace all [`Column`] expressions in a given expression tree with
/// `Column` expressions provided by the hash map argument.
pub fn replace_col(expr: Expr, replace_map: &HashMap<&Column, &Column>) -> Result<Expr> {
expr.transform(&|expr| {
Ok({
if let Expr::Column(c) = &expr {
match replace_map.get(c) {
Some(new_c) => Transformed::yes(Expr::Column((*new_c).to_owned())),
None => Transformed::no(expr),
}
} else {
Transformed::no(expr)
}
})
})
.data()
}
/// Recursively 'unnormalize' (remove all qualifiers) from an
/// expression tree.
///
/// For example, if there were expressions like `foo.bar` this would
/// rewrite it to just `bar`.
pub fn unnormalize_col(expr: Expr) -> Expr {
expr.transform(&|expr| {
Ok({
if let Expr::Column(c) = expr {
let col = Column {
relation: None,
name: c.name,
};
Transformed::yes(Expr::Column(col))
} else {
Transformed::no(expr)
}
})
})
.data()
.expect("Unnormalize is infallable")
}
/// Create a Column from the Scalar Expr
pub fn create_col_from_scalar_expr(
scalar_expr: &Expr,
subqry_alias: String,
) -> Result<Column> {
match scalar_expr {
Expr::Alias(Alias { name, .. }) => Ok(Column::new(Some(subqry_alias), name)),
Expr::Column(Column { relation: _, name }) => {
Ok(Column::new(Some(subqry_alias), name))
}
_ => {
let scalar_column = scalar_expr.display_name()?;
Ok(Column::new(Some(subqry_alias), scalar_column))
}
}
}
/// Recursively un-normalize all [`Column`] expressions in a list of expression trees
#[inline]
pub fn unnormalize_cols(exprs: impl IntoIterator<Item = Expr>) -> Vec<Expr> {
exprs.into_iter().map(unnormalize_col).collect()
}
/// Recursively remove all the ['OuterReferenceColumn'] and return the inside Column
/// in the expression tree.
pub fn strip_outer_reference(expr: Expr) -> Expr {
expr.transform(&|expr| {
Ok({
if let Expr::OuterReferenceColumn(_, col) = expr {
Transformed::yes(Expr::Column(col))
} else {
Transformed::no(expr)
}
})
})
.data()
.expect("strip_outer_reference is infallable")
}
/// Returns plan with expressions coerced to types compatible with
/// schema types
pub fn coerce_plan_expr_for_schema(
plan: &LogicalPlan,
schema: &DFSchema,
) -> Result<LogicalPlan> {
match plan {
// special case Projection to avoid adding multiple projections
LogicalPlan::Projection(Projection { expr, input, .. }) => {
let new_exprs =
coerce_exprs_for_schema(expr.clone(), input.schema(), schema)?;
let projection = Projection::try_new(new_exprs, input.clone())?;
Ok(LogicalPlan::Projection(projection))
}
_ => {
let exprs: Vec<Expr> = plan
.schema()
.fields()
.iter()
.map(|field| Expr::Column(field.qualified_column()))
.collect();
let new_exprs = coerce_exprs_for_schema(exprs, plan.schema(), schema)?;
let add_project = new_exprs.iter().any(|expr| expr.try_into_col().is_err());
if add_project {
let projection = Projection::try_new(new_exprs, Arc::new(plan.clone()))?;
Ok(LogicalPlan::Projection(projection))
} else {
Ok(plan.clone())
}
}
}
}
fn coerce_exprs_for_schema(
exprs: Vec<Expr>,
src_schema: &DFSchema,
dst_schema: &DFSchema,
) -> Result<Vec<Expr>> {
exprs
.into_iter()
.enumerate()
.map(|(idx, expr)| {
let new_type = dst_schema.field(idx).data_type();
if new_type != &expr.get_type(src_schema)? {
match expr {
Expr::Alias(Alias { expr, name, .. }) => {
Ok(expr.cast_to(new_type, src_schema)?.alias(name))
}
_ => expr.cast_to(new_type, src_schema),
}
} else {
Ok(expr.clone())
}
})
.collect::<Result<_>>()
}
/// Recursively un-alias an expressions
#[inline]
pub fn unalias(expr: Expr) -> Expr {
match expr {
Expr::Alias(Alias { expr, .. }) => unalias(*expr),
_ => expr,
}
}
/// Rewrites `expr` using `rewriter`, ensuring that the output has the
/// same name as `expr` prior to rewrite, adding an alias if necessary.
///
/// This is important when optimizing plans to ensure the output
/// schema of plan nodes don't change after optimization
pub fn rewrite_preserving_name<R>(expr: Expr, rewriter: &mut R) -> Result<Expr>
where
R: TreeNodeRewriter<Node = Expr>,
{
let original_name = expr.name_for_alias()?;
let expr = expr.rewrite(rewriter)?.data;
expr.alias_if_changed(original_name)
}
#[cfg(test)]
mod test {
use std::ops::Add;
use super::*;
use crate::expr::Sort;
use crate::{col, lit, Cast};
use arrow::datatypes::DataType;
use datafusion_common::tree_node::{TreeNode, TreeNodeRewriter};
use datafusion_common::{DFField, DFSchema, ScalarValue};
#[derive(Default)]
struct RecordingRewriter {
v: Vec<String>,
}
impl TreeNodeRewriter for RecordingRewriter {
type Node = Expr;
fn f_down(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
self.v.push(format!("Previsited {expr}"));
Ok(Transformed::no(expr))
}
fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
self.v.push(format!("Mutated {expr}"));
Ok(Transformed::no(expr))
}
}
#[test]
fn rewriter_rewrite() {
// rewrites all "foo" string literals to "bar"
let transformer = |expr: Expr| -> Result<Transformed<Expr>> {
match expr {
Expr::Literal(ScalarValue::Utf8(Some(utf8_val))) => {
let utf8_val = if utf8_val == "foo" {
"bar".to_string()
} else {
utf8_val
};
Ok(Transformed::yes(lit(utf8_val)))
}
// otherwise, return None
_ => Ok(Transformed::no(expr)),
}
};
// rewrites "foo" --> "bar"
let rewritten = col("state")
.eq(lit("foo"))
.transform(&transformer)
.data()
.unwrap();
assert_eq!(rewritten, col("state").eq(lit("bar")));
// doesn't rewrite
let rewritten = col("state")
.eq(lit("baz"))
.transform(&transformer)
.data()
.unwrap();
assert_eq!(rewritten, col("state").eq(lit("baz")));
}
#[test]
fn normalize_cols() {
let expr = col("a") + col("b") + col("c");
// Schemas with some matching and some non matching cols
let schema_a = make_schema_with_empty_metadata(vec![
make_field("tableA", "a"),
make_field("tableA", "aa"),
]);
let schema_c = make_schema_with_empty_metadata(vec![
make_field("tableC", "cc"),
make_field("tableC", "c"),
]);
let schema_b = make_schema_with_empty_metadata(vec![make_field("tableB", "b")]);
// non matching
let schema_f = make_schema_with_empty_metadata(vec![
make_field("tableC", "f"),
make_field("tableC", "ff"),
]);
let schemas = vec![schema_c, schema_f, schema_b, schema_a];
let schemas = schemas.iter().collect::<Vec<_>>();
let normalized_expr =
normalize_col_with_schemas_and_ambiguity_check(expr, &[&schemas], &[])
.unwrap();
assert_eq!(
normalized_expr,
col("tableA.a") + col("tableB.b") + col("tableC.c")
);
}
#[test]
fn normalize_cols_non_exist() {
// test normalizing columns when the name doesn't exist
let expr = col("a") + col("b");
let schema_a =
make_schema_with_empty_metadata(vec![make_field("\"tableA\"", "a")]);
let schemas = [schema_a];
let schemas = schemas.iter().collect::<Vec<_>>();
let error =
normalize_col_with_schemas_and_ambiguity_check(expr, &[&schemas], &[])
.unwrap_err()
.strip_backtrace();
assert_eq!(
error,
r#"Schema error: No field named b. Valid fields are "tableA".a."#
);
}
#[test]
fn unnormalize_cols() {
let expr = col("tableA.a") + col("tableB.b");
let unnormalized_expr = unnormalize_col(expr);
assert_eq!(unnormalized_expr, col("a") + col("b"));
}
fn make_schema_with_empty_metadata(fields: Vec<DFField>) -> DFSchema {
DFSchema::new_with_metadata(fields, HashMap::new()).unwrap()
}
fn make_field(relation: &str, column: &str) -> DFField {
DFField::new(Some(relation.to_string()), column, DataType::Int8, false)
}
#[test]
fn rewriter_visit() {
let mut rewriter = RecordingRewriter::default();
col("state").eq(lit("CO")).rewrite(&mut rewriter).unwrap();
assert_eq!(
rewriter.v,
vec![
"Previsited state = Utf8(\"CO\")",
"Previsited state",
"Mutated state",
"Previsited Utf8(\"CO\")",
"Mutated Utf8(\"CO\")",
"Mutated state = Utf8(\"CO\")"
]
)
}
#[test]
fn test_rewrite_preserving_name() {
test_rewrite(col("a"), col("a"));
test_rewrite(col("a"), col("b"));
// cast data types
test_rewrite(
col("a"),
Expr::Cast(Cast::new(Box::new(col("a")), DataType::Int32)),
);
// change literal type from i32 to i64
test_rewrite(col("a").add(lit(1i32)), col("a").add(lit(1i64)));
// SortExpr a+1 ==> b + 2
test_rewrite(
Expr::Sort(Sort::new(Box::new(col("a").add(lit(1i32))), true, false)),
Expr::Sort(Sort::new(Box::new(col("b").add(lit(2i64))), true, false)),
);
}
/// rewrites `expr_from` to `rewrite_to` using
/// `rewrite_preserving_name` verifying the result is `expected_expr`
fn test_rewrite(expr_from: Expr, rewrite_to: Expr) {
struct TestRewriter {
rewrite_to: Expr,
}
impl TreeNodeRewriter for TestRewriter {
type Node = Expr;
fn f_up(&mut self, _: Expr) -> Result<Transformed<Expr>> {
Ok(Transformed::yes(self.rewrite_to.clone()))
}
}
let mut rewriter = TestRewriter {
rewrite_to: rewrite_to.clone(),
};
let expr = rewrite_preserving_name(expr_from.clone(), &mut rewriter).unwrap();
let original_name = match &expr_from {
Expr::Sort(Sort { expr, .. }) => expr.display_name(),
expr => expr.display_name(),
}
.unwrap();
let new_name = match &expr {
Expr::Sort(Sort { expr, .. }) => expr.display_name(),
expr => expr.display_name(),
}
.unwrap();
assert_eq!(
original_name, new_name,
"mismatch rewriting expr_from: {expr_from} to {rewrite_to}"
)
}
}