sdf-jkl commented on code in PR #18789:
URL: https://github.com/apache/datafusion/pull/18789#discussion_r2615522273


##########
datafusion/functions/src/datetime/date_part.rs:
##########
@@ -378,3 +474,158 @@ fn epoch(array: &dyn Array) -> Result<ArrayRef> {
     };
     Ok(Arc::new(f))
 }
+
+#[cfg(test)]
+mod tests {

Review Comment:
   Moved the unit tests here for now.



##########
datafusion/functions/src/datetime/date_part.rs:
##########
@@ -240,6 +307,35 @@ impl ScalarUDFImpl for DatePartFunc {
     }
 }
 
+fn date_to_scalar(date: NaiveDate, target_type: &DataType) -> 
Option<ScalarValue> {

Review Comment:
   Cleaned this up a little



##########
datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs:
##########
@@ -1960,12 +1962,70 @@ impl<S: SimplifyInfo> TreeNodeRewriter for 
Simplifier<'_, S> {
                 }))
             }
 
+            // =======================================
+            // preimage_in_comparison
+            // =======================================
+            //
+            // For case:
+            // date_part(expr as 'YEAR') op literal
+            //
+            // Background:
+            // Datasources such as Parquet can prune partitions using simple 
predicates,
+            // but they cannot do so for complex expressions.
+            // For a complex predicate like `date_part('YEAR', c1) < 2000`, 
pruning is not possible.
+            // After rewriting it to `c1 < 2000-01-01`, pruning becomes 
feasible.
+            Expr::BinaryExpr(BinaryExpr { left, op, right })
+                if get_preimage(&left, &right, info)?.0.is_some()
+                    && get_preimage(&left, &right, info)?.1.is_some() =>

Review Comment:
   Looking forward to `if let` to be stabilized in `match` guards



##########
datafusion/expr/src/udf.rs:
##########
@@ -226,6 +226,25 @@ impl ScalarUDF {
         self.inner.simplify(args, info)
     }
 
+    /// Return a preimage
+    ///
+    /// See [`ScalarUDFImpl::preimage`] for more details.
+    pub fn preimage(
+        &self,
+        args: &[Expr],
+        lit_expr: &Expr,
+        info: &dyn SimplifyInfo,
+    ) -> Result<Option<Interval>> {
+        self.inner.preimage(args, lit_expr, info)
+    }
+
+    /// Return inner column from function args
+    ///
+    /// See [`ScalarUDFImpl::column_expr`]
+    pub fn column_expr(&self, args: &[Expr]) -> Option<Expr> {
+        self.inner.column_expr(args)

Review Comment:
   Added a little helper method to `ScalarUDFImpl` to extract the inner 
columnar `Expr`



##########
datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs:
##########
@@ -1960,12 +1962,70 @@ impl<S: SimplifyInfo> TreeNodeRewriter for 
Simplifier<'_, S> {
                 }))
             }
 
+            // =======================================
+            // preimage_in_comparison
+            // =======================================
+            //
+            // For case:
+            // date_part(expr as 'YEAR') op literal
+            //
+            // Background:
+            // Datasources such as Parquet can prune partitions using simple 
predicates,
+            // but they cannot do so for complex expressions.
+            // For a complex predicate like `date_part('YEAR', c1) < 2000`, 
pruning is not possible.
+            // After rewriting it to `c1 < 2000-01-01`, pruning becomes 
feasible.
+            Expr::BinaryExpr(BinaryExpr { left, op, right })
+                if get_preimage(&left, &right, info)?.0.is_some()
+                    && get_preimage(&left, &right, info)?.1.is_some() =>
+            {
+                // todo use let binding (if let Some(interval) = ...) once 
stabilized to avoid computing this thrice😢
+                let (Some(interval), Some(col_expr)) =
+                    get_preimage(left.as_ref(), &right, info)?
+                else {
+                    unreachable!(
+                        "The above if statement insures interval and col_expr 
are Some"
+                    )
+                };
+                rewrite_with_preimage(info, interval, op, Box::new(col_expr))?
+            }
+            // literal op date_part(literal, expression)
+            // -->
+            // date_part(literal, expression) op_swap literal
+            Expr::BinaryExpr(BinaryExpr { left, op, right })
+                if get_preimage(&right, &left, info)?.0.is_some()
+                    && get_preimage(&right, &left, info)?.1.is_some()
+                    && op.swap().is_some() =>
+            {
+                let swapped = op.swap().unwrap();
+                let (Some(interval), Some(col_expr)) = get_preimage(&right, 
&left, info)?
+                else {
+                    unreachable!(
+                        "The above if statement insures interval and col_expr 
are Some"
+                    )
+                };
+                rewrite_with_preimage(info, interval, swapped, 
Box::new(col_expr))?
+            }
+
             // no additional rewrites possible
             expr => Transformed::no(expr),
         })
     }
 }
 
+fn get_preimage(
+    left_expr: &Expr,
+    right_expr: &Expr,
+    info: &dyn SimplifyInfo,
+) -> Result<(Option<Interval>, Option<Expr>)> {
+    let Expr::ScalarFunction(ScalarFunction { func, args }) = left_expr else {
+        return Ok((None, None));
+    };
+    Ok((
+        func.preimage(args, right_expr, info)?,
+        func.column_expr(args),

Review Comment:
   Had to add it here, because we already extract the `func, args` here.



##########
datafusion/functions/Cargo.toml:
##########
@@ -76,6 +76,7 @@ datafusion-doc = { workspace = true }
 datafusion-execution = { workspace = true }
 datafusion-expr = { workspace = true }
 datafusion-expr-common = { workspace = true }
+datafusion-optimizer = { workspace = true }

Review Comment:
   If that's ok...



##########
datafusion/optimizer/src/simplify_expressions/udf_preimage.rs:
##########
@@ -0,0 +1,135 @@
+// 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::{internal_err, tree_node::Transformed, Result};
+use datafusion_expr::{and, lit, or, simplify::SimplifyInfo, BinaryExpr, Expr, 
Operator};
+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(

Review Comment:
   Added a little more comments



-- 
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]

Reply via email to