You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by bo...@apache.org on 2021/11/03 12:22:20 UTC
[impala] branch master updated (cd64271 -> 9ed4b36)
This is an automated email from the ASF dual-hosted git repository.
boroknagyz pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git.
from cd64271 IMPALA-9873: Avoid materialization of columns for filtered out rows in Parquet table.
new 217d821 IMPALA-10836: Add 'SimplifyCastExprRule' rule to rewrite cast expr in some situations
new 9ed4b36 IMPALA-10777: Enable min/max filtering for Iceberg partitions
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
be/src/exec/hdfs-scanner.h | 7 ++
be/src/exec/parquet/hdfs-parquet-scanner.cc | 21 +++---
be/src/exec/parquet/hdfs-parquet-scanner.h | 6 +-
be/src/runtime/runtime-filter.h | 5 ++
common/thrift/PlanNodes.thrift | 4 ++
.../java/org/apache/impala/analysis/Analyzer.java | 2 +
.../org/apache/impala/catalog/FeIcebergTable.java | 13 ++++
.../java/org/apache/impala/catalog/FeTable.java | 6 ++
.../impala/planner/RuntimeFilterGenerator.java | 39 +++++++++--
.../impala/rewrite/SimplifyCastExprRule.java | 62 +++++++++++++++++
.../impala/analysis/ExprRewriteRulesTest.java | 80 ++++++++++++++++++++++
.../queries/PlannerTest/insert-sort-by.test | 4 +-
.../queries/QueryTest/min_max_filters.test | 10 +++
13 files changed, 235 insertions(+), 24 deletions(-)
create mode 100644 fe/src/main/java/org/apache/impala/rewrite/SimplifyCastExprRule.java
[impala] 02/02: IMPALA-10777: Enable min/max filtering for Iceberg
partitions
Posted by bo...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
boroknagyz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git
commit 9ed4b3689784670532e840c5cb0389bdd9d5c0e8
Author: Zoltan Borok-Nagy <bo...@cloudera.com>
AuthorDate: Tue Oct 5 14:35:59 2021 +0200
IMPALA-10777: Enable min/max filtering for Iceberg partitions
This patch enables min/max filters for Iceberg columns that
participate in table partitioning. The min/max filters are
evaluated at the Parquet row group level. This means that it
is still slower than dynamic partition pruning (which doesn't
even need to open the files), but much faster than no pruning at all.
Performance
I used the following query to measure perf on a scale 10 TPC-DS
dataset:
select i_item_id,sum(ss_ext_sales_price) total_sales
from
store_sales,
date_dim,
customer_address,
item
where i_item_id in (select
i_item_id
from item
where i_color in ('orchid','chiffon','lace'))
and ss_item_sk = i_item_sk
and ss_sold_date_sk = d_date_sk
and d_year = 2000
and d_moy = 1
and ss_addr_sk = ca_address_sk
and ca_gmt_offset = -8
The above query took the following times to execute:
Regular Parquet table: 1.16s
Iceberg table without min/max filters: 4.39s
Iceberg table with min/max filters: 1.77s
Testing:
* added e2e test
* planner test could not be added because Iceberg tables behave
differently during planner tests (due to some hacks that needs
refactoring)
Change-Id: I51b53188c6da7eeebfeae385e1de31ace0980cac
Reviewed-on: http://gerrit.cloudera.org:8080/17960
Reviewed-by: Qifan Chen <qc...@cloudera.com>
Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
be/src/exec/hdfs-scanner.h | 7 ++++
be/src/exec/parquet/hdfs-parquet-scanner.cc | 21 +++++-------
be/src/exec/parquet/hdfs-parquet-scanner.h | 6 ++--
be/src/runtime/runtime-filter.h | 5 +++
common/thrift/PlanNodes.thrift | 4 +++
.../org/apache/impala/catalog/FeIcebergTable.java | 13 ++++++++
.../java/org/apache/impala/catalog/FeTable.java | 6 ++++
.../impala/planner/RuntimeFilterGenerator.java | 39 ++++++++++++++++++----
.../queries/QueryTest/min_max_filters.test | 10 ++++++
9 files changed, 89 insertions(+), 22 deletions(-)
diff --git a/be/src/exec/hdfs-scanner.h b/be/src/exec/hdfs-scanner.h
index 6402bbf..6f80904 100644
--- a/be/src/exec/hdfs-scanner.h
+++ b/be/src/exec/hdfs-scanner.h
@@ -196,6 +196,13 @@ class HdfsScanner {
return -1;
}
+ /// Return the runtime filter by index 'filter_idx'.
+ const RuntimeFilter* GetFilter(int filter_idx) {
+ DCHECK_GE(filter_idx, 0);
+ DCHECK_LT(filter_idx, filter_ctxs_.size());
+ return filter_ctxs_[filter_idx]->filter;
+ }
+
/// Scanner subclasses must implement these static functions as well. Unfortunately,
/// c++ does not allow static virtual functions.
diff --git a/be/src/exec/parquet/hdfs-parquet-scanner.cc b/be/src/exec/parquet/hdfs-parquet-scanner.cc
index 4068aab..a47e1de 100644
--- a/be/src/exec/parquet/hdfs-parquet-scanner.cc
+++ b/be/src/exec/parquet/hdfs-parquet-scanner.cc
@@ -726,13 +726,12 @@ Status HdfsParquetScanner::EvaluateOverlapForRowGroup(
/// Find the index of the filter that is common in data structure
/// filter_ctxs_ and filter_stats_.
int idx = FindFilterIndex(filter_id);
- DCHECK(idx >= 0);
- if (IsBoundByPartitionColumn(idx)) {
- continue;
- }
+ const RuntimeFilter* filter = GetFilter(idx);
+ // We skip row group filtering if the column is not present in the data files.
+ if (!filter->IsColumnInDataFile(GetScanNodeId())) continue;
- MinMaxFilter* minmax_filter = FindMinMaxFilter(idx);
+ MinMaxFilter* minmax_filter = GetMinMaxFilter(filter);
VLOG(3) << "Try to filter out a rowgroup via overlap predicate filter: "
<< " fid=" << filter_id
@@ -1354,12 +1353,9 @@ void HdfsParquetScanner::GetMinMaxSlotsForOverlapPred(
*max_slot = min_max_tuple_->GetSlot(max_slot_desc->tuple_offset());
}
-MinMaxFilter* HdfsParquetScanner::FindMinMaxFilter(int filter_idx) {
- if (filter_idx >= 0 && filter_idx < filter_ctxs_.size()) {
- const RuntimeFilter* filter = filter_ctxs_[filter_idx]->filter;
- if (filter && filter->is_min_max_filter()) {
- return filter->get_min_max();
- }
+MinMaxFilter* HdfsParquetScanner::GetMinMaxFilter(const RuntimeFilter* filter) {
+ if (filter && filter->is_min_max_filter()) {
+ return filter->get_min_max();
}
return nullptr;
}
@@ -1461,7 +1457,8 @@ Status HdfsParquetScanner::FindSkipRangesForPagesWithMinMaxFilters(
int slot_idx = desc.slot_index;
int filter_idx = FindFilterIndex(filter_id);
- MinMaxFilter* minmax_filter = FindMinMaxFilter(filter_idx);
+ const RuntimeFilter* filter = GetFilter(filter_idx);
+ MinMaxFilter* minmax_filter = GetMinMaxFilter(filter);
if (!minmax_filter || !IsFilterWorthyForOverlapCheck(filter_idx)) {
continue;
}
diff --git a/be/src/exec/parquet/hdfs-parquet-scanner.h b/be/src/exec/parquet/hdfs-parquet-scanner.h
index bf243a4..25c2c02 100644
--- a/be/src/exec/parquet/hdfs-parquet-scanner.h
+++ b/be/src/exec/parquet/hdfs-parquet-scanner.h
@@ -644,9 +644,9 @@ class HdfsParquetScanner : public HdfsColumnarScanner {
/// Return the overlap predicate descs from the HDFS scan plan.
const vector<TOverlapPredicateDesc>& GetOverlapPredicateDescs();
- /// Find and return the min/max filter at filter_ctx_[filter_idx].
- /// Return nullptr if no min/max filter is found at that location.
- MinMaxFilter* FindMinMaxFilter(int filter_idx);
+ /// Return the min/max filter of 'filter'.
+ /// Return nullptr if no min/max filter is present.
+ MinMaxFilter* GetMinMaxFilter(const RuntimeFilter* filter);
/// Return true when the filter at filter_ctx_[filter_idx] is bound by a
/// partition column and false otherwise.
diff --git a/be/src/runtime/runtime-filter.h b/be/src/runtime/runtime-filter.h
index 45d869f..fa8eccf 100644
--- a/be/src/runtime/runtime-filter.h
+++ b/be/src/runtime/runtime-filter.h
@@ -122,6 +122,11 @@ class RuntimeFilter {
return filter_desc().targets[target_ndx].is_bound_by_partition_columns;
}
+ bool IsColumnInDataFile(int plan_id) const {
+ int target_ndx = filter_desc().planid_to_target_ndx.at(plan_id);
+ return filter_desc().targets[target_ndx].is_column_in_data_file;
+ }
+
/// Frequency with which to check for filter arrival in WaitForArrival()
static const int SLEEP_PERIOD_MS;
diff --git a/common/thrift/PlanNodes.thrift b/common/thrift/PlanNodes.thrift
index 46db62d..e137250 100644
--- a/common/thrift/PlanNodes.thrift
+++ b/common/thrift/PlanNodes.thrift
@@ -120,6 +120,10 @@ struct TRuntimeFilterTargetDesc {
// Indicates if the low and high value in column stats are present
10: optional bool is_min_max_value_present
+
+ // Indicates if the column is actually stored in the data files (unlike partition
+ // columns in regular Hive tables)
+ 11: optional bool is_column_in_data_file
}
enum TRuntimeFilterType {
diff --git a/fe/src/main/java/org/apache/impala/catalog/FeIcebergTable.java b/fe/src/main/java/org/apache/impala/catalog/FeIcebergTable.java
index c25664d..e362808 100644
--- a/fe/src/main/java/org/apache/impala/catalog/FeIcebergTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/FeIcebergTable.java
@@ -247,6 +247,19 @@ public interface FeIcebergTable extends FeFsTable {
return getFeFsTable().getHostIndex();
}
+ @Override /* FeTable */
+ default boolean isComputedPartitionColumn(Column col) {
+ Preconditions.checkState(col instanceof IcebergColumn);
+ IcebergColumn iceCol = (IcebergColumn)col;
+ IcebergPartitionSpec spec = getDefaultPartitionSpec();
+ if (spec == null || !spec.hasPartitionFields()) return false;
+
+ for (IcebergPartitionField partField : spec.getIcebergPartitionFields()) {
+ if (iceCol.getFieldId() == partField.getSourceId()) return true;
+ }
+ return false;
+ }
+
/**
* Current snapshot id of the table.
*/
diff --git a/fe/src/main/java/org/apache/impala/catalog/FeTable.java b/fe/src/main/java/org/apache/impala/catalog/FeTable.java
index 0d4f3a1..fe5f9f1 100644
--- a/fe/src/main/java/org/apache/impala/catalog/FeTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/FeTable.java
@@ -111,6 +111,12 @@ public interface FeTable {
boolean isClusteringColumn(Column c);
/**
+ * Return true when the column is used in a computed partition, e.g. in Iceberg
+ * partition transforms.
+ */
+ default boolean isComputedPartitionColumn(Column c) { return false; }
+
+ /**
* Case-insensitive lookup.
*
* @return null if the column with 'name' is not found.
diff --git a/fe/src/main/java/org/apache/impala/planner/RuntimeFilterGenerator.java b/fe/src/main/java/org/apache/impala/planner/RuntimeFilterGenerator.java
index 28cf07f..9ca74b8 100644
--- a/fe/src/main/java/org/apache/impala/planner/RuntimeFilterGenerator.java
+++ b/fe/src/main/java/org/apache/impala/planner/RuntimeFilterGenerator.java
@@ -46,6 +46,7 @@ import org.apache.impala.analysis.TupleId;
import org.apache.impala.analysis.TupleIsNullPredicate;
import org.apache.impala.catalog.FeTable;
import org.apache.impala.catalog.Column;
+import org.apache.impala.catalog.FeIcebergTable;
import org.apache.impala.catalog.KuduColumn;
import org.apache.impala.catalog.ScalarType;
import org.apache.impala.catalog.Type;
@@ -232,14 +233,17 @@ public final class RuntimeFilterGenerator {
// The low and high value of the column on which the filter is applied
public final TColumnValue lowValue;
public final TColumnValue highValue;
+ // Indicates if the data is actually stored in the data files
+ public final boolean isColumnInDataFile;
public RuntimeFilterTarget(ScanNode targetNode, Expr targetExpr,
- boolean isBoundByPartitionColumns, boolean isLocalTarget, TColumnValue lowValue,
- TColumnValue highValue) {
+ boolean isBoundByPartitionColumns, boolean isColumnInDataFile,
+ boolean isLocalTarget, TColumnValue lowValue, TColumnValue highValue) {
Preconditions.checkState(targetExpr.isBoundByTupleIds(targetNode.getTupleIds()));
node = targetNode;
expr = targetExpr;
this.isBoundByPartitionColumns = isBoundByPartitionColumns;
+ this.isColumnInDataFile = isColumnInDataFile;
this.isLocalTarget = isLocalTarget;
this.lowValue = lowValue;
this.highValue = highValue;
@@ -256,6 +260,9 @@ public final class RuntimeFilterGenerator {
tFilterTarget.setTarget_expr_slotids(tSlotIds);
tFilterTarget.setIs_bound_by_partition_columns(isBoundByPartitionColumns);
tFilterTarget.setIs_local_target(isLocalTarget);
+ if (node instanceof HdfsScanNode) {
+ tFilterTarget.setIs_column_in_data_file(isColumnInDataFile);
+ }
if (node instanceof KuduScanNode) {
// assignRuntimeFilters() only assigns KuduScanNode targets if the target expr
// is a slot ref, possibly with an implicit cast, pointing to a column.
@@ -290,6 +297,7 @@ public final class RuntimeFilterGenerator {
return output.append("Target Id: " + node.getId() + " ")
.append("Target expr: " + expr.debugString() + " ")
.append("Partition columns: " + isBoundByPartitionColumns)
+ .append("Is column stored in data files: " + isColumnInDataFile)
.append("Is local: " + isLocalTarget)
.append("lowValue: " + (lowValue != null ? lowValue.toString() : -1))
.append("highValue: " + (highValue != null ? highValue.toString() : -1))
@@ -924,6 +932,8 @@ public final class RuntimeFilterGenerator {
boolean isBoundByPartitionColumns = isBoundByPartitionColumns(analyzer, targetExpr,
scanNode);
if (disableRowRuntimeFiltering && !isBoundByPartitionColumns) continue;
+ boolean isColumnInDataFile = isColumnInDataFile(scanNode.getTupleDesc().getTable(),
+ isBoundByPartitionColumns);
boolean isLocalTarget = isLocalTarget(filter, scanNode);
if (runtimeFilterMode == TRuntimeFilterMode.LOCAL && !isLocalTarget) continue;
@@ -1008,7 +1018,8 @@ public final class RuntimeFilterGenerator {
}
RuntimeFilter.RuntimeFilterTarget target =
new RuntimeFilter.RuntimeFilterTarget(scanNode, targetExpr,
- isBoundByPartitionColumns, isLocalTarget, lowValue, highValue);
+ isBoundByPartitionColumns, isColumnInDataFile, isLocalTarget,
+ lowValue, highValue);
filter.addTarget(target);
}
@@ -1033,13 +1044,13 @@ public final class RuntimeFilterGenerator {
Preconditions.checkState(targetExpr.isBoundByTupleIds(targetNode.getTupleIds()));
TupleDescriptor baseTblDesc = targetNode.getTupleDesc();
FeTable tbl = baseTblDesc.getTable();
- if (tbl.getNumClusteringCols() == 0) return false;
+ if (tbl.getNumClusteringCols() == 0 && !(tbl instanceof FeIcebergTable)) return false;
List<SlotId> sids = new ArrayList<>();
targetExpr.getIds(null, sids);
for (SlotId sid : sids) {
- SlotDescriptor slotDesc = analyzer.getSlotDesc(sid);
- if (slotDesc.getColumn() == null
- || slotDesc.getColumn().getPosition() >= tbl.getNumClusteringCols()) {
+ Column col = analyzer.getSlotDesc(sid).getColumn();
+ if (col == null) return false;
+ if (!tbl.isClusteringColumn(col) && !tbl.isComputedPartitionColumn(col)) {
return false;
}
}
@@ -1047,6 +1058,20 @@ public final class RuntimeFilterGenerator {
}
/**
+ * Return true if the column is actually stored in the data file. E.g. partition
+ * columns are not stored in most cases.
+ */
+ private static boolean isColumnInDataFile(FeTable tbl,
+ boolean isBoundByPartitionColumns) {
+ // Non-partition values are always sotred in the data files.
+ if (!isBoundByPartitionColumns) return true;
+ // Iceberg uses hidden partitioning which means all columns are stored in the data
+ // files.
+ if (tbl instanceof FeIcebergTable) return true;
+ return false;
+ }
+
+ /**
* Computes the target expr for a specified runtime filter 'filter' to be applied at
* the scan node with target tuple descriptor 'targetTid'.
*/
diff --git a/testdata/workloads/functional-query/queries/QueryTest/min_max_filters.test b/testdata/workloads/functional-query/queries/QueryTest/min_max_filters.test
index e1248bb..f14e02a 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/min_max_filters.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/min_max_filters.test
@@ -425,3 +425,13 @@ on a.date_col = b.date_col and b.date_col = c.date_col;
aggregation(SUM, ProbeRows): 48
row_regex: .*1 of 1 Runtime Filter Published.*
====
+---- QUERY
+SET RUNTIME_FILTER_WAIT_TIME_MS=$RUNTIME_FILTER_WAIT_TIME_MS;
+select * from functional_parquet.iceberg_partitioned i1,
+ functional_parquet.iceberg_partitioned i2
+where i1.action = i2.action and
+ i1.id = i2.id and
+ i2.event_time = '2020-01-01 10:00:00';
+---- RUNTIME_PROFILE
+row_regex:.* RF00.\[min_max\] -> i1\.action.*
+====
[impala] 01/02: IMPALA-10836: Add 'SimplifyCastExprRule' rule to
rewrite cast expr in some situations
Posted by bo...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
boroknagyz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git
commit 217d821e94cc8571c7f21e8a4d55a3d3f900c116
Author: skyyws <sk...@163.com>
AuthorDate: Mon Sep 6 20:32:12 2021 +0800
IMPALA-10836: Add 'SimplifyCastExprRule' rule to rewrite cast expr in some situations
This patch adds a new expr rewrite rule to simplify some cast expr when
cast target data type is the same as inner expr data type. We will
remove unnecessary cast expr if any rules are matched. This kind of
rewrite will improve query performance when casting a non-partition
column, especially when scanning lots of data. Besides, cast expr in
where clause can not pushdown to Kudu server, if we can remove
unnecessary cast expr, Impala will pushdown this predicate to Kudu
server, and this will save lots of time and IO/memmory.
Testing:
- Added unit test cases in `ExprRewriteRulesTest`
Change-Id: Id8fac7100060d4e139a8b24d4795c6f279c55954
Reviewed-on: http://gerrit.cloudera.org:8080/17933
Tested-by: Impala Public Jenkins <im...@cloudera.com>
Reviewed-by: Zoltan Borok-Nagy <bo...@cloudera.com>
---
.../java/org/apache/impala/analysis/Analyzer.java | 2 +
.../impala/rewrite/SimplifyCastExprRule.java | 62 +++++++++++++++++
.../impala/analysis/ExprRewriteRulesTest.java | 80 ++++++++++++++++++++++
.../queries/PlannerTest/insert-sort-by.test | 4 +-
4 files changed, 146 insertions(+), 2 deletions(-)
diff --git a/fe/src/main/java/org/apache/impala/analysis/Analyzer.java b/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
index 9734c3a..c3d48dc 100644
--- a/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
+++ b/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
@@ -68,6 +68,7 @@ import org.apache.impala.compat.MetastoreShim;
import org.apache.impala.planner.JoinNode;
import org.apache.impala.planner.PlanNode;
import org.apache.impala.rewrite.BetweenToCompoundRule;
+import org.apache.impala.rewrite.SimplifyCastExprRule;
import org.apache.impala.rewrite.ConvertToCNFRule;
import org.apache.impala.rewrite.EqualityDisjunctsToInRule;
import org.apache.impala.rewrite.ExprRewriteRule;
@@ -535,6 +536,7 @@ public class Analyzer {
rules.add(SimplifyCastStringToTimestamp.INSTANCE);
rules.add(CountDistinctToNdvRule.INSTANCE);
rules.add(DefaultNdvScaleRule.INSTANCE);
+ rules.add(SimplifyCastExprRule.INSTANCE);
}
exprRewriter_ = new ExprRewriter(rules);
}
diff --git a/fe/src/main/java/org/apache/impala/rewrite/SimplifyCastExprRule.java b/fe/src/main/java/org/apache/impala/rewrite/SimplifyCastExprRule.java
new file mode 100644
index 0000000..4272e7b
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/rewrite/SimplifyCastExprRule.java
@@ -0,0 +1,62 @@
+// 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.
+
+package org.apache.impala.rewrite;
+
+import com.google.common.base.Preconditions;
+import org.apache.impala.analysis.Analyzer;
+import org.apache.impala.analysis.CastExpr;
+import org.apache.impala.analysis.Expr;
+import org.apache.impala.analysis.NullLiteral;
+
+/**
+ * This rewrite rule simplifies cast expr when cast target data type is the same as inner
+ * expr data type.
+ * Examples:
+ * CAST(str_col AS STRING) ==> str_col
+ * SUM(CAST(int_col AS INT)) ==> SUM(int_col)
+ * CAST(int_col+int_col AS INT) ==> int_col+int_col
+ * CAST(CAST(col as BIGINT) as BIGINT) ==> CAST(col as BIGINT)
+ *
+ * This rule is also valid for complex type.
+ * Examples:
+ * CAST(int_array.item as INT) ==> int_array.item
+ * CAST(string_map.value as STRING) ==> string_map.value
+ * CAST(CAST(array.item as INT) AS INT) ==> CAST(array.item as INT)
+ * CAST(CAST(map.value as STRING) AS STRING) ==> CAST(map.value as STRING)
+ *
+ * Pay attention:
+ * For varchar type, we remove cast expr only when lengths are the same.
+ * For decimal type, we remove cast expr only when precisions and scales are the same.
+ */
+public class SimplifyCastExprRule implements ExprRewriteRule {
+ public static ExprRewriteRule INSTANCE = new SimplifyCastExprRule();
+
+ @Override
+ public Expr apply(Expr expr, Analyzer analyzer) {
+ if (!(expr instanceof CastExpr)) return expr;
+
+ Preconditions.checkState(expr.getChildren().size() == 1);
+ CastExpr castExpr = (CastExpr) expr;
+ Expr child = castExpr.getChild(0);
+ //In analysis phase, CaseExpr will convert child to target type, we cannot rewrite in
+ //this situation, such as cast(cast(NULL as string) as timestamp FORMAT 'YYYY-MM-DD').
+ //If we replace inner 'cast(NULL as string)' as 'NULL', query will throw exception.
+ if (child instanceof NullLiteral) return castExpr;
+ return castExpr.getType().matchesType(child.getType())? child : castExpr;
+ }
+}
diff --git a/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java b/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
index d91a53c..e799a35 100644
--- a/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
@@ -32,6 +32,7 @@ import org.apache.impala.common.ImpalaException;
import org.apache.impala.common.QueryFixture;
import org.apache.impala.common.SqlCastException;
import org.apache.impala.rewrite.BetweenToCompoundRule;
+import org.apache.impala.rewrite.SimplifyCastExprRule;
import org.apache.impala.rewrite.ConvertToCNFRule;
import org.apache.impala.rewrite.EqualityDisjunctsToInRule;
import org.apache.impala.rewrite.ExprRewriteRule;
@@ -915,4 +916,83 @@ public class ExprRewriteRulesTest extends FrontendTestBase {
RewritesOk(
"NULL || bool_col", extractCompoundVerticalBarExprRule, "NULL OR bool_col");
}
+
+ @Test
+ public void testSimplifyCastExprRule() throws ImpalaException {
+ ExprRewriteRule rule = SimplifyCastExprRule.INSTANCE;
+
+ //Inner expr is a column
+ RewritesOk("functional.alltypes", "CAST(int_col AS INT)", rule, "int_col");
+ RewritesOk("functional.alltypes", "CAST(date_string_col AS STRING)", rule,
+ "date_string_col");
+ RewritesOk("functional.alltypes", "CAST(timestamp_col AS TIMESTAMP)", rule,
+ "timestamp_col");
+ //Multi-layer cast
+ RewritesOk("functional.alltypes", "CAST(CAST(int_col AS INT) AS INT)", rule,
+ "int_col");
+ //No rewrite
+ RewritesOk("functional.alltypes", "CAST(int_col AS BIGINT)", rule, null);
+
+ //Inner expr is an arithmetic expr
+ RewritesOk("functional.alltypes", "CAST(bigint_col+bigint_col AS BIGINT)", rule,
+ "bigint_col + bigint_col");
+ //Multi-layer cast
+ RewritesOk("functional.alltypes", "SUM(CAST(bigint_col+bigint_col AS BIGINT))", rule,
+ "sum(bigint_col + bigint_col)");
+ //No rewrite
+ RewritesOk("functional.alltypes", "CAST(bigint_col+bigint_col AS DOUBLE)", rule,
+ null);
+
+ //Inner expr is also a cast expr
+ RewritesOk("functional.alltypes", "CAST(CAST(int_col AS BIGINT) AS BIGINT)", rule,
+ "CAST(int_col AS BIGINT)");
+ //Multi-layer cast
+ RewritesOk("functional.alltypes",
+ "CAST(CAST(CAST(int_col AS BIGINT) AS BIGINT) AS BIGINT)", rule,
+ "CAST(int_col AS BIGINT)");
+ //No rewrite
+ RewritesOk("functional.alltypes", "CAST(CAST(int_col AS BIGINT) AS INT)", rule, null);
+
+ //Decimal type, d3 type is DECIMAL(20,10)
+ RewritesOk("functional.decimal_tbl", "CAST(d3 AS DECIMAL(20,10))", rule, "d3");
+ RewritesOk("functional.decimal_tbl",
+ "CAST(CAST(d3 AS DECIMAL(10,5)) AS DECIMAL(10,5))", rule,
+ "CAST(d3 AS DECIMAL(10,5))");
+ //No rewrite
+ RewritesOk("functional.decimal_tbl", "CAST(d3 AS DECIMAL(10,5))", rule, null);
+ RewritesOk("functional.decimal_tbl", "CAST(d3 AS DECIMAL(25,15))", rule, null);
+ RewritesOk("functional.decimal_tbl",
+ "CAST(CAST(d3 AS DECIMAL(10,5)) AS DECIMAL(15,5))", rule, null);
+
+ //Varchar type, vc type is VARCHAR(32)
+ RewritesOk("functional.chars_formats", "CAST(vc AS VARCHAR(32))", rule, "vc");
+ RewritesOk("functional.chars_formats",
+ "CAST(CAST(vc AS VARCHAR(16)) AS VARCHAR(16))", rule, "CAST(vc AS VARCHAR(16))");
+ //No rewrite
+ RewritesOk("functional.chars_formats", "CAST(vc AS VARCHAR(16))", rule, null);
+ RewritesOk("functional.chars_formats", "CAST(vc AS VARCHAR(48))", rule, null);
+ RewritesOk("functional.chars_formats",
+ "CAST(CAST(vc AS VARCHAR(48)) AS VARCHAR(16))", rule, null);
+
+ //Array type
+ RewritesOk("functional.allcomplextypes.int_array_col",
+ "CAST(int_array_col.item AS INT)", rule, "int_array_col.item");
+ RewritesOk("functional.allcomplextypes.int_array_col",
+ "CAST(CAST(int_array_col.item AS BIGINT) AS BIGINT)", rule,
+ "CAST(int_array_col.item AS BIGINT)");
+
+ //Map type
+ RewritesOk("functional.allcomplextypes.int_map_col",
+ "CAST(int_map_col.key AS STRING)", rule, "int_map_col.`key`");
+ RewritesOk("functional.allcomplextypes.int_map_col",
+ "CAST(CAST(int_map_col.value AS STRING) AS STRING)", rule,
+ "CAST(int_map_col.value AS STRING)");
+
+ //Struct type
+ RewritesOk("functional.allcomplextypes", "CAST(int_struct_col.f1 AS INT)", rule,
+ "int_struct_col.f1");
+ RewritesOk("functional.allcomplextypes",
+ "CAST(CAST(int_struct_col.f1 AS BIGINT) AS BIGINT)", rule,
+ "CAST(int_struct_col.f1 AS BIGINT)");
+ }
}
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/insert-sort-by.test b/testdata/workloads/functional-planner/queries/PlannerTest/insert-sort-by.test
index 525ce97..1e20c4b 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/insert-sort-by.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/insert-sort-by.test
@@ -387,7 +387,7 @@ WRITE TO HDFS [test_sort_by.t_nopart, OVERWRITE=false]
| partitions=1
|
02:SORT
-| order by: CAST(id AS INT) ASC NULLS LAST
+| order by: id ASC NULLS LAST
| row-size=1B cardinality=2
|
01:AGGREGATE [FINALIZE]
@@ -402,7 +402,7 @@ WRITE TO HDFS [test_sort_by.t_nopart, OVERWRITE=false]
| partitions=1
|
02:SORT
-| order by: CAST(id AS INT) ASC NULLS LAST
+| order by: id ASC NULLS LAST
| row-size=1B cardinality=2
|
01:AGGREGATE [FINALIZE]