andygrove commented on code in PR #3222:
URL: https://github.com/apache/arrow-datafusion/pull/3222#discussion_r957633348


##########
datafusion/optimizer/src/type_coercion.rs:
##########
@@ -0,0 +1,178 @@
+// 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 for type validation and coercion
+
+use crate::{OptimizerConfig, OptimizerRule};
+use arrow::datatypes::DataType;
+use datafusion_common::{DFSchema, DFSchemaRef, Result};
+use datafusion_expr::binary_rule::coerce_types;
+use datafusion_expr::expr_rewriter::{ExprRewritable, ExprRewriter, 
RewriteRecursion};
+use datafusion_expr::logical_plan::builder::build_join_schema;
+use datafusion_expr::logical_plan::JoinType;
+use datafusion_expr::utils::from_plan;
+use datafusion_expr::{cast_if_needed, ExprSchemable};
+use datafusion_expr::{Expr, LogicalPlan};
+
+#[derive(Default)]
+pub struct TypeCoercion {}
+
+impl TypeCoercion {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for TypeCoercion {
+    fn name(&self) -> &str {
+        "TypeCoercion"
+    }
+
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &mut OptimizerConfig,
+    ) -> Result<LogicalPlan> {
+        // optimize child plans first
+        let new_inputs = plan
+            .inputs()
+            .iter()
+            .map(|p| self.optimize(p, optimizer_config))
+            .collect::<Result<Vec<_>>>()?;
+
+        let schema = match new_inputs.len() {
+            1 => new_inputs[0].schema().clone(),
+            2 => DFSchemaRef::new(build_join_schema(
+                new_inputs[0].schema(),
+                new_inputs[1].schema(),
+                &JoinType::Inner,
+            )?),
+            _ => DFSchemaRef::new(DFSchema::empty()),
+        };
+
+        let mut expr_rewrite = TypeCoercionRewriter { schema };
+
+        let new_expr = plan
+            .expressions()
+            .into_iter()
+            .map(|expr| expr.rewrite(&mut expr_rewrite))
+            .collect::<Result<Vec<_>>>()?;
+
+        from_plan(plan, &new_expr, &new_inputs)
+    }
+}
+
+struct TypeCoercionRewriter {
+    schema: DFSchemaRef,
+}
+
+impl ExprRewriter for TypeCoercionRewriter {
+    fn pre_visit(&mut self, _expr: &Expr) -> Result<RewriteRecursion> {
+        Ok(RewriteRecursion::Continue)
+    }
+
+    fn mutate(&mut self, expr: Expr) -> Result<Expr> {
+        match &expr {
+            Expr::BinaryExpr { left, op, right } => {
+                let left_type = left.get_type(&self.schema)?;
+                let right_type = right.get_type(&self.schema)?;
+                match right_type {
+                    DataType::Interval(_) => {

Review Comment:
   Removing this causes one test failue:
   
   ```
   ---- sql::timestamp::timestamp_array_add_interval stdout ----
   thread 'sql::timestamp::timestamp_array_add_interval' panicked at 'called 
`Result::unwrap()` on an `Err` value: "Internal(\"Unsupported CAST from 
Interval(DayTime) to Timestamp(Nanosecond, None)\") at Creating physical plan 
for 'SELECT ts, ts - INTERVAL '8' MILLISECONDS FROM table_a': Projection: 
#table_a.ts, #table_a.ts - CAST(IntervalDayTime(\"8\") AS Timestamp(Nanosecond, 
None))\n  TableScan: table_a projection=[ts]"', 
datafusion/core/tests/sql/mod.rs:773:10
   ```
   
   ~Arrow does not support `CAST from Interval(DayTime) to 
Timestamp(Nanosecond, None)`. I think this could be added so I filed 
https://github.com/apache/arrow-rs/issues/2606. Once this is implemented, we 
can remove this code.~



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

Reply via email to