sdf-jkl commented on code in PR #18789:
URL: https://github.com/apache/datafusion/pull/18789#discussion_r2643772111
##########
datafusion/core/tests/optimizer/mod.rs:
##########
@@ -378,3 +384,196 @@ fn validate_unchanged_cases(guarantees: &[(Expr,
NullableInterval)], cases: &[Ex
);
}
}
+
+// DatePart preimage tests
+#[test]
+fn test_preimage_date_part_date32_eq() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) = 2024 -> c1 >= 2024-01-01 AND c1 <
2025-01-01
+ let expr_lt = expr_fn::date_part(lit("year"),
col("date32")).eq(lit(2024i32));
+ let expected = and(
+ col("date32").gt_eq(lit(ScalarValue::Date32(Some(19723)))),
+ col("date32").lt(lit(ScalarValue::Date32(Some(20089)))),
+ );
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_date64_not_eq() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) <> 2024 -> c1 < 2024-01-01 AND c1 >=
2025-01-01
+ let expr_lt = expr_fn::date_part(lit("year"),
col("date64")).not_eq(lit(2024i32));
+ let expected = or(
+ col("date64").lt(lit(ScalarValue::Date64(Some(19723 * 86_400_000)))),
+ col("date64").gt_eq(lit(ScalarValue::Date64(Some(20089 *
86_400_000)))),
+ );
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_timestamp_nano_lt() {
+ let schema = expr_test_schema();
+ let expr_lt = expr_fn::date_part(lit("year"),
col("ts_nano_none")).lt(lit(2024i32));
+ let expected = col("ts_nano_none").lt(lit(ScalarValue::TimestampNanosecond(
+ Some(19723 * 86_400_000_000_000),
+ None,
+ )));
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_timestamp_nano_utc_gt() {
+ let schema = expr_test_schema();
+ let expr_lt = expr_fn::date_part(lit("year"),
col("ts_nano_utc")).gt(lit(2024i32));
+ let expected =
col("ts_nano_utc").gt_eq(lit(ScalarValue::TimestampNanosecond(
+ Some(20089 * 86_400_000_000_000),
+ None,
+ )));
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_timestamp_sec_est_gt_eq() {
+ let schema = expr_test_schema();
+ let expr_lt = expr_fn::date_part(lit("year"),
col("ts_sec_est")).gt_eq(lit(2024i32));
+ let expected = col("ts_sec_est").gt_eq(lit(ScalarValue::TimestampSecond(
+ Some(19723 * 86_400),
+ None,
+ )));
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_timestamp_sec_est_lt_eq() {
+ let schema = expr_test_schema();
+ let expr_lt = expr_fn::date_part(lit("year"),
col("ts_mic_pt")).lt_eq(lit(2024i32));
+ let expected = col("ts_mic_pt").lt(lit(ScalarValue::TimestampMicrosecond(
+ Some(20089 * 86_400_000_000),
+ None,
+ )));
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_timestamp_nano_lt_swap() {
+ let schema = expr_test_schema();
+ let expr_lt = lit(2024i32).gt(expr_fn::date_part(lit("year"),
col("ts_nano_none")));
+ let expected = col("ts_nano_none").lt(lit(ScalarValue::TimestampNanosecond(
+ Some(19723 * 86_400_000_000_000),
+ None,
+ )));
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+fn test_preimage_date_part_date32_is_not_distinct_from() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) is not distinct from 2024 -> c1 >=
2024-01-01 AND c1 < 2025-01-01 (the null handling part is dropped since rhs is
not null)
+ let expr_lt = Expr::BinaryExpr(BinaryExpr {
+ left: Box::new(expr_fn::date_part(lit("year"), col("date32"))),
+ op: Operator::IsNotDistinctFrom,
+ right: Box::new(lit(2024i32)),
+ });
+ let expected = and(
+ col("date32").gt_eq(lit(ScalarValue::Date32(Some(19723)))),
+ col("date32").lt(lit(ScalarValue::Date32(Some(20089)))),
+ );
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+// Should not simplify - interval can't be calculated
+fn test_preimage_date_part_date32_is_not_distinct_from_null() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) is not distinct from Null -> unchanged
+ let expr_lt = Expr::BinaryExpr(BinaryExpr {
+ left: Box::new(expr_fn::date_part(lit("year"), col("date32"))),
+ op: Operator::IsNotDistinctFrom,
+ right: Box::new(lit(ScalarValue::Null)),
+ });
+ assert_eq!(optimize_test(expr_lt.clone(), &schema), expr_lt)
+}
+
+#[test]
+fn test_preimage_date_part_date64_is_distinct_from() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) is distinct from 2024 -> c1 < 2024-01-01
OR c1 >= 2025-01-01 or c1 is NULL
+ let expr_lt = Expr::BinaryExpr(BinaryExpr {
+ left: Box::new(expr_fn::date_part(lit("year"), col("date64"))),
+ op: Operator::IsDistinctFrom,
+ right: Box::new(lit(2024i32)),
+ });
+ let expected = col("date64")
+ .lt(lit(ScalarValue::Date64(Some(19723 * 86_400_000))))
+ .or(col("date64").gt_eq(lit(ScalarValue::Date64(Some(20089 *
86_400_000)))))
+ .or(col("date64").is_null());
+ assert_eq!(optimize_test(expr_lt, &schema), expected)
+}
+
+#[test]
+// Should not simplify - interval can't be calculated
+fn test_preimage_date_part_date64_is_distinct_from_null() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) is distinct from 2024 -> c1 < 2024-01-01
OR c1 >= unchanged
+ let expr_lt = Expr::BinaryExpr(BinaryExpr {
+ left: Box::new(expr_fn::date_part(lit("year"), col("date64"))),
+ op: Operator::IsDistinctFrom,
+ right: Box::new(lit(ScalarValue::Null)),
+ });
+ assert_eq!(optimize_test(expr_lt.clone(), &schema), expr_lt)
+}
+
+#[test]
+// Should not simplify
+fn test_preimage_date_part_not_year_date32_eq() {
+ let schema = expr_test_schema();
+ // date_part(c1, DatePart::Year) = 2024 -> c1 >= 2024-01-01 AND c1 <
2025-01-01
+ let expr_lt = expr_fn::date_part(lit("month"),
col("date32")).eq(lit(1i32));
+ assert_eq!(optimize_test(expr_lt.clone(), &schema), expr_lt)
+}
+
+fn optimize_test(expr: Expr, schema: &DFSchemaRef) -> Expr {
+ let props = ExecutionProps::new();
+ let simplifier =
+
ExprSimplifier::new(SimplifyContext::new(&props).with_schema(Arc::clone(schema)));
+
+ simplifier.simplify(expr).unwrap()
+}
+
+fn expr_test_schema() -> DFSchemaRef {
Review Comment:
Changed `Fields` nullability to true to support `IsDistinctFrom` unit test
##########
datafusion/optimizer/src/simplify_expressions/udf_preimage.rs:
##########
@@ -0,0 +1,112 @@
+// 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.
+
+use datafusion_common::{Result, internal_err, tree_node::Transformed};
+use datafusion_expr::{BinaryExpr, Expr, Operator, and, lit, or,
simplify::SimplifyInfo};
+use datafusion_expr_common::interval_arithmetic::Interval;
+
+/// Rewrites a binary expression using its "preimage"
+///
+/// Specifically it rewrites expressions of the form `<expr> OP x` (e.g.
`<expr> =
+/// x`) where `<expr>` is known to have a pre-image (aka the entire single
+/// range for which it is valid)
+///
+/// This rewrite is described in the [ClickHouse Paper] and is particularly
+/// useful for simplifying expressions `date_part` or equivalent functions. The
+/// idea is that if you have an expression like `date_part(YEAR, k) = 2024`
and you
+/// can find a [preimage] for `date_part(YEAR, k)`, which is the range of dates
+/// covering the entire year of 2024. Thus, you can rewrite the expression to
`k
+/// >= '2024-01-01' AND k < '2025-01-01' which is often more optimizable.
+///
+/// [ClickHouse Paper]: https://www.vldb.org/pvldb/vol17/p3731-schulze.pdf
+/// [preimage]: https://en.wikipedia.org/wiki/Image_(mathematics)#Inverse_image
+///
+pub(super) fn rewrite_with_preimage(
+ _info: &dyn SimplifyInfo,
+ preimage_interval: Interval,
+ op: Operator,
+ expr: Box<Expr>,
+) -> Result<Transformed<Expr>> {
+ let (lower, upper) = preimage_interval.into_bounds();
+ let (lower, upper) = (lit(lower), lit(upper));
+
+ let rewritten_expr = match op {
+ // <expr> < x ==> <expr> < upper
+ // <expr> >= x ==> <expr> >= lower
+ Operator::Lt | Operator::GtEq => Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op,
+ right: Box::new(lower),
+ }),
+ // <expr> > x ==> <expr> >= upper
+ Operator::Gt => Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op: Operator::GtEq,
+ right: Box::new(upper),
+ }),
+ // <expr> <= x ==> <expr> < upper
+ Operator::LtEq => Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op: Operator::Lt,
+ right: Box::new(upper),
+ }),
+ // <expr> = x ==> (<expr> >= lower) and (<expr> < upper)
+ //
+ // <expr> is not distinct from x ==> (<expr> is NULL and x is NULL) or
((<expr> >= lower) and (<expr> < upper))
+ // but since x is always not NULL => (<expr> >= lower) and (<expr> <
upper)
+ Operator::Eq | Operator::IsNotDistinctFrom => and(
+ Expr::BinaryExpr(BinaryExpr {
+ left: expr.clone(),
+ op: Operator::GtEq,
+ right: Box::new(lower),
+ }),
+ Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op: Operator::Lt,
+ right: Box::new(upper),
+ }),
+ ),
+ // <expr> != x ==> (<expr> < lower) or (<expr> >= upper)
+ Operator::NotEq => or(
+ Expr::BinaryExpr(BinaryExpr {
+ left: expr.clone(),
+ op: Operator::Lt,
+ right: Box::new(lower),
+ }),
+ Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op: Operator::GtEq,
+ right: Box::new(upper),
+ }),
+ ),
+ // <expr> is distinct from x ==> (<expr> < lower) or (<expr> >= upper)
or (<expr> is NULL and x is not NULL) or (<expr> is not NULL and x is NULL)
+ // but given that x is always not NULL => (<expr> < lower) or (<expr>
>= upper) or (<expr> is NULL)
+ Operator::IsDistinctFrom => Expr::BinaryExpr(BinaryExpr {
Review Comment:
Same as above, for `IsDistinctFrom` rhs can't be `Null`.
We can simplify the `Null` handling part: `(<expr> is NULL and x is not
NULL) or (<expr> is not NULL and x is NULL)` to `(<expr> is NULL)`.
##########
datafusion/optimizer/src/simplify_expressions/udf_preimage.rs:
##########
@@ -0,0 +1,112 @@
+// 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.
+
+use datafusion_common::{Result, internal_err, tree_node::Transformed};
+use datafusion_expr::{BinaryExpr, Expr, Operator, and, lit, or,
simplify::SimplifyInfo};
+use datafusion_expr_common::interval_arithmetic::Interval;
+
+/// Rewrites a binary expression using its "preimage"
+///
+/// Specifically it rewrites expressions of the form `<expr> OP x` (e.g.
`<expr> =
+/// x`) where `<expr>` is known to have a pre-image (aka the entire single
+/// range for which it is valid)
+///
+/// This rewrite is described in the [ClickHouse Paper] and is particularly
+/// useful for simplifying expressions `date_part` or equivalent functions. The
+/// idea is that if you have an expression like `date_part(YEAR, k) = 2024`
and you
+/// can find a [preimage] for `date_part(YEAR, k)`, which is the range of dates
+/// covering the entire year of 2024. Thus, you can rewrite the expression to
`k
+/// >= '2024-01-01' AND k < '2025-01-01' which is often more optimizable.
+///
+/// [ClickHouse Paper]: https://www.vldb.org/pvldb/vol17/p3731-schulze.pdf
+/// [preimage]: https://en.wikipedia.org/wiki/Image_(mathematics)#Inverse_image
+///
+pub(super) fn rewrite_with_preimage(
+ _info: &dyn SimplifyInfo,
+ preimage_interval: Interval,
+ op: Operator,
+ expr: Box<Expr>,
+) -> Result<Transformed<Expr>> {
+ let (lower, upper) = preimage_interval.into_bounds();
+ let (lower, upper) = (lit(lower), lit(upper));
+
+ let rewritten_expr = match op {
+ // <expr> < x ==> <expr> < upper
+ // <expr> >= x ==> <expr> >= lower
+ Operator::Lt | Operator::GtEq => Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op,
+ right: Box::new(lower),
+ }),
+ // <expr> > x ==> <expr> >= upper
+ Operator::Gt => Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op: Operator::GtEq,
+ right: Box::new(upper),
+ }),
+ // <expr> <= x ==> <expr> < upper
+ Operator::LtEq => Expr::BinaryExpr(BinaryExpr {
+ left: expr,
+ op: Operator::Lt,
+ right: Box::new(upper),
+ }),
+ // <expr> = x ==> (<expr> >= lower) and (<expr> < upper)
+ //
+ // <expr> is not distinct from x ==> (<expr> is NULL and x is NULL) or
((<expr> >= lower) and (<expr> < upper))
+ // but since x is always not NULL => (<expr> >= lower) and (<expr> <
upper)
+ Operator::Eq | Operator::IsNotDistinctFrom => and(
Review Comment:
`IsNotDistinctFrom` acts like `Eq`, but handles `Null` differently.
For `IsNotDistinctFrom`:
`Null` = `Null` => True,
While `Eq`:
`Null` = `Null` => False.
Preimage optimization requires an interval to perform this optimization,
therefore, rhs can't be `Null`. We can safely remove the `Null` handling part.
This makes `IsNotDistinctFrom` behavior same as `Eq`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]