alamb commented on a change in pull request #288:
URL: https://github.com/apache/arrow-datafusion/pull/288#discussion_r629262731



##########
File path: datafusion/src/execution/context.rs
##########
@@ -740,6 +748,12 @@ impl ExecutionConfig {
     }
 }
 
+/// Current execution props

Review comment:
       ```suggestion
   /// Holds per-execution properties and data (such as starting timestamps, 
etc). 
   /// An instance of this struct is created each time a [`LogicalPlan`] is 
prepared for 
   /// execution (optimized). If the same plan is optimized multiple times, a 
new 
   /// `ExecutionProps` is created each time. 
   ```

##########
File path: datafusion/src/optimizer/timestamp_evaluation.rs
##########
@@ -0,0 +1,177 @@
+// 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.
+
+//! Optimizer rule to replace timestamp expressions to constants.
+//! This saves time in planning and executing the query.
+use crate::error::Result;
+use crate::logical_plan::{Expr, LogicalPlan};
+use crate::optimizer::optimizer::OptimizerRule;
+
+use super::utils;
+use crate::execution::context::ExecutionProps;
+use crate::physical_plan::functions::BuiltinScalarFunction;
+use crate::scalar::ScalarValue;
+use chrono::{DateTime, Utc};
+
+/// Optimization rule that replaces timestamp expressions with their values 
evaluated

Review comment:
       What would you think about extending the `constant_folding` optimizer 
rule instead of adding an entirely new rule?
   
   I think you could probably add a case to the expression rewriter in 
https://github.com/apache/arrow-datafusion/blob/master/datafusion/src/optimizer/constant_folding.rs#L122
 for `Expr::ScalarFunction { fun: BuiltinScalarFunction::Now}}`  and avoid the 
need for all the code in this pass for traversing the expression tree. 
   
   

##########
File path: datafusion/tests/sql.rs
##########
@@ -2738,6 +2738,24 @@ async fn test_cast_expressions() -> Result<()> {
     Ok(())
 }
 
+#[tokio::test]
+async fn test_timestamp_expressions() -> Result<()> {
+    let t1 = chrono::Utc::now().timestamp();
+    let mut ctx = ExecutionContext::new();
+    let actual = execute(&mut ctx, "SELECT NOW(), NOW() as t2").await;
+    let res1 = actual[0][0].as_str();
+    let res2 = actual[0][1].as_str();
+    let t3 = chrono::Utc::now().timestamp();
+    let t2_naive =

Review comment:
       👍  good test. 

##########
File path: datafusion/src/optimizer/timestamp_evaluation.rs
##########
@@ -0,0 +1,177 @@
+// 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.
+
+//! Optimizer rule to replace timestamp expressions to constants.
+//! This saves time in planning and executing the query.
+use crate::error::Result;
+use crate::logical_plan::{Expr, LogicalPlan};
+use crate::optimizer::optimizer::OptimizerRule;
+
+use super::utils;
+use crate::execution::context::ExecutionProps;
+use crate::physical_plan::functions::BuiltinScalarFunction;
+use crate::scalar::ScalarValue;
+use chrono::{DateTime, Utc};
+
+/// Optimization rule that replaces timestamp expressions with their values 
evaluated
+pub struct TimestampEvaluation {}
+
+impl TimestampEvaluation {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+
+    /// Recursive function to optimize the now expression
+    pub fn rewrite_expr(&self, exp: &Expr, date_time: &DateTime<Utc>) -> 
Result<Expr> {
+        let expressions = utils::expr_sub_expressions(exp).unwrap();
+        let expressions = expressions
+            .iter()
+            .map(|e| self.rewrite_expr(e, date_time))
+            .collect::<Result<Vec<_>>>()?;
+
+        let exp = match exp {
+            Expr::ScalarFunction {
+                fun: BuiltinScalarFunction::Now,
+                ..
+            } => Expr::Literal(ScalarValue::TimestampNanosecond(Some(
+                date_time.timestamp_nanos(),
+            ))),
+            _ => exp.clone(),
+        };
+        utils::rewrite_expression(&exp, &expressions)
+    }
+
+    fn optimize_with_datetime(
+        &self,
+        plan: &LogicalPlan,
+        date_time: &DateTime<Utc>,
+    ) -> Result<LogicalPlan> {
+        match plan {
+            LogicalPlan::Projection { .. } => {
+                let exprs = plan
+                    .expressions()
+                    .iter()
+                    .map(|exp| self.rewrite_expr(exp, date_time).unwrap())
+                    .collect::<Vec<_>>();
+
+                // apply the optimization to all inputs of the plan
+                let inputs = plan.inputs();
+                let new_inputs = inputs
+                    .iter()
+                    .map(|plan| self.optimize_with_datetime(*plan, date_time))
+                    .collect::<Result<Vec<_>>>()?;
+
+                utils::from_plan(plan, &exprs, &new_inputs)
+            }
+            _ => {
+                let expr = plan.expressions();
+
+                // apply the optimization to all inputs of the plan
+                let inputs = plan.inputs();
+                let new_inputs = inputs
+                    .iter()
+                    .map(|plan| self.optimize_with_datetime(*plan, date_time))
+                    .collect::<Result<Vec<_>>>()?;
+
+                utils::from_plan(plan, &expr, &new_inputs)
+            }
+        }
+    }
+}
+
+impl OptimizerRule for TimestampEvaluation {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        props: &ExecutionProps,
+    ) -> Result<LogicalPlan> {
+        self.optimize_with_datetime(plan, 
&props.query_execution_start_time.unwrap())
+    }
+
+    fn name(&self) -> &str {
+        "timestamp_evaluation"
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::logical_plan::LogicalPlanBuilder;
+    use crate::test::*;
+
+    fn get_optimized_plan_formatted(plan: &LogicalPlan) -> String {
+        let rule = TimestampEvaluation::new();
+        let execution_props = ExecutionProps {
+            query_execution_start_time: Some(chrono::Utc::now()),
+        };
+
+        let optimized_plan = rule
+            .optimize(plan, &execution_props)
+            .expect("failed to optimize plan");
+        return format!("{:?}", optimized_plan);
+    }
+
+    #[test]
+    fn single_now() {
+        let table_scan = test_table_scan().unwrap();
+        let proj = vec![Expr::ScalarFunction {
+            args: vec![],
+            fun: BuiltinScalarFunction::Now,
+        }];
+        let plan = LogicalPlanBuilder::from(&table_scan)
+            .project(proj)
+            .unwrap()
+            .build()
+            .unwrap();
+
+        let expected = "Projection: TimestampNanosecond(";
+        assert!(get_optimized_plan_formatted(&plan).starts_with(expected));
+    }
+
+    #[test]
+    fn double_now() {
+        let table_scan = test_table_scan().unwrap();
+        let proj = vec![
+            Expr::ScalarFunction {
+                args: vec![],
+                fun: BuiltinScalarFunction::Now,
+            },
+            Expr::Alias(
+                Box::new(Expr::ScalarFunction {
+                    args: vec![],
+                    fun: BuiltinScalarFunction::Now,
+                }),
+                "t2".to_string(),
+            ),
+        ];
+        let plan = LogicalPlanBuilder::from(&table_scan)
+            .project(proj)
+            .unwrap()
+            .build()
+            .unwrap();
+
+        let actual = get_optimized_plan_formatted(&plan);
+        println!("output is {}", &actual);
+        let expected_start = "Projection: TimestampNanosecond(";
+        assert!(actual.starts_with(expected_start));
+
+        let expected_end = ") AS t2\
+             \n  TableScan: test projection=None";
+        assert!(actual.ends_with(expected_end));

Review comment:
       It would probably be good here to ensure the same timestamp value was 
produced in place `now()` was replaced.
   
   Since you can specify what timestamp value goes in perhaps you could hard 
code it in the test (so you could compare the plan with a known constant 
string). Perhaps something like:
   
   ```
           let start_time  = Utc.ymd(2018, 7, 1).and_hms(6, 0, 0); // 
2018-Jul-01 06:00
   
           let execution_props = ExecutionProps {
               query_execution_start_time: Some(start_time),
           };
   ```

##########
File path: datafusion/src/physical_plan/functions.rs
##########
@@ -3611,17 +3607,19 @@ mod tests {
         Ok(())
     }
 
-    #[test]
-    fn test_concat_error() -> Result<()> {

Review comment:
       I think it would be valuable to update the test case




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

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to