Skip to main content

datafusion_expr/expr_rewriter/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Expression rewriter
6
7use std::collections::HashMap;
8use std::collections::HashSet;
9use std::fmt::Debug;
10use std::sync::Arc;
11
12use crate::expr::{Alias, Sort, Unnest};
13use crate::logical_plan::Projection;
14use crate::{Expr, ExprSchemable, LogicalPlan};
15
16use datafusion_common::TableReference;
17use datafusion_common::config::ConfigOptions;
18use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
19use datafusion_common::{Column, DFSchema, Result};
20
21mod guarantees;
22pub use guarantees::GuaranteeRewriter;
23pub use guarantees::rewrite_with_guarantees;
24pub use guarantees::rewrite_with_guarantees_map;
25mod order_by;
26
27pub use order_by::rewrite_sort_cols_by_aggs;
28
29/// Trait for rewriting [`Expr`]s into function calls.
30///
31/// This trait is used with `FunctionRegistry::register_function_rewrite` to
32/// to evaluating `Expr`s using functions that may not be built in to DataFusion
33///
34/// For example, concatenating arrays `a || b` is represented as
35/// `Operator::ArrowAt`, but can be implemented by calling a function
36/// `array_concat` from the `functions-nested` crate.
37// This is not used in datafusion internally, but it is still helpful for downstream project so don't remove it.
38pub trait FunctionRewrite: Debug {
39    /// Return a human readable name for this rewrite
40    fn name(&self) -> &str;
41
42    /// Potentially rewrite `expr` to some other expression
43    ///
44    /// Note that recursion is handled by the caller -- this method should only
45    /// handle `expr`, not recurse to its children.
46    fn rewrite(
47        &self,
48        expr: Expr,
49        schema: &DFSchema,
50        config: &ConfigOptions,
51    ) -> Result<Transformed<Expr>>;
52}
53
54/// Recursively normalize all [`Column`] expressions in the `expr` expression tree.
55pub fn normalize_col(expr: Expr, plan: &LogicalPlan) -> Result<Expr> {
56    ColumnNormalizer::new(plan).normalize(expr)
57}
58
59/// Reuses the plan's normalization context across expressions. Initialize it
60/// lazily so literals and already-qualified columns need no plan traversal.
61pub(crate) struct ColumnNormalizer<'a> {
62    plan: &'a LogicalPlan,
63    context: Option<(Vec<&'a DFSchema>, Vec<HashSet<Column>>)>,
64}
65
66impl<'a> ColumnNormalizer<'a> {
67    pub(crate) fn new(plan: &'a LogicalPlan) -> Self {
68        Self {
69            plan,
70            context: None,
71        }
72    }
73
74    #[inline]
75    pub(crate) fn normalize_column(&mut self, column: Column) -> Result<Column> {
76        if column.relation.is_some() {
77            return Ok(column);
78        }
79
80        let (fallback_schemas, using_columns) = match &mut self.context {
81            Some(context) => context,
82            context @ None => context.insert((
83                self.plan.fallback_normalize_schemas(),
84                self.plan.using_columns()?,
85            )),
86        };
87        column.normalize_with_schemas_and_ambiguity_check(
88            &[&[self.plan.schema()], fallback_schemas],
89            using_columns,
90        )
91    }
92
93    pub(crate) fn normalize(&mut self, expr: Expr) -> Result<Expr> {
94        expr.transform(|expr| match expr {
95            Expr::Column(column) => self
96                .normalize_column(column)
97                .map(|column| Transformed::yes(Expr::Column(column))),
98            _ => Ok(Transformed::no(expr)),
99        })
100        .data()
101    }
102}
103
104/// See [`Column::normalize_with_schemas_and_ambiguity_check`] for usage
105pub fn normalize_col_with_schemas_and_ambiguity_check(
106    expr: Expr,
107    schemas: &[&[&DFSchema]],
108    using_columns: &[HashSet<Column>],
109) -> Result<Expr> {
110    // Normalize column inside Unnest
111    if let Expr::Unnest(Unnest { expr, outer }) = expr {
112        let e = normalize_col_with_schemas_and_ambiguity_check(
113            expr.as_ref().clone(),
114            schemas,
115            using_columns,
116        )?;
117        return Ok(Expr::Unnest(Unnest {
118            expr: Box::new(e),
119            outer,
120        }));
121    }
122
123    expr.transform(|expr| {
124        Ok({
125            if let Expr::Column(c) = expr {
126                let col =
127                    c.normalize_with_schemas_and_ambiguity_check(schemas, using_columns)?;
128                Transformed::yes(Expr::Column(col))
129            } else {
130                Transformed::no(expr)
131            }
132        })
133    })
134    .data()
135}
136
137/// Recursively normalize all [`Column`] expressions in a list of expression trees
138pub fn normalize_cols(
139    exprs: impl IntoIterator<Item = impl Into<Expr>>,
140    plan: &LogicalPlan,
141) -> Result<Vec<Expr>> {
142    let mut normalizer = ColumnNormalizer::new(plan);
143    exprs
144        .into_iter()
145        .map(|e| normalizer.normalize(e.into()))
146        .collect()
147}
148
149pub fn normalize_sorts(
150    sorts: impl IntoIterator<Item = impl Into<Sort>>,
151    plan: &LogicalPlan,
152) -> Result<Vec<Sort>> {
153    let mut normalizer = ColumnNormalizer::new(plan);
154    sorts
155        .into_iter()
156        .map(|e| {
157            let sort = e.into();
158            normalizer
159                .normalize(sort.expr)
160                .map(|expr| Sort::new(expr, sort.asc, sort.nulls_first))
161        })
162        .collect()
163}
164
165/// Recursively replace all [`Column`] expressions in a given expression tree with
166/// `Column` expressions provided by the hash map argument.
167pub fn replace_col(expr: Expr, replace_map: &HashMap<&Column, &Column>) -> Result<Expr> {
168    expr.transform(|expr| {
169        Ok({
170            if let Expr::Column(c) = &expr {
171                match replace_map.get(c) {
172                    Some(new_c) => Transformed::yes(Expr::Column((*new_c).to_owned())),
173                    None => Transformed::no(expr),
174                }
175            } else {
176                Transformed::no(expr)
177            }
178        })
179    })
180    .data()
181}
182
183/// Recursively 'unnormalize' (remove all qualifiers) from an
184/// expression tree.
185///
186/// For example, if there were expressions like `foo.bar` this would
187/// rewrite it to just `bar`.
188pub fn unnormalize_col(expr: Expr) -> Expr {
189    expr.transform(|expr| {
190        Ok({
191            if let Expr::Column(c) = expr {
192                let col = Column::new_unqualified(c.name);
193                Transformed::yes(Expr::Column(col))
194            } else {
195                Transformed::no(expr)
196            }
197        })
198    })
199    .data()
200    .expect("Unnormalize is infallible")
201}
202
203/// Create a Column from the Scalar Expr
204pub fn create_col_from_scalar_expr(
205    scalar_expr: &Expr,
206    subqry_alias: String,
207) -> Result<Column> {
208    match scalar_expr {
209        Expr::Alias(Alias { name, .. }) => Ok(Column::new(
210            Some::<TableReference>(subqry_alias.into()),
211            name,
212        )),
213        Expr::Column(col) => Ok(col.with_relation(subqry_alias.into())),
214        _ => {
215            let scalar_column = scalar_expr.schema_name().to_string();
216            Ok(Column::new(
217                Some::<TableReference>(subqry_alias.into()),
218                scalar_column,
219            ))
220        }
221    }
222}
223
224/// Recursively un-normalize all [`Column`] expressions in a list of expression trees
225#[inline]
226pub fn unnormalize_cols(exprs: impl IntoIterator<Item = Expr>) -> Vec<Expr> {
227    exprs.into_iter().map(unnormalize_col).collect()
228}
229
230/// Recursively remove all the [`Expr::OuterReferenceColumn`] and return the inside Column
231/// in the expression tree.
232pub fn strip_outer_reference(expr: Expr) -> Expr {
233    expr.transform(|expr| {
234        Ok({
235            if let Expr::OuterReferenceColumn(_, col) = expr {
236                Transformed::yes(Expr::Column(col))
237            } else {
238                Transformed::no(expr)
239            }
240        })
241    })
242    .data()
243    .expect("strip_outer_reference is infallible")
244}
245
246/// Returns plan with expressions coerced to types compatible with
247/// schema types
248pub fn coerce_plan_expr_for_schema(
249    plan: LogicalPlan,
250    schema: &DFSchema,
251) -> Result<LogicalPlan> {
252    match plan {
253        // special case Projection to avoid adding multiple projections
254        LogicalPlan::Projection(Projection { expr, input, .. }) => {
255            let new_exprs = coerce_exprs_for_schema(expr, input.schema(), schema)?;
256            let projection = Projection::try_new(new_exprs, input)?;
257            Ok(LogicalPlan::Projection(projection))
258        }
259        _ => {
260            let exprs: Vec<Expr> = plan.schema().iter().map(Expr::from).collect();
261            let new_exprs = coerce_exprs_for_schema(exprs, plan.schema(), schema)?;
262            let add_project = new_exprs.iter().any(|expr| expr.try_as_col().is_none());
263            if add_project {
264                let projection = Projection::try_new(new_exprs, Arc::new(plan))?;
265                Ok(LogicalPlan::Projection(projection))
266            } else {
267                Ok(plan)
268            }
269        }
270    }
271}
272
273fn coerce_exprs_for_schema(
274    exprs: Vec<Expr>,
275    src_schema: &DFSchema,
276    dst_schema: &DFSchema,
277) -> Result<Vec<Expr>> {
278    exprs
279        .into_iter()
280        .enumerate()
281        .map(|(idx, expr)| {
282            let new_type = dst_schema.field(idx).data_type();
283            if new_type != &expr.get_type(src_schema)? {
284                match expr {
285                    Expr::Alias(Alias { expr, name, .. }) => {
286                        Ok(expr.cast_to(new_type, src_schema)?.alias(name))
287                    }
288                    #[expect(deprecated)]
289                    Expr::Wildcard { .. } => Ok(expr),
290                    _ => {
291                        match expr {
292                            // maintain the original name when casting a column, to avoid the
293                            // tablename being added to it when not explicitly set by the query
294                            // (see: https://github.com/apache/datafusion/issues/18818)
295                            Expr::Column(ref column) => {
296                                let name = column.name().to_owned();
297                                Ok(expr.cast_to(new_type, src_schema)?.alias(name))
298                            }
299                            _ => Ok(expr.cast_to(new_type, src_schema)?),
300                        }
301                    }
302                }
303            } else {
304                Ok(expr)
305            }
306        })
307        .collect::<Result<_>>()
308}
309
310/// Recursively un-alias an expressions
311#[inline]
312pub fn unalias(expr: Expr) -> Expr {
313    match expr {
314        Expr::Alias(Alias { expr, .. }) => unalias(*expr),
315        _ => expr,
316    }
317}
318
319/// Handles ensuring the name of rewritten expressions is not changed.
320///
321/// This is important when optimizing plans to ensure the output
322/// schema of plan nodes don't change after optimization.
323/// For example, if an expression `1 + 2` is rewritten to `3`, the name of the
324/// expression should be preserved: `3 as "1 + 2"`
325///
326/// See <https://github.com/apache/datafusion/issues/3555> for details
327pub struct NamePreserver {
328    use_alias: bool,
329}
330
331/// If the qualified name of an expression is remembered, it will be preserved
332/// when rewriting the expression
333#[derive(Debug)]
334pub enum SavedName {
335    /// Saved qualified name to be preserved
336    Saved {
337        relation: Option<TableReference>,
338        name: String,
339    },
340    /// Name is not preserved
341    None,
342}
343
344impl NamePreserver {
345    /// Create a new NamePreserver for rewriting the `expr` that is part of the specified plan
346    pub fn new(plan: &LogicalPlan) -> Self {
347        Self {
348            // The expressions of these plans do not contribute to their output schema,
349            // so there is no need to preserve expression names to prevent a schema change.
350            use_alias: !matches!(
351                plan,
352                LogicalPlan::Filter(_)
353                    | LogicalPlan::Join(_)
354                    | LogicalPlan::TableScan(_)
355                    | LogicalPlan::Limit(_)
356                    | LogicalPlan::Statement(_)
357            ),
358        }
359    }
360
361    /// Create a new NamePreserver for rewriting the `expr`s in `Projection`
362    ///
363    /// This will use aliases
364    pub fn new_for_projection() -> Self {
365        Self { use_alias: true }
366    }
367
368    pub fn save(&self, expr: &Expr) -> SavedName {
369        if self.use_alias {
370            match expr {
371                Expr::Alias(alias) => SavedName::Saved {
372                    relation: alias.relation.clone(),
373                    name: alias.name.clone(),
374                },
375                _ => {
376                    let (relation, name) = expr.qualified_name();
377                    SavedName::Saved { relation, name }
378                }
379            }
380        } else {
381            SavedName::None
382        }
383    }
384}
385
386impl SavedName {
387    /// Ensures the qualified name of the rewritten expression is preserved
388    pub fn restore(self, expr: Expr) -> Expr {
389        match self {
390            SavedName::Saved { relation, name } => {
391                let (new_relation, new_name) = expr.qualified_name();
392                if new_relation != relation || new_name != name {
393                    expr.alias_qualified(relation, name)
394                } else {
395                    expr
396                }
397            }
398            SavedName::None => expr,
399        }
400    }
401}
402
403#[cfg(test)]
404mod test {
405    use std::ops::Add;
406
407    use super::*;
408    use crate::literal::lit_with_metadata;
409    use crate::{Cast, LogicalPlanBuilder, col, lit};
410    use arrow::datatypes::{DataType, Field, Schema};
411    use datafusion_common::ScalarValue;
412    use datafusion_common::tree_node::TreeNodeRewriter;
413
414    #[derive(Default)]
415    struct RecordingRewriter {
416        v: Vec<String>,
417    }
418
419    impl TreeNodeRewriter for RecordingRewriter {
420        type Node = Expr;
421
422        fn f_down(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
423            self.v.push(format!("Previsited {expr}"));
424            Ok(Transformed::no(expr))
425        }
426
427        fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
428            self.v.push(format!("Mutated {expr}"));
429            Ok(Transformed::no(expr))
430        }
431    }
432
433    #[test]
434    fn rewriter_rewrite() {
435        // rewrites all "foo" string literals to "bar"
436        let transformer = |expr: Expr| -> Result<Transformed<Expr>> {
437            match expr {
438                Expr::Literal(ScalarValue::Utf8(Some(utf8_val)), metadata) => {
439                    let utf8_val = if utf8_val == "foo" {
440                        "bar".to_string()
441                    } else {
442                        utf8_val
443                    };
444                    Ok(Transformed::yes(lit_with_metadata(utf8_val, metadata)))
445                }
446                // otherwise, return None
447                _ => Ok(Transformed::no(expr)),
448            }
449        };
450
451        // rewrites "foo" --> "bar"
452        let rewritten = col("state")
453            .eq(lit("foo"))
454            .transform(transformer)
455            .data()
456            .unwrap();
457        assert_eq!(rewritten, col("state").eq(lit("bar")));
458
459        // doesn't rewrite
460        let rewritten = col("state")
461            .eq(lit("baz"))
462            .transform(transformer)
463            .data()
464            .unwrap();
465        assert_eq!(rewritten, col("state").eq(lit("baz")));
466    }
467
468    #[test]
469    fn normalize_cols() {
470        let expr = col("a") + col("b") + col("c");
471
472        // Schemas with some matching and some non matching cols
473        let schema_a = make_schema_with_empty_metadata(
474            vec![Some("tableA".into()), Some("tableA".into())],
475            vec!["a", "aa"],
476        );
477        let schema_c = make_schema_with_empty_metadata(
478            vec![Some("tableC".into()), Some("tableC".into())],
479            vec!["cc", "c"],
480        );
481        let schema_b =
482            make_schema_with_empty_metadata(vec![Some("tableB".into())], vec!["b"]);
483        // non matching
484        let schema_f = make_schema_with_empty_metadata(
485            vec![Some("tableC".into()), Some("tableC".into())],
486            vec!["f", "ff"],
487        );
488        let schemas = [schema_c, schema_f, schema_b, schema_a];
489        let schemas = schemas.iter().collect::<Vec<_>>();
490
491        let normalized_expr =
492            normalize_col_with_schemas_and_ambiguity_check(expr, &[&schemas], &[])
493                .unwrap();
494        assert_eq!(
495            normalized_expr,
496            col("tableA.a") + col("tableB.b") + col("tableC.c")
497        );
498    }
499
500    #[test]
501    fn normalize_cols_non_exist() {
502        // test normalizing columns when the name doesn't exist
503        let expr = col("a") + col("b");
504        let schema_a =
505            make_schema_with_empty_metadata(vec![Some("\"tableA\"".into())], vec!["a"]);
506        let schemas = [schema_a];
507        let schemas = schemas.iter().collect::<Vec<_>>();
508
509        let error =
510            normalize_col_with_schemas_and_ambiguity_check(expr, &[&schemas], &[])
511                .unwrap_err()
512                .strip_backtrace();
513        let expected = "Schema error: No field named b.\n\
514            Valid fields are \"tableA\".a.";
515        assert_eq!(error, expected);
516    }
517
518    #[test]
519    fn normalize_batch_schema_precedence() -> Result<()> {
520        let schema = Schema::new(vec![
521            Field::new("a", DataType::Int32, false),
522            Field::new("b", DataType::Int32, false),
523        ]);
524        let plan = crate::logical_plan::table_scan(Some("t"), &schema, None)?
525            .project([col("t.a").alias("b")])?
526            .build()?;
527        let exprs = vec![col("b") + col("a"), col("other.missing"), lit(1)];
528        let expected = vec![col("b") + col("t.a"), col("other.missing"), lit(1)];
529        assert_eq!(super::normalize_cols(exprs.clone(), &plan)?, expected);
530        assert_eq!(normalize_col(exprs[0].clone(), &plan)?, expected[0]);
531        let sorts = exprs.into_iter().map(|e| e.sort(false, true));
532        assert_eq!(
533            normalize_sorts(sorts, &plan)?,
534            expected
535                .into_iter()
536                .map(|e| e.sort(false, true))
537                .collect::<Vec<_>>()
538        );
539        Ok(())
540    }
541
542    #[test]
543    fn normalize_batch_using_join() -> Result<()> {
544        let schema = Schema::new(vec![
545            Field::new("a", DataType::Int32, false),
546            Field::new("b", DataType::Int32, false),
547        ]);
548        let right =
549            crate::logical_plan::table_scan(Some("right"), &schema, None)?.build()?;
550        let plan = crate::logical_plan::table_scan(Some("left"), &schema, None)?
551            .join_using(right, crate::JoinType::Inner, vec![Column::from_name("a")])?
552            .build()?;
553        assert_eq!(
554            super::normalize_cols([col("a"), col("a") + col("right.a")], &plan)?,
555            vec![col("left.a"), col("left.a") + col("right.a")]
556        );
557        let projected = LogicalPlanBuilder::from(plan.clone())
558            .project([col("a").alias("key"), col("left.b").alias("value")])?
559            .build()?;
560        assert_eq!(
561            projected.expressions(),
562            vec![col("left.a").alias("key"), col("left.b").alias("value")]
563        );
564        let err = super::normalize_cols([col("a"), col("b"), col("missing")], &plan)
565            .unwrap_err();
566        assert!(
567            err.strip_backtrace()
568                .contains("Ambiguous reference to unqualified field b")
569        );
570        Ok(())
571    }
572
573    #[test]
574    fn normalize_batch_skips_unused_plan_context() -> Result<()> {
575        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
576        let right =
577            crate::logical_plan::table_scan(Some("right"), &schema, None)?.build()?;
578        let mut plan = crate::logical_plan::table_scan(Some("left"), &schema, None)?
579            .join_using(right, crate::JoinType::Inner, vec![Column::from_name("a")])?
580            .build()?;
581        // Invalid USING keys must only be inspected when an unqualified column
582        // needs normalization, just as with a single expression.
583        let LogicalPlan::Join(join) = &mut plan else {
584            unreachable!()
585        };
586        join.on[0].0 = lit(1);
587        assert!(plan.using_columns().is_err());
588        assert!(super::normalize_cols(Vec::<Expr>::new(), &plan)?.is_empty());
589        let exprs = vec![lit(1), col("left.a"), col("other.missing")];
590        assert_eq!(super::normalize_cols(exprs.clone(), &plan)?, exprs);
591        assert_eq!(normalize_col(col("left.a"), &plan)?, col("left.a"));
592        assert_eq!(
593            normalize_sorts([col("left.a").sort(true, false)], &plan)?,
594            vec![col("left.a").sort(true, false)]
595        );
596        assert!(super::normalize_cols([col("left.a"), col("a")], &plan).is_err());
597        let projected = LogicalPlanBuilder::from(plan.clone())
598            .project([col("left.a")])?
599            .build()?;
600        assert_eq!(projected.expressions(), vec![col("left.a")]);
601        assert!(LogicalPlanBuilder::from(plan).project([col("a")]).is_err());
602        Ok(())
603    }
604
605    #[test]
606    fn unnormalize_cols() {
607        let expr = col("tableA.a") + col("tableB.b");
608        let unnormalized_expr = unnormalize_col(expr);
609        assert_eq!(unnormalized_expr, col("a") + col("b"));
610    }
611
612    fn make_schema_with_empty_metadata(
613        qualifiers: Vec<Option<TableReference>>,
614        fields: Vec<&str>,
615    ) -> DFSchema {
616        let fields = fields
617            .iter()
618            .map(|f| Arc::new(Field::new((*f).to_string(), DataType::Int8, false)))
619            .collect::<Vec<_>>();
620        let schema = Arc::new(Schema::new(fields));
621        DFSchema::from_field_specific_qualified_schema(qualifiers, &schema).unwrap()
622    }
623
624    #[test]
625    fn rewriter_visit() {
626        let mut rewriter = RecordingRewriter::default();
627        col("state").eq(lit("CO")).rewrite(&mut rewriter).unwrap();
628
629        assert_eq!(
630            rewriter.v,
631            vec![
632                "Previsited state = Utf8(\"CO\")",
633                "Previsited state",
634                "Mutated state",
635                "Previsited Utf8(\"CO\")",
636                "Mutated Utf8(\"CO\")",
637                "Mutated state = Utf8(\"CO\")"
638            ]
639        )
640    }
641
642    #[test]
643    fn test_rewrite_preserving_name() {
644        test_rewrite(col("a"), col("a"));
645
646        test_rewrite(col("a"), col("b"));
647
648        // cast data types
649        test_rewrite(
650            col("a"),
651            Expr::Cast(Cast::new(Box::new(col("a")), DataType::Int32)),
652        );
653
654        // change literal type from i32 to i64
655        test_rewrite(col("a").add(lit(1i32)), col("a").add(lit(1i64)));
656
657        // test preserve qualifier
658        test_rewrite(
659            Expr::Column(Column::new(Some("test"), "a")),
660            Expr::Column(Column::new_unqualified("test.a")),
661        );
662        test_rewrite(
663            Expr::Column(Column::new_unqualified("test.a")),
664            Expr::Column(Column::new(Some("test"), "a")),
665        );
666    }
667
668    /// rewrites `expr_from` to `rewrite_to` while preserving the original qualified name
669    /// by using the `NamePreserver`
670    fn test_rewrite(expr_from: Expr, rewrite_to: Expr) {
671        struct TestRewriter {
672            rewrite_to: Expr,
673        }
674
675        impl TreeNodeRewriter for TestRewriter {
676            type Node = Expr;
677
678            fn f_up(&mut self, _: Expr) -> Result<Transformed<Expr>> {
679                Ok(Transformed::yes(self.rewrite_to.clone()))
680            }
681        }
682
683        let mut rewriter = TestRewriter {
684            rewrite_to: rewrite_to.clone(),
685        };
686        let saved_name = NamePreserver { use_alias: true }.save(&expr_from);
687        let new_expr = expr_from.clone().rewrite(&mut rewriter).unwrap().data;
688        let new_expr = saved_name.restore(new_expr);
689
690        let original_name = expr_from.qualified_name();
691        let new_name = new_expr.qualified_name();
692        assert_eq!(
693            original_name, new_name,
694            "mismatch rewriting expr_from: {expr_from} to {rewrite_to}"
695        )
696    }
697}