Skip to main content

datafusion_optimizer/simplify_expressions/
simplify_exprs.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//! Simplify expressions optimizer rule and implementation
6
7use std::sync::Arc;
8
9use datafusion_common::tree_node::{Transformed, TreeNode};
10use datafusion_common::{Column, DFSchema, DFSchemaRef, DataFusionError, Result};
11use datafusion_expr::Expr;
12use datafusion_expr::logical_plan::{Aggregate, LogicalPlan, Projection};
13use datafusion_expr::simplify::SimplifyContext;
14use datafusion_expr::utils::{
15    columnize_expr, find_aggregate_exprs, grouping_set_to_exprlist, merge_schema,
16};
17
18use super::ExprSimplifier;
19use crate::optimizer::ApplyOrder;
20use crate::simplify_expressions::linear_aggregates::rewrite_multiple_linear_aggregates;
21use crate::utils::{NamePreserver, merge_into_schema};
22use crate::{OptimizerConfig, OptimizerRule};
23
24/// Optimizer Pass that simplifies [`LogicalPlan`]s by rewriting
25/// [`Expr`]`s evaluating constants and applying algebraic
26/// simplifications
27///
28/// # Introduction
29/// It uses boolean algebra laws to simplify or reduce the number of terms in expressions.
30///
31/// # Example:
32/// `Filter: b > 2 AND b > 2`
33/// is optimized to
34/// `Filter: b > 2`
35///
36/// [`Expr`]: datafusion_expr::Expr
37#[derive(Default, Debug)]
38pub struct SimplifyExpressions {}
39
40impl OptimizerRule for SimplifyExpressions {
41    fn name(&self) -> &str {
42        "simplify_expressions"
43    }
44
45    fn apply_order(&self) -> Option<ApplyOrder> {
46        Some(ApplyOrder::BottomUp)
47    }
48
49    fn rewrite(
50        &self,
51        plan: LogicalPlan,
52        config: &dyn OptimizerConfig,
53    ) -> Result<Transformed<LogicalPlan>, DataFusionError> {
54        Self::optimize_internal(plan, config)
55    }
56}
57
58impl SimplifyExpressions {
59    fn optimize_internal(
60        plan: LogicalPlan,
61        config: &dyn OptimizerConfig,
62    ) -> Result<Transformed<LogicalPlan>> {
63        let schema = if let Some(merge_schema) = merge_into_schema(&plan)? {
64            DFSchemaRef::new(merge_schema)
65        } else if !plan.inputs().is_empty() {
66            DFSchemaRef::new(merge_schema(&plan.inputs()))
67        } else if let LogicalPlan::TableScan(scan) = &plan {
68            // When predicates are pushed into a table scan, there is no input
69            // schema to resolve predicates against, so it must be handled specially
70            //
71            // Note that this is not `plan.schema()` which is the *output*
72            // schema, and reflects any pushed down projection. The output schema
73            // will not contain columns that *only* appear in pushed down predicates
74            // (and no where else) in the plan.
75            //
76            // Thus, use the full schema of the inner provider without any
77            // projection applied for simplification
78            Arc::new(DFSchema::try_from_qualified_schema(
79                scan.table_name.clone(),
80                &scan.source.schema(),
81            )?)
82        } else {
83            Arc::new(DFSchema::empty())
84        };
85
86        let info = SimplifyContext::builder()
87            .with_schema(schema)
88            .with_config_options(config.options())
89            .with_query_execution_start_time(config.query_execution_start_time())
90            .build();
91
92        // Inputs have already been rewritten (due to bottom-up traversal handled by Optimizer)
93        // Just need to rewrite our own expressions
94
95        let simplifier = ExprSimplifier::new(info);
96
97        // The left and right expressions in a Join on clause are not
98        // commutative, for reasons that are not entirely clear. Thus, do not
99        // reorder expressions in Join while simplifying.
100        //
101        // This is likely related to the fact that order of the columns must
102        // match the order of the children. see
103        // https://github.com/apache/datafusion/pull/8780 for more details
104        let simplifier = if let LogicalPlan::Join(_) = plan {
105            simplifier.with_canonicalize(false)
106        } else {
107            simplifier
108        };
109
110        // Preserve expression names to avoid changing the schema of the plan.
111        let name_preserver = NamePreserver::new(&plan);
112        let mut rewrite_expr = |expr: Expr| {
113            let name = name_preserver.save(&expr);
114            let expr = simplifier.simplify_with_cycle_count_transformed(expr)?.0;
115            Ok(Transformed::new_transformed(
116                name.restore(expr.data),
117                expr.transformed,
118            ))
119        };
120
121        plan.map_expressions(|expr| {
122            // Preserve the aliasing of grouping sets.
123            if let Expr::GroupingSet(_) = &expr {
124                expr.map_children(&mut rewrite_expr)
125            } else {
126                rewrite_expr(expr)
127            }
128        })?
129        .transform_data(rewrite_aggregate_non_aggregate_aggr_expr)
130    }
131}
132
133impl SimplifyExpressions {
134    #[expect(missing_docs)]
135    pub fn new() -> Self {
136        Self {}
137    }
138}
139
140/// Ensures that `LogicalPlan::Aggregate` is well formed after rewrites
141/// by potentially introducing an extra `Projection`.
142///
143/// Also applies the [`rewrite_multiple_linear_aggregates`] special case
144///
145/// # Rationale:
146///
147/// [`LogicalPlan::Aggregate`] requires agg expressions to be (possibly aliased)
148/// [`Expr::AggregateFunction`]. Some UDAF simplifiers may return other [`Expr`]
149/// variants.
150///
151/// # Operation
152///
153/// Rewrites things like this (note that `exp1` is not an aggregate):
154/// * `Aggregate(group_expr, aggr_expr=[exp1 + agg(exp2)])`
155///
156/// into:
157/// * `Projection(exp1 + _X)`
158/// * `  Aggregate(group_expr, aggr_expr=[agg(exp2) AS _X])`
159fn rewrite_aggregate_non_aggregate_aggr_expr(
160    plan: LogicalPlan,
161) -> Result<Transformed<LogicalPlan>> {
162    let LogicalPlan::Aggregate(Aggregate {
163        input,
164        group_expr,
165        mut aggr_expr,
166        schema,
167        ..
168    }) = plan
169    else {
170        return Ok(Transformed::no(plan));
171    };
172
173    let rewrote_aggs = rewrite_multiple_linear_aggregates(&mut aggr_expr)?;
174
175    // Ensure that all Aggregate arguments are AggregateExpr
176    if aggr_expr.iter().all(is_top_level_aggregate_expr) {
177        let new_plan = LogicalPlan::Aggregate(Aggregate::try_new_with_schema(
178            input, group_expr, aggr_expr, schema,
179        )?);
180        return if !rewrote_aggs {
181            Ok(Transformed::no(new_plan))
182        } else {
183            Ok(Transformed::yes(new_plan))
184        };
185    }
186
187    // Otherwise we need to add a Projection above Aggregate to calculate
188    // the final output expressions.
189
190    let inner_aggr_expr = find_aggregate_exprs(aggr_expr.iter());
191    let inner_aggregate = LogicalPlan::Aggregate(Aggregate::try_new(
192        Arc::clone(&input),
193        group_expr.clone(),
194        inner_aggr_expr,
195    )?);
196    let inner_aggregate = Arc::new(inner_aggregate);
197
198    let mut projection_exprs = aggregate_output_exprs(&group_expr)?;
199    projection_exprs.extend(aggr_expr);
200    let projection_exprs = projection_exprs
201        .into_iter()
202        .map(|expr| columnize_expr(expr, inner_aggregate.as_ref()))
203        .collect::<Result<Vec<_>>>()?;
204
205    Ok(Transformed::yes(LogicalPlan::Projection(
206        Projection::try_new(projection_exprs, inner_aggregate)?,
207    )))
208}
209
210fn is_top_level_aggregate_expr(expr: &Expr) -> bool {
211    matches!(
212        expr.clone().unalias_nested().data,
213        Expr::AggregateFunction(_)
214    )
215}
216
217fn aggregate_output_exprs(group_expr: &[Expr]) -> Result<Vec<Expr>> {
218    let mut output_exprs = grouping_set_to_exprlist(group_expr)?
219        .into_iter()
220        .cloned()
221        .collect::<Vec<_>>();
222
223    if matches!(group_expr, [Expr::GroupingSet(_)]) {
224        output_exprs.push(Expr::Column(Column::from_name(
225            Aggregate::INTERNAL_GROUPING_ID,
226        )));
227    }
228
229    Ok(output_exprs)
230}
231
232#[cfg(test)]
233mod tests {
234    use std::ops::Not;
235
236    use arrow::datatypes::{DataType, Field, Schema};
237    use chrono::{DateTime, Utc};
238
239    use datafusion_common::ScalarValue;
240    use datafusion_expr::logical_plan::builder::table_scan_with_filters;
241    use datafusion_expr::logical_plan::table_scan;
242    use datafusion_expr::*;
243    use datafusion_functions_aggregate::expr_fn::{max, min, sum};
244
245    use crate::OptimizerContext;
246    use crate::assert_optimized_plan_eq_snapshot;
247    use crate::test::{assert_fields_eq, test_table_scan_with_name};
248
249    use super::*;
250
251    fn test_table_scan() -> LogicalPlan {
252        let schema = Schema::new(vec![
253            Field::new("a", DataType::Boolean, false),
254            Field::new("b", DataType::Boolean, false),
255            Field::new("c", DataType::Boolean, false),
256            Field::new("d", DataType::UInt32, false),
257            Field::new("e", DataType::UInt32, true),
258        ]);
259        table_scan(Some("test"), &schema, None)
260            .expect("creating scan")
261            .build()
262            .expect("building plan")
263    }
264
265    macro_rules! assert_optimized_plan_equal {
266        (
267            $plan:expr,
268            @ $expected:literal $(,)?
269        ) => {{
270            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(SimplifyExpressions::new())];
271            let optimizer_ctx = OptimizerContext::new();
272            assert_optimized_plan_eq_snapshot!(
273                optimizer_ctx,
274                rules,
275                $plan,
276                @ $expected,
277            )
278        }};
279    }
280
281    #[test]
282    fn test_simplify_table_full_filter_in_scan() -> Result<()> {
283        let fields = vec![
284            Field::new("a", DataType::UInt32, false),
285            Field::new("b", DataType::UInt32, false),
286            Field::new("c", DataType::UInt32, false),
287        ];
288
289        let schema = Schema::new(fields);
290
291        let table_scan = table_scan_with_filters(
292            Some("test"),
293            &schema,
294            Some(vec![0]),
295            vec![col("b").is_not_null()],
296        )?
297        .build()?;
298        assert_eq!(1, table_scan.schema().fields().len());
299        assert_fields_eq(&table_scan, vec!["a"]);
300
301        assert_optimized_plan_equal!(
302            table_scan,
303            @ "TableScan: test projection=[a], full_filters=[Boolean(true)]"
304        )
305    }
306
307    #[test]
308    fn test_simplify_filter_pushdown() -> Result<()> {
309        let table_scan = test_table_scan();
310        let plan = LogicalPlanBuilder::from(table_scan)
311            .project(vec![col("a")])?
312            .filter(and(col("b").gt(lit(1)), col("b").gt(lit(1))))?
313            .build()?;
314
315        assert_optimized_plan_equal!(
316            plan,
317            @ r"
318        Filter: test.b > Int32(1)
319          Projection: test.a
320            TableScan: test
321        "
322        )
323    }
324
325    #[test]
326    fn test_simplify_optimized_plan() -> Result<()> {
327        let table_scan = test_table_scan();
328        let plan = LogicalPlanBuilder::from(table_scan)
329            .project(vec![col("a")])?
330            .filter(and(col("b").gt(lit(1)), col("b").gt(lit(1))))?
331            .build()?;
332
333        assert_optimized_plan_equal!(
334            plan,
335            @ r"
336        Filter: test.b > Int32(1)
337          Projection: test.a
338            TableScan: test
339        "
340        )
341    }
342
343    #[test]
344    fn test_simplify_udaf_to_non_aggregate_expr() -> Result<()> {
345        let schema = Schema::new(vec![Field::new("a", DataType::Int64, false)]);
346        let table_scan = table_scan(Some("test"), &schema, None)?
347            .build()
348            .expect("building scan");
349
350        let plan = LogicalPlanBuilder::from(table_scan)
351            .aggregate(Vec::<Expr>::new(), vec![sum(col("a") + lit(2i64))])?
352            .build()?;
353
354        assert_optimized_plan_equal!(
355            plan,
356            @r"
357        Aggregate: groupBy=[[]], aggr=[[sum(test.a + Int64(2))]]
358          TableScan: test
359        "
360        )?;
361        Ok(())
362    }
363
364    #[test]
365    fn test_simplify_common_sum_arg() -> Result<()> {
366        let schema = Schema::new(vec![Field::new("a", DataType::Int64, false)]);
367        let table_scan = table_scan(Some("test"), &schema, None)?
368            .build()
369            .expect("building scan");
370
371        let plan = LogicalPlanBuilder::from(table_scan)
372            .aggregate(
373                Vec::<Expr>::new(),
374                vec![sum(col("a") + lit(2i64)), sum(col("a") + lit(3i64))],
375            )?
376            .build()?;
377
378        assert_optimized_plan_equal!(
379            plan,
380            @r"
381        Projection: sum(test.a) + Int64(2) * CAST(count(test.a) AS Int64) AS sum(test.a + Int64(2)), sum(test.a) + Int64(3) * CAST(count(test.a) AS Int64) AS sum(test.a + Int64(3))
382          Aggregate: groupBy=[[]], aggr=[[sum(test.a), count(test.a)]]
383            TableScan: test
384        "
385        )?;
386        Ok(())
387    }
388
389    #[test]
390    fn test_simplify_optimized_plan_with_or() -> Result<()> {
391        let table_scan = test_table_scan();
392        let plan = LogicalPlanBuilder::from(table_scan)
393            .project(vec![col("a")])?
394            .filter(or(col("b").gt(lit(1)), col("b").gt(lit(1))))?
395            .build()?;
396
397        assert_optimized_plan_equal!(
398            plan,
399            @ r"
400        Filter: test.b > Int32(1)
401          Projection: test.a
402            TableScan: test
403        "
404        )
405    }
406
407    #[test]
408    fn test_simplify_optimized_plan_with_composed_and() -> Result<()> {
409        let table_scan = test_table_scan();
410        // ((c > 5) AND (d < 6)) AND (c > 5) --> (c > 5) AND (d < 6)
411        let plan = LogicalPlanBuilder::from(table_scan)
412            .project(vec![col("a"), col("b")])?
413            .filter(and(
414                and(col("a").gt(lit(5)), col("b").lt(lit(6))),
415                col("a").gt(lit(5)),
416            ))?
417            .build()?;
418
419        assert_optimized_plan_equal!(
420            plan,
421            @ r"
422        Filter: test.a > Int32(5) AND test.b < Int32(6)
423          Projection: test.a, test.b
424            TableScan: test
425        "
426        )
427    }
428
429    #[test]
430    fn test_simplify_optimized_plan_eq_expr() -> Result<()> {
431        let table_scan = test_table_scan();
432        let plan = LogicalPlanBuilder::from(table_scan)
433            .filter(col("b").eq(lit(true)))?
434            .filter(col("c").eq(lit(false)))?
435            .project(vec![col("a")])?
436            .build()?;
437
438        assert_optimized_plan_equal!(
439            plan,
440            @ r"
441        Projection: test.a
442          Filter: NOT test.c
443            Filter: test.b
444              TableScan: test
445        "
446        )
447    }
448
449    #[test]
450    fn test_simplify_optimized_plan_not_eq_expr() -> Result<()> {
451        let table_scan = test_table_scan();
452        let plan = LogicalPlanBuilder::from(table_scan)
453            .filter(col("b").not_eq(lit(true)))?
454            .filter(col("c").not_eq(lit(false)))?
455            .limit(0, Some(1))?
456            .project(vec![col("a")])?
457            .build()?;
458
459        assert_optimized_plan_equal!(
460            plan,
461            @ r"
462        Projection: test.a
463          Limit: skip=0, fetch=1
464            Filter: test.c
465              Filter: NOT test.b
466                TableScan: test
467        "
468        )
469    }
470
471    #[test]
472    fn test_simplify_optimized_plan_and_expr() -> Result<()> {
473        let table_scan = test_table_scan();
474        let plan = LogicalPlanBuilder::from(table_scan)
475            .filter(col("b").not_eq(lit(true)).and(col("c").eq(lit(true))))?
476            .project(vec![col("a")])?
477            .build()?;
478
479        assert_optimized_plan_equal!(
480            plan,
481            @ r"
482        Projection: test.a
483          Filter: NOT test.b AND test.c
484            TableScan: test
485        "
486        )
487    }
488
489    #[test]
490    fn test_simplify_optimized_plan_or_expr() -> Result<()> {
491        let table_scan = test_table_scan();
492        let plan = LogicalPlanBuilder::from(table_scan)
493            .filter(col("b").not_eq(lit(true)).or(col("c").eq(lit(false))))?
494            .project(vec![col("a")])?
495            .build()?;
496
497        assert_optimized_plan_equal!(
498            plan,
499            @ r"
500        Projection: test.a
501          Filter: NOT test.b OR NOT test.c
502            TableScan: test
503        "
504        )
505    }
506
507    #[test]
508    fn test_simplify_optimized_plan_not_expr() -> Result<()> {
509        let table_scan = test_table_scan();
510        let plan = LogicalPlanBuilder::from(table_scan)
511            .filter(col("b").eq(lit(false)).not())?
512            .project(vec![col("a")])?
513            .build()?;
514
515        assert_optimized_plan_equal!(
516            plan,
517            @ r"
518        Projection: test.a
519          Filter: test.b
520            TableScan: test
521        "
522        )
523    }
524
525    #[test]
526    fn test_simplify_optimized_plan_support_projection() -> Result<()> {
527        let table_scan = test_table_scan();
528        let plan = LogicalPlanBuilder::from(table_scan)
529            .project(vec![col("a"), col("d"), col("b").eq(lit(false))])?
530            .build()?;
531
532        assert_optimized_plan_equal!(
533            plan,
534            @ r"
535        Projection: test.a, test.d, NOT test.b AS test.b = Boolean(false)
536          TableScan: test
537        "
538        )
539    }
540
541    #[test]
542    fn test_simplify_optimized_plan_support_aggregate() -> Result<()> {
543        let table_scan = test_table_scan();
544        let plan = LogicalPlanBuilder::from(table_scan)
545            .project(vec![col("a"), col("c"), col("b")])?
546            .aggregate(
547                vec![col("a"), col("c")],
548                vec![max(col("b").eq(lit(true))), min(col("b"))],
549            )?
550            .build()?;
551
552        assert_optimized_plan_equal!(
553            plan,
554            @ r"
555        Aggregate: groupBy=[[test.a, test.c]], aggr=[[max(test.b) AS max(test.b = Boolean(true)), min(test.b)]]
556          Projection: test.a, test.c, test.b
557            TableScan: test
558        "
559        )
560    }
561
562    #[test]
563    fn test_simplify_optimized_plan_support_values() -> Result<()> {
564        let expr1 = Expr::BinaryExpr(BinaryExpr::new(
565            Box::new(lit(1)),
566            Operator::Plus,
567            Box::new(lit(2)),
568        ));
569        let expr2 = Expr::BinaryExpr(BinaryExpr::new(
570            Box::new(lit(2)),
571            Operator::Minus,
572            Box::new(lit(1)),
573        ));
574        let values = vec![vec![expr1, expr2]];
575        let plan = LogicalPlanBuilder::values(values)?.build()?;
576
577        assert_optimized_plan_equal!(
578            plan,
579            @ "Values: (Int32(3) AS Int32(1) + Int32(2), Int32(1) AS Int32(2) - Int32(1))"
580        )
581    }
582
583    fn get_optimized_plan_formatted(
584        plan: LogicalPlan,
585        date_time: &DateTime<Utc>,
586    ) -> String {
587        let config = OptimizerContext::new().with_query_execution_start_time(*date_time);
588        let rule = SimplifyExpressions::new();
589
590        let optimized_plan = rule.rewrite(plan, &config).unwrap().data;
591        format!("{optimized_plan}")
592    }
593
594    #[test]
595    fn cast_expr() -> Result<()> {
596        let table_scan = test_table_scan();
597        let proj = vec![Expr::Cast(Cast::new(Box::new(lit("0")), DataType::Int32))];
598        let plan = LogicalPlanBuilder::from(table_scan)
599            .project(proj)?
600            .build()?;
601
602        let expected = "Projection: Int32(0) AS Utf8(\"0\")\
603            \n  TableScan: test";
604        let actual = get_optimized_plan_formatted(plan, &Utc::now());
605        assert_eq!(expected, actual);
606        Ok(())
607    }
608
609    #[test]
610    fn simplify_and_eval() -> Result<()> {
611        // demonstrate a case where the evaluation needs to run prior
612        // to the simplifier for it to work
613        let table_scan = test_table_scan();
614        let time = Utc::now();
615        // (true or false) != col --> !col
616        let proj = vec![lit(true).or(lit(false)).not_eq(col("a"))];
617        let plan = LogicalPlanBuilder::from(table_scan)
618            .project(proj)?
619            .build()?;
620
621        let actual = get_optimized_plan_formatted(plan, &time);
622        let expected = "Projection: NOT test.a AS Boolean(true) OR Boolean(false) != test.a\
623                        \n  TableScan: test";
624
625        assert_eq!(expected, actual);
626        Ok(())
627    }
628
629    #[test]
630    fn simplify_not_binary() -> Result<()> {
631        let table_scan = test_table_scan();
632
633        let plan = LogicalPlanBuilder::from(table_scan)
634            .filter(col("d").gt(lit(10)).not())?
635            .build()?;
636
637        assert_optimized_plan_equal!(
638            plan,
639            @ r"
640        Filter: test.d <= Int32(10)
641          TableScan: test
642        "
643        )
644    }
645
646    #[test]
647    fn simplify_not_bool_and() -> Result<()> {
648        let table_scan = test_table_scan();
649
650        let plan = LogicalPlanBuilder::from(table_scan)
651            .filter(col("d").gt(lit(10)).and(col("d").lt(lit(100))).not())?
652            .build()?;
653
654        assert_optimized_plan_equal!(
655            plan,
656            @ r"
657        Filter: test.d <= Int32(10) OR test.d >= Int32(100)
658          TableScan: test
659        "
660        )
661    }
662
663    #[test]
664    fn simplify_not_bool_or() -> Result<()> {
665        let table_scan = test_table_scan();
666
667        let plan = LogicalPlanBuilder::from(table_scan)
668            .filter(col("d").gt(lit(10)).or(col("d").lt(lit(100))).not())?
669            .build()?;
670
671        assert_optimized_plan_equal!(
672            plan,
673            @ r"
674        Filter: test.d <= Int32(10) AND test.d >= Int32(100)
675          TableScan: test
676        "
677        )
678    }
679
680    #[test]
681    fn simplify_not_not() -> Result<()> {
682        let table_scan = test_table_scan();
683
684        let plan = LogicalPlanBuilder::from(table_scan)
685            .filter(col("d").gt(lit(10)).not().not())?
686            .build()?;
687
688        assert_optimized_plan_equal!(
689            plan,
690            @ r"
691        Filter: test.d > Int32(10)
692          TableScan: test
693        "
694        )
695    }
696
697    #[test]
698    fn simplify_not_null() -> Result<()> {
699        let table_scan = test_table_scan();
700
701        let plan = LogicalPlanBuilder::from(table_scan)
702            .filter(col("e").is_null().not())?
703            .build()?;
704
705        assert_optimized_plan_equal!(
706            plan,
707            @ r"
708        Filter: test.e IS NOT NULL
709          TableScan: test
710        "
711        )
712    }
713
714    #[test]
715    fn simplify_not_not_null() -> Result<()> {
716        let table_scan = test_table_scan();
717
718        let plan = LogicalPlanBuilder::from(table_scan)
719            .filter(col("e").is_not_null().not())?
720            .build()?;
721
722        assert_optimized_plan_equal!(
723            plan,
724            @ r"
725        Filter: test.e IS NULL
726          TableScan: test
727        "
728        )
729    }
730
731    #[test]
732    fn simplify_not_in() -> Result<()> {
733        let table_scan = test_table_scan();
734
735        let plan = LogicalPlanBuilder::from(table_scan)
736            .filter(col("d").in_list(vec![lit(1), lit(2), lit(3)], false).not())?
737            .build()?;
738
739        assert_optimized_plan_equal!(
740            plan,
741            @ r"
742        Filter: test.d != Int32(1) AND test.d != Int32(2) AND test.d != Int32(3)
743          TableScan: test
744        "
745        )
746    }
747
748    #[test]
749    fn simplify_not_not_in() -> Result<()> {
750        let table_scan = test_table_scan();
751
752        let plan = LogicalPlanBuilder::from(table_scan)
753            .filter(col("d").in_list(vec![lit(1), lit(2), lit(3)], true).not())?
754            .build()?;
755
756        assert_optimized_plan_equal!(
757            plan,
758            @ r"
759        Filter: test.d = Int32(1) OR test.d = Int32(2) OR test.d = Int32(3)
760          TableScan: test
761        "
762        )
763    }
764
765    #[test]
766    fn simplify_not_between() -> Result<()> {
767        let table_scan = test_table_scan();
768        let qual = col("d").between(lit(1), lit(10));
769
770        let plan = LogicalPlanBuilder::from(table_scan)
771            .filter(qual.not())?
772            .build()?;
773
774        assert_optimized_plan_equal!(
775            plan,
776            @ r"
777        Filter: test.d < Int32(1) OR test.d > Int32(10)
778          TableScan: test
779        "
780        )
781    }
782
783    #[test]
784    fn simplify_not_not_between() -> Result<()> {
785        let table_scan = test_table_scan();
786        let qual = col("d").not_between(lit(1), lit(10));
787
788        let plan = LogicalPlanBuilder::from(table_scan)
789            .filter(qual.not())?
790            .build()?;
791
792        assert_optimized_plan_equal!(
793            plan,
794            @ r"
795        Filter: test.d >= Int32(1) AND test.d <= Int32(10)
796          TableScan: test
797        "
798        )
799    }
800
801    #[test]
802    fn simplify_not_like() -> Result<()> {
803        let schema = Schema::new(vec![
804            Field::new("a", DataType::Utf8, false),
805            Field::new("b", DataType::Utf8, false),
806        ]);
807        let table_scan = table_scan(Some("test"), &schema, None)
808            .expect("creating scan")
809            .build()
810            .expect("building plan");
811
812        let plan = LogicalPlanBuilder::from(table_scan)
813            .filter(col("a").like(col("b")).not())?
814            .build()?;
815
816        assert_optimized_plan_equal!(
817            plan,
818            @ r"
819        Filter: test.a NOT LIKE test.b
820          TableScan: test
821        "
822        )
823    }
824
825    #[test]
826    fn simplify_not_not_like() -> Result<()> {
827        let schema = Schema::new(vec![
828            Field::new("a", DataType::Utf8, false),
829            Field::new("b", DataType::Utf8, false),
830        ]);
831        let table_scan = table_scan(Some("test"), &schema, None)
832            .expect("creating scan")
833            .build()
834            .expect("building plan");
835
836        let plan = LogicalPlanBuilder::from(table_scan)
837            .filter(col("a").not_like(col("b")).not())?
838            .build()?;
839
840        assert_optimized_plan_equal!(
841            plan,
842            @ r"
843        Filter: test.a LIKE test.b
844          TableScan: test
845        "
846        )
847    }
848
849    #[test]
850    fn simplify_not_ilike() -> Result<()> {
851        let schema = Schema::new(vec![
852            Field::new("a", DataType::Utf8, false),
853            Field::new("b", DataType::Utf8, false),
854        ]);
855        let table_scan = table_scan(Some("test"), &schema, None)
856            .expect("creating scan")
857            .build()
858            .expect("building plan");
859
860        let plan = LogicalPlanBuilder::from(table_scan)
861            .filter(col("a").ilike(col("b")).not())?
862            .build()?;
863
864        assert_optimized_plan_equal!(
865            plan,
866            @ r"
867        Filter: test.a NOT ILIKE test.b
868          TableScan: test
869        "
870        )
871    }
872
873    #[test]
874    fn simplify_not_distinct_from() -> Result<()> {
875        let table_scan = test_table_scan();
876
877        let plan = LogicalPlanBuilder::from(table_scan)
878            .filter(binary_expr(col("d"), Operator::IsDistinctFrom, lit(10)).not())?
879            .build()?;
880
881        assert_optimized_plan_equal!(
882            plan,
883            @ r"
884        Filter: test.d IS NOT DISTINCT FROM Int32(10)
885          TableScan: test
886        "
887        )
888    }
889
890    #[test]
891    fn simplify_not_not_distinct_from() -> Result<()> {
892        let table_scan = test_table_scan();
893
894        let plan = LogicalPlanBuilder::from(table_scan)
895            .filter(binary_expr(col("d"), Operator::IsNotDistinctFrom, lit(10)).not())?
896            .build()?;
897
898        assert_optimized_plan_equal!(
899            plan,
900            @ r"
901        Filter: test.d IS DISTINCT FROM Int32(10)
902          TableScan: test
903        "
904        )
905    }
906
907    #[test]
908    fn simplify_equijoin_predicate() -> Result<()> {
909        let t1 = test_table_scan_with_name("t1")?;
910        let t2 = test_table_scan_with_name("t2")?;
911
912        let left_key = col("t1.a") + lit(1i64).cast_to(&DataType::UInt32, t1.schema())?;
913        let right_key =
914            col("t2.a") + lit(2i64).cast_to(&DataType::UInt32, t2.schema())?;
915        let plan = LogicalPlanBuilder::from(t1)
916            .join_with_expr_keys(
917                t2,
918                JoinType::Inner,
919                (vec![left_key], vec![right_key]),
920                None,
921            )?
922            .build()?;
923
924        // before simplify: t1.a + CAST(Int64(1), UInt32) = t2.a + CAST(Int64(2), UInt32)
925        // after simplify: t1.a + UInt32(1) = t2.a + UInt32(2) AS t1.a + Int64(1) = t2.a + Int64(2)
926        assert_optimized_plan_equal!(
927            plan,
928            @ r"
929        Inner Join: t1.a + UInt32(1) = t2.a + UInt32(2)
930          TableScan: t1
931          TableScan: t2
932        "
933        )
934    }
935
936    #[test]
937    fn simplify_is_not_null() -> Result<()> {
938        let table_scan = test_table_scan();
939
940        let plan = LogicalPlanBuilder::from(table_scan)
941            .filter(col("d").is_not_null())?
942            .build()?;
943
944        assert_optimized_plan_equal!(
945            plan,
946            @ r"
947        Filter: Boolean(true)
948          TableScan: test
949        "
950        )
951    }
952
953    #[test]
954    fn simplify_is_null() -> Result<()> {
955        let table_scan = test_table_scan();
956
957        let plan = LogicalPlanBuilder::from(table_scan)
958            .filter(col("d").is_null())?
959            .build()?;
960
961        assert_optimized_plan_equal!(
962            plan,
963            @ r"
964        Filter: Boolean(false)
965          TableScan: test
966        "
967        )
968    }
969
970    #[test]
971    fn simplify_grouping_sets() -> Result<()> {
972        let table_scan = test_table_scan();
973        let plan = LogicalPlanBuilder::from(table_scan)
974            .aggregate(
975                [grouping_set(vec![
976                    vec![(lit(42).alias("prev") + lit(1)).alias("age"), col("a")],
977                    vec![col("a").or(col("b")).and(lit(1).lt(lit(0))).alias("cond")],
978                    vec![col("d").alias("e"), (lit(1) + lit(2))],
979                ])],
980                [] as [Expr; 0],
981            )?
982            .build()?;
983
984        assert_optimized_plan_equal!(
985            plan,
986            @ r"
987        Aggregate: groupBy=[[GROUPING SETS ((Int32(43) AS age, test.a), (Boolean(false) AS cond), (test.d AS e, Int32(3) AS Int32(1) + Int32(2)))]], aggr=[[]]
988          TableScan: test
989        "
990        )
991    }
992
993    #[test]
994    fn test_simplify_regex_special_cases() -> Result<()> {
995        let schema = Schema::new(vec![
996            Field::new("a", DataType::Utf8, true),
997            Field::new("b", DataType::Utf8, false),
998        ]);
999        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1000
1001        // Test `~ ".*"` is TRUE for any non-NULL string and NULL for a NULL input
1002        let plan = LogicalPlanBuilder::from(table_scan.clone())
1003            .filter(binary_expr(col("a"), Operator::RegexMatch, lit(".*")))?
1004            .build()?;
1005
1006        assert_optimized_plan_equal!(
1007            plan,
1008            @ r"
1009        Filter: test.a IS NOT NULL OR Boolean(NULL)
1010          TableScan: test
1011        "
1012        )?;
1013
1014        // Test `!~ ".*"` preserves NULL semantics while remaining false for non-NULL strings
1015        let plan = LogicalPlanBuilder::from(table_scan.clone())
1016            .filter(binary_expr(col("a"), Operator::RegexNotMatch, lit(".*")))?
1017            .build()?;
1018
1019        assert_optimized_plan_equal!(
1020            plan,
1021            @ r"
1022        Filter: test.a IS NULL AND Boolean(NULL)
1023          TableScan: test
1024        "
1025        )?;
1026
1027        // Test case-insensitive versions
1028
1029        // Test `~* ".*"` transforms to true for any non-NULL string
1030        let plan = LogicalPlanBuilder::from(table_scan.clone())
1031            .filter(binary_expr(col("b"), Operator::RegexIMatch, lit(".*")))?
1032            .build()?;
1033
1034        assert_optimized_plan_equal!(
1035            plan,
1036            @ r"
1037        Filter: Boolean(true)
1038          TableScan: test
1039        "
1040        )?;
1041
1042        // Test NULL `!~ ".*"` transforms to Boolean(NULL)
1043        let plan = LogicalPlanBuilder::from(table_scan.clone())
1044            .filter(binary_expr(
1045                lit(ScalarValue::Utf8(None)),
1046                Operator::RegexNotMatch,
1047                lit(".*"),
1048            ))?
1049            .build()?;
1050
1051        assert_optimized_plan_equal!(
1052            plan,
1053            @ r"
1054        Filter: Boolean(NULL)
1055          TableScan: test
1056        "
1057        )?;
1058
1059        // Test `!~* ".*"` preserves NULL semantics while remaining false for non-NULL strings
1060        let plan = LogicalPlanBuilder::from(table_scan.clone())
1061            .filter(binary_expr(col("a"), Operator::RegexNotIMatch, lit(".*")))?
1062            .build()?;
1063
1064        assert_optimized_plan_equal!(
1065            plan,
1066            @ r"
1067        Filter: test.a IS NULL AND Boolean(NULL)
1068          TableScan: test
1069        "
1070        )?;
1071
1072        // Test NULL `!~* ".*"` transforms to Boolean(NULL)
1073        let plan = LogicalPlanBuilder::from(table_scan.clone())
1074            .filter(binary_expr(
1075                lit(ScalarValue::Utf8(None)),
1076                Operator::RegexNotIMatch,
1077                lit(".*"),
1078            ))?
1079            .build()?;
1080
1081        assert_optimized_plan_equal!(
1082            plan,
1083            @ r"
1084        Filter: Boolean(NULL)
1085          TableScan: test
1086        "
1087        )
1088    }
1089
1090    #[test]
1091    fn simplify_not_in_list() -> Result<()> {
1092        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1093        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1094
1095        let plan = LogicalPlanBuilder::from(table_scan)
1096            .filter(col("a").in_list(vec![lit("a"), lit("b")], false).not())?
1097            .build()?;
1098
1099        assert_optimized_plan_equal!(
1100            plan,
1101            @ r#"
1102        Filter: test.a != Utf8("a") AND test.a != Utf8("b")
1103          TableScan: test
1104        "#
1105        )
1106    }
1107
1108    #[test]
1109    fn simplify_not_not_in_list() -> Result<()> {
1110        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1111        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1112
1113        let plan = LogicalPlanBuilder::from(table_scan)
1114            .filter(
1115                col("a")
1116                    .in_list(vec![lit("a"), lit("b")], false)
1117                    .not()
1118                    .not(),
1119            )?
1120            .build()?;
1121
1122        assert_optimized_plan_equal!(
1123            plan,
1124            @ r#"
1125        Filter: test.a = Utf8("a") OR test.a = Utf8("b")
1126          TableScan: test
1127        "#
1128        )
1129    }
1130
1131    #[test]
1132    fn simplify_not_exists() -> Result<()> {
1133        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1134        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1135        let table_scan2 =
1136            datafusion_expr::table_scan(Some("test2"), &schema, None)?.build()?;
1137
1138        let plan = LogicalPlanBuilder::from(table_scan)
1139            .filter(
1140                exists(Arc::new(LogicalPlanBuilder::from(table_scan2).build()?)).not(),
1141            )?
1142            .build()?;
1143
1144        assert_optimized_plan_equal!(
1145            plan,
1146            @ r"
1147        Filter: NOT EXISTS (<subquery>)
1148          Subquery:
1149            TableScan: test2
1150          TableScan: test
1151        "
1152        )
1153    }
1154
1155    #[test]
1156    fn simplify_not_not_exists() -> Result<()> {
1157        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1158        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1159        let table_scan2 =
1160            datafusion_expr::table_scan(Some("test2"), &schema, None)?.build()?;
1161
1162        let plan = LogicalPlanBuilder::from(table_scan)
1163            .filter(
1164                exists(Arc::new(LogicalPlanBuilder::from(table_scan2).build()?))
1165                    .not()
1166                    .not(),
1167            )?
1168            .build()?;
1169
1170        assert_optimized_plan_equal!(
1171            plan,
1172            @ r"
1173        Filter: EXISTS (<subquery>)
1174          Subquery:
1175            TableScan: test2
1176          TableScan: test
1177        "
1178        )
1179    }
1180
1181    #[test]
1182    fn simplify_not_in_subquery() -> Result<()> {
1183        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1184        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1185        let table_scan2 =
1186            datafusion_expr::table_scan(Some("test2"), &schema, None)?.build()?;
1187
1188        let plan = LogicalPlanBuilder::from(table_scan)
1189            .filter(
1190                in_subquery(
1191                    col("a"),
1192                    Arc::new(LogicalPlanBuilder::from(table_scan2).build()?),
1193                )
1194                .not(),
1195            )?
1196            .build()?;
1197
1198        assert_optimized_plan_equal!(
1199            plan,
1200            @ r"
1201        Filter: test.a NOT IN (<subquery>)
1202          Subquery:
1203            TableScan: test2
1204          TableScan: test
1205        "
1206        )
1207    }
1208
1209    #[test]
1210    fn simplify_not_not_in_subquery() -> Result<()> {
1211        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1212        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1213        let table_scan2 =
1214            datafusion_expr::table_scan(Some("test2"), &schema, None)?.build()?;
1215
1216        let plan = LogicalPlanBuilder::from(table_scan)
1217            .filter(
1218                in_subquery(
1219                    col("a"),
1220                    Arc::new(LogicalPlanBuilder::from(table_scan2).build()?),
1221                )
1222                .not()
1223                .not(),
1224            )?
1225            .build()?;
1226
1227        assert_optimized_plan_equal!(
1228            plan,
1229            @ r"
1230        Filter: test.a IN (<subquery>)
1231          Subquery:
1232            TableScan: test2
1233          TableScan: test
1234        "
1235        )
1236    }
1237}