alamb commented on code in PR #18789:
URL: https://github.com/apache/datafusion/pull/18789#discussion_r2604479324


##########
datafusion/expr/src/udf.rs:
##########
@@ -696,6 +696,33 @@ pub trait ScalarUDFImpl: Debug + DynEq + DynHash + Send + 
Sync {
         Ok(ExprSimplifyResult::Original(args))
     }
 
+    /// Attempts to convert a literal value to in interval of the 
corresponding datatype
+    /// of a column expression so that a **preimage** can be computed for
+    /// pruning comparison predicates.
+    ///
+    /// This is used during predicate-pushdown optimization
+    /// (see 
`datafusion-optimizer-udf_preimage::preimage_in_comparison_for_binary`)
+    ///
+    /// Currently is only implemented by:
+    /// - `date_part(YEAR, expr)`
+    ///
+    /// # Arguments:
+    /// * `lit_value`:  The literal `&ScalarValue` used in comparison
+    /// * `target_type`: The datatype of the column expression inside the 
function
+    ///
+    /// # Returns
+    ///
+    /// Returns an `Interval` of the appropriate target type if a
+    /// preimage cast is supported for the given function/operator combination;
+    /// otherwise returns `None`.
+    fn preimage(
+        &self,
+        _lit_value: &ScalarValue,
+        _target_type: &DataType,

Review Comment:
   Each `ScalarValue` knows its type, so I don't think we need to pass in 
`target_type`, we could get it by calling `ScalarValue::data_type`
   
   
https://docs.rs/datafusion/latest/datafusion/common/enum.ScalarValue.html#method.data_type



##########
datafusion/expr/src/udf.rs:
##########
@@ -696,6 +696,33 @@ pub trait ScalarUDFImpl: Debug + DynEq + DynHash + Send + 
Sync {
         Ok(ExprSimplifyResult::Original(args))
     }
 
+    /// Attempts to convert a literal value to in interval of the 
corresponding datatype
+    /// of a column expression so that a **preimage** can be computed for
+    /// pruning comparison predicates.
+    ///
+    /// This is used during predicate-pushdown optimization
+    /// (see 
`datafusion-optimizer-udf_preimage::preimage_in_comparison_for_binary`)
+    ///
+    /// Currently is only implemented by:
+    /// - `date_part(YEAR, expr)`
+    ///
+    /// # Arguments:
+    /// * `lit_value`:  The literal `&ScalarValue` used in comparison
+    /// * `target_type`: The datatype of the column expression inside the 
function
+    ///
+    /// # Returns
+    ///
+    /// Returns an `Interval` of the appropriate target type if a

Review Comment:
   How about this for a function description? I was trying to summarize what 
the API actually means and here is what I came up with:
   
   ```rust
   /// Returns the [preimage] for this function and the specified scalar value, 
if any. 
   /// 
   /// A preimage is a single contiguous [`Interval`] of values where the 
function
   /// will always return `lit_value`
   ///
   /// 
   /// 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.
   ///
   /// This should only return a preimage if the function takes a single 
argument
   ///
   /// [ClickHouse Paper]:  https://www.vldb.org/pvldb/vol17/p3731-schulze.pdf
   /// [preimage]: 
https://en.wikipedia.org/wiki/Image_(mathematics)#Inverse_image
   
   



##########
datafusion/expr/src/udf.rs:
##########
@@ -696,6 +696,33 @@ pub trait ScalarUDFImpl: Debug + DynEq + DynHash + Send + 
Sync {
         Ok(ExprSimplifyResult::Original(args))
     }
 
+    /// Attempts to convert a literal value to in interval of the 
corresponding datatype
+    /// of a column expression so that a **preimage** can be computed for
+    /// pruning comparison predicates.
+    ///
+    /// This is used during predicate-pushdown optimization
+    /// (see 
`datafusion-optimizer-udf_preimage::preimage_in_comparison_for_binary`)
+    ///
+    /// Currently is only implemented by:
+    /// - `date_part(YEAR, expr)`
+    ///
+    /// # Arguments:
+    /// * `lit_value`:  The literal `&ScalarValue` used in comparison
+    /// * `target_type`: The datatype of the column expression inside the 
function
+    ///
+    /// # Returns
+    ///
+    /// Returns an `Interval` of the appropriate target type if a
+    /// preimage cast is supported for the given function/operator combination;
+    /// otherwise returns `None`.
+    fn preimage(
+        &self,
+        _lit_value: &ScalarValue,
+        _target_type: &DataType,

Review Comment:
   I also think it might be important to pass in a `info: &SimplifyInfo` here



##########
datafusion/functions/src/datetime/date_part.rs:
##########
@@ -240,6 +269,44 @@ impl ScalarUDFImpl for DatePartFunc {
     }
 }
 
+fn date_to_scalar(date: NaiveDate, target_type: &DataType) -> 
Option<ScalarValue> {
+    let scalar = match target_type {
+        Date32 => {
+            let days = date
+                .signed_duration_since(NaiveDate::from_ymd_opt(1970, 1, 1)?)
+                .num_days() as i32;
+            ScalarValue::Date32(Some(days))
+        }
+        Date64 => {
+            let milis = date
+                .signed_duration_since(NaiveDate::from_ymd_opt(1970, 1, 1)?)
+                .num_milliseconds();
+            ScalarValue::Date64(Some(milis))
+        }
+        Timestamp(unit, tz) => {

Review Comment:
   You could probably use these functions: 
https://docs.rs/arrow/latest/arrow/array/temporal_conversions/fn.timestamp_ms_to_datetime.html,
  
https://docs.rs/arrow/latest/arrow/array/temporal_conversions/fn.timestamp_s_to_datetime.html
 ,etc function



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

Review Comment:
   I tried to find an existing function in arrow to do this conversion, but I 
did not find any 😢 
   
   https://docs.rs/arrow/latest/arrow/array/temporal_conversions/index.html



##########
datafusion/optimizer/Cargo.toml:
##########
@@ -49,6 +49,7 @@ chrono = { workspace = true }
 datafusion-common = { workspace = true, default-features = true }
 datafusion-expr = { workspace = true }
 datafusion-expr-common = { workspace = true }
+datafusion-functions = { workspace = true }

Review Comment:
   I think we are trying hard to avoid this dependency -- the optimizer should 
not have to know anything about specific functions, the idea is that the 
optimizer only knows about the UDF APIs
   
   The rationale for avoiding explicit functions is so that DataFusion can work 
with any set of functions, not just built in ones. I'll try and add a comment 
explaining this to the Cargo.toml file as it is not obvious (nor are you the 
first who has tried this approach)



##########
datafusion/optimizer/src/simplify_expressions/udf_preimage.rs:
##########
@@ -0,0 +1,340 @@
+// 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 std::str::FromStr;
+
+use arrow::compute::kernels::cast_utils::IntervalUnit;
+use datafusion_common::{internal_err, tree_node::Transformed, Result, 
ScalarValue};
+use datafusion_expr::{
+    and, expr::ScalarFunction, lit, or, simplify::SimplifyInfo, BinaryExpr, 
Expr,
+    Operator, ScalarUDFImpl,
+};
+use datafusion_functions::datetime::date_part::DatePartFunc;
+
+pub(super) fn preimage_in_comparison_for_binary(

Review Comment:
   A few more comments would really help me to understand what was going on in 
this function 
   
   Perhaps something like
   
   ```rust
   /// 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)
   ```
   
   I am actually not quite sure that is correct
   
   
   
   I also found the code was simpler if the interval was passed in (see my 
suggestion above on the case)
   
   ```rust
   pub(super) fn rewrite_with_preimage(
       info: &dyn SimplifyInfo,
       preimage_interval: Interval,
       op: Operator,
       expr: Box<Expr>,
   ) -> Result<Transformed<Expr>> {
   ```
   
   That way this function only constructed the BinaryExpr from the intervals 🤔 



##########
datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs:
##########
@@ -1960,6 +1964,41 @@ 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 
is_scalar_udf_expr_and_support_preimage_in_comparison_for_binary(
+                    info, &left, op, &right,
+                ) =>
+            {
+                preimage_in_comparison_for_binary(info, *left, *right, op)?
+            }

Review Comment:
   I played around with how this could look. What do you think about something 
like this:
   
   ```rust
               // =======================================
               // 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.as_ref())?.is_some() =>
               {
                   // todo use let binding (if let Some(interval) = ...) once 
stabilized to avoid computing this twice
                   let interval = get_preimage(left.as_ref())?.unwrap();
                   rewrite_with_preimage(info, interval, op, right)?
               }
               // literal op date_part(literal, expression)
               // -->
               // date_part(literal, expression) op_swap literal
               Expr::BinaryExpr(BinaryExpr { left, op, right })
                   if get_preimage(right.as_ref())?.is_some() && 
op.swap().is_some() =>
               {
                   let swapped = op.swap().unwrap();
                   let interval = get_preimage(right.as_ref())?.unwrap();
                   rewrite_with_preimage(info, interval, swapped, left)?
               }
   ```
   
   Where I defined a function like this to call preimage (I don't think I have 
the right signature for extracting the args)
   
   ```rust
   fn get_preimage(expr: &Expr) -> Result<Option<Interval>> {
       let Expr::ScalarFunction(ScalarFunction { func, args }) = expr else {
           return Ok(None);
       };
       func.preimage(args)
   }
   ```
   
   I think it could potentially reduce the boiler plate a bunch



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