You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/09/05 13:32:45 UTC
[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #3222: Add optimizer rule for type coercion (binary operations only)
alamb commented on code in PR #3222:
URL: https://github.com/apache/arrow-datafusion/pull/3222#discussion_r962907948
##########
datafusion/physical-expr/src/planner.rs:
##########
@@ -47,7 +47,13 @@ pub fn create_physical_expr(
input_schema: &Schema,
execution_props: &ExecutionProps,
) -> Result<Arc<dyn PhysicalExpr>> {
- assert_eq!(input_schema.fields.len(), input_dfschema.fields().len());
+ if input_schema.fields.len() != input_dfschema.fields().len() {
Review Comment:
👍
##########
datafusion/physical-expr/src/planner.rs:
##########
@@ -47,7 +47,13 @@ pub fn create_physical_expr(
input_schema: &Schema,
execution_props: &ExecutionProps,
) -> Result<Arc<dyn PhysicalExpr>> {
- assert_eq!(input_schema.fields.len(), input_dfschema.fields().len());
+ if input_schema.fields.len() != input_dfschema.fields().len() {
+ return Err(DataFusionError::Internal(
+ "create_physical_expr passed Arrow schema and DataFusion \
+ schema with different number of fields"
+ .to_string(),
+ ));
Review Comment:
```suggestion
return Err(DataFusionError::Internal(
format!("create_physical_expr passed Arrow schema and DataFusion \
schema with different number of fields, {} vs {}",
input_schema.fields.len(), input_dfschema.fields().len()
),
));
```
##########
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:
I agree it is strange -- maybe it is worth a ticket to investigate further (or maybe @waitingkuo is already tracking it)
##########
datafusion/expr/src/expr.rs:
##########
@@ -1101,6 +1102,20 @@ mod test {
Ok(())
}
+ #[test]
Review Comment:
👍
##########
datafusion/core/tests/sql/joins.rs:
##########
@@ -1438,9 +1438,9 @@ async fn reduce_left_join_1() -> Result<()> {
"Explain [plan_type:Utf8, plan:Utf8]",
" Projection: #t1.t1_id, #t1.t1_name, #t1.t1_int, #t2.t2_id, #t2.t2_name, #t2.t2_int [t1_id:UInt32;N, t1_name:Utf8;N, t1_int:UInt32;N, t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
" Inner Join: #t1.t1_id = #t2.t2_id [t1_id:UInt32;N, t1_name:Utf8;N, t1_int:UInt32;N, t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
- " Filter: #t1.t1_id < Int64(100) [t1_id:UInt32;N, t1_name:Utf8;N, t1_int:UInt32;N]",
+ " Filter: CAST(#t1.t1_id AS Int64) < Int64(100) [t1_id:UInt32;N, t1_name:Utf8;N, t1_int:UInt32;N]",
Review Comment:
I think it is much clearer that the casts are now visible in the explain plan (as it is clear what is going on)
##########
datafusion/optimizer/src/type_coercion.rs:
##########
@@ -0,0 +1,170 @@
+// 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::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(_) => {
+ // we don't want to cast intervals because that breaks
+ // the logic in the physical planner
+ Ok(expr)
+ }
+ _ => {
+ let coerced_type = coerce_types(&left_type, op, &right_type)?;
+ let left = left.clone().cast_to(&coerced_type, &self.schema)?;
Review Comment:
I think it is a minor point and could be done in a follow on PR, but since this function gets an owned `expr` it might be possible to `match expr` rather than `match &expr` and save these clones
##########
datafusion/core/tests/sql/explain_analyze.rs:
##########
@@ -694,7 +694,7 @@ async fn test_physical_plan_display_indent() {
" RepartitionExec: partitioning=Hash([Column { name: \"c1\", index: 0 }], 9000)",
" AggregateExec: mode=Partial, gby=[c1@0 as c1], aggr=[MAX(aggregate_test_100.c12), MIN(aggregate_test_100.c12)]",
" CoalesceBatchesExec: target_batch_size=4096",
- " FilterExec: c12@1 < CAST(10 AS Float64)",
+ " FilterExec: c12@1 < 10",
Review Comment:
🎉 -- which I think is a good example of the value of this pass
##########
datafusion/core/tests/sql/timestamp.rs:
##########
@@ -1398,6 +1398,7 @@ async fn timestamp_sub_interval_days() -> Result<()> {
}
#[tokio::test]
+#[ignore] // https://github.com/apache/arrow-datafusion/issues/3327
Review Comment:
Should this test be ignored? Maybe this is a merge conflict -- I think @HaoYang670 has fixed this test in https://github.com/apache/arrow-datafusion/pull/3337 so it no longer needs to be ignored
##########
datafusion/core/src/execution/context.rs:
##########
@@ -1401,6 +1402,9 @@ impl SessionState {
}
rules.push(Arc::new(ReduceOuterJoin::new()));
rules.push(Arc::new(FilterPushDown::new()));
+ // we do type coercion after filter push down so that we don't push CAST filters to Parquet
Review Comment:
I have a partially written ticket (I will post later this week) related to supporting `CAST` in pruning logic (which is part of what is pushed to parquet). Perhaps this is also related
--
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: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org