kasakrisz commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1243658746


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.hadoop.hive.ql.optimizer.calcite.rules;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelOptUtil;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
+import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Rule to transpose Filter and TableFunctionScan RelNodes
+ */
+public class HiveFilterTableFunctionTransposeRule extends RelOptRule {
+
+  public static final HiveFilterTableFunctionTransposeRule INSTANCE =
+          new 
HiveFilterTableFunctionTransposeRule(HiveRelFactories.HIVE_BUILDER);
+
+  public HiveFilterTableFunctionTransposeRule(RelBuilderFactory 
relBuilderFactory) {
+    super(operand(HiveFilter.class, operand(HiveTableFunctionScan.class, 
any())),

Review Comment:
   To follow the logic I proposed with the Lateral view specific subclass can 
we use it here instead of `HiveTableFunctionScan`? And checks like 
`tableFunctionScanRel.isLateralView()` is no longer required.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveTableFunctionScan.java:
##########
@@ -32,6 +32,14 @@
 
 public class HiveTableFunctionScan extends TableFunctionScan implements 
HiveRelNode {
 
+  // True if this RelNode was created through a lateral view. This is needed 
because
+  // when the return type is different based on whether the node was created 
as a lateral
+  // view. For lateral views, the fields from the base source table are 
accessible along
+  // with the fields coming from the udtf that expand the output rows into 
multiple rows.
+  // When this RelNode is created without a lateral view, only the udtf output 
is present
+  // in the return type.
+  private final boolean isLateralView;

Review Comment:
   How about creating a subclass from `HiveTableFunctionScan` and move the 
lateral view specific code into it instead of introducing this boolean field?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.hadoop.hive.ql.optimizer.calcite.rules;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelOptUtil;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
+import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Rule to transpose Filter and TableFunctionScan RelNodes
+ */
+public class HiveFilterTableFunctionTransposeRule extends RelOptRule {
+
+  public static final HiveFilterTableFunctionTransposeRule INSTANCE =
+          new 
HiveFilterTableFunctionTransposeRule(HiveRelFactories.HIVE_BUILDER);
+
+  public HiveFilterTableFunctionTransposeRule(RelBuilderFactory 
relBuilderFactory) {
+    super(operand(HiveFilter.class, operand(HiveTableFunctionScan.class, 
any())),
+        relBuilderFactory, null);
+  }
+
+  @Override
+  public boolean matches(RelOptRuleCall call) {
+    final Filter filterRel = call.rel(0);
+    final HiveTableFunctionScan tableFunctionScanRel = call.rel(1);
+
+    RexNode condition = filterRel.getCondition();
+    if (!HiveCalciteUtil.isDeterministic(condition)) {
+      return false;
+    }
+
+    // If the HiveTableFunctionScan is a special inline(array(...))
+    // udtf, the table is generated from this node. The underlying
+    // RelNode will be a dummy table so no filter condition should
+    // pass through the HiveTableFunctionScan.
+    if (isInlineArray(tableFunctionScanRel)) {
+      return false;
+    }
+
+    // If the HiveTableFunctionScan is not a lateral view, the return type
+    // for the RelNode only contains the output of the udtf so no filter
+    // condition can be passed through.
+    if (!tableFunctionScanRel.isLateralView()) {
+      return false;
+    }
+
+    RelNode inputRel = tableFunctionScanRel.getInput(0);
+
+    // The TableFunctionScan is always created such that all the input RelNode
+    // fields are present in its RelNode.  If a Filter has an InputRef that is
+    // greater then the number of the RelNode below the TableFunctionScan, that
+    // means it was a field created by the TableFunctionScan and thus the 
Filter
+    // cannot be pushed through.
+    //
+    // We check for each individual conjunction (breaking it up by top level 
'and'
+    // conditions).
+    int numFieldsInInput = inputRel.getRowType().getFieldCount();
+
+    for (RexNode ce : RelOptUtil.conjunctions(filterRel.getCondition())) {
+      Set<Integer> inputRefs = HiveCalciteUtil.getInputRefs(ce);
+
+      boolean canBePushed = true;
+      for (Integer inputRef : inputRefs) {
+        if (inputRef >= numFieldsInInput) {
+          canBePushed = false;
+          break;
+        }
+      }
+
+      if (canBePushed) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public void onMatch(RelOptRuleCall call) {
+    final Filter filter = call.rel(0);
+    final HiveTableFunctionScan tfs = call.rel(1);
+    final RelNode inputRel = tfs.getInput(0);
+    final int numFieldsInInput = inputRel.getRowType().getFieldCount();
+
+    final List<RexNode> newPartKeyFilterConditions = new ArrayList<>();
+    final List<RexNode> unpushedFilterConditions = new ArrayList<>();
+
+    // Check for each individual 'and' condition so that we can push partial
+    // expressions through.
+    for (RexNode ce : RelOptUtil.conjunctions(filter.getCondition())) {
+      Set<Integer> inputRefs = HiveCalciteUtil.getInputRefs(ce);
+      boolean canBePushed = true;
+      // We can only push if all the InputRef pointers are referencing the
+      // input RelNode to the TableFunctionScan
+      for (Integer inputRef : inputRefs) {
+        if (inputRef >= numFieldsInInput) {
+          canBePushed = false;
+          break;
+        }
+      }
+      if (canBePushed) {
+        newPartKeyFilterConditions.add(ce);
+      } else {
+        unpushedFilterConditions.add(ce);
+      }
+    }
+
+    // The "matches" check should guarantee there's something to push.
+    Preconditions.checkState(!newPartKeyFilterConditions.isEmpty());
+    final RexNode filterCondToPushBelowProj = RexUtil.composeConjunction(
+        filter.getCluster().getRexBuilder(), newPartKeyFilterConditions, true);
+
+    // Create the new filter with the pushed through conditions
+    final RelNode newFilter =
+        filter.copy(filter.getTraitSet(), tfs.getInput(0), 
filterCondToPushBelowProj);
+
+    // If there are conditions that cannot be pushed through, generate the 
RexNode
+    final RexNode unpushedFilCondAboveProj = unpushedFilterConditions.isEmpty()
+        ? null
+        : RexUtil.composeConjunction(filter.getCluster().getRexBuilder(),
+            unpushedFilterConditions, true);
+
+    // Generate the new TableFunctionScanNode with the Filter InputRel
+    final RelNode tableFunctionScanNode = tfs.copy(tfs.getTraitSet(), 
ImmutableList.of(newFilter),
+        tfs.getCall(), tfs.getElementType(), tfs.getRowType(), 
tfs.getColumnMappings());
+
+    // If there are expressions that couldn't be pushed through, generate the 
filter above the
+    // TableFunctionScan with these conditions.
+    final RelNode topLevelNode = unpushedFilCondAboveProj == null
+        ? tableFunctionScanNode
+        : filter.copy(filter.getTraitSet(), tableFunctionScanNode, 
unpushedFilCondAboveProj);

Review Comment:
   AFAIK `RelBuildel` is used for creating new RelNodes.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.hadoop.hive.ql.optimizer.calcite.rules;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelOptUtil;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
+import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Rule to transpose Filter and TableFunctionScan RelNodes
+ */
+public class HiveFilterTableFunctionTransposeRule extends RelOptRule {
+
+  public static final HiveFilterTableFunctionTransposeRule INSTANCE =
+          new 
HiveFilterTableFunctionTransposeRule(HiveRelFactories.HIVE_BUILDER);
+
+  public HiveFilterTableFunctionTransposeRule(RelBuilderFactory 
relBuilderFactory) {
+    super(operand(HiveFilter.class, operand(HiveTableFunctionScan.class, 
any())),
+        relBuilderFactory, null);
+  }
+
+  @Override
+  public boolean matches(RelOptRuleCall call) {
+    final Filter filterRel = call.rel(0);
+    final HiveTableFunctionScan tableFunctionScanRel = call.rel(1);
+
+    RexNode condition = filterRel.getCondition();
+    if (!HiveCalciteUtil.isDeterministic(condition)) {
+      return false;
+    }
+
+    // If the HiveTableFunctionScan is a special inline(array(...))
+    // udtf, the table is generated from this node. The underlying
+    // RelNode will be a dummy table so no filter condition should
+    // pass through the HiveTableFunctionScan.
+    if (isInlineArray(tableFunctionScanRel)) {
+      return false;
+    }
+
+    // If the HiveTableFunctionScan is not a lateral view, the return type
+    // for the RelNode only contains the output of the udtf so no filter
+    // condition can be passed through.
+    if (!tableFunctionScanRel.isLateralView()) {
+      return false;
+    }
+
+    RelNode inputRel = tableFunctionScanRel.getInput(0);
+
+    // The TableFunctionScan is always created such that all the input RelNode
+    // fields are present in its RelNode.  If a Filter has an InputRef that is
+    // greater then the number of the RelNode below the TableFunctionScan, that
+    // means it was a field created by the TableFunctionScan and thus the 
Filter
+    // cannot be pushed through.
+    //
+    // We check for each individual conjunction (breaking it up by top level 
'and'
+    // conditions).
+    int numFieldsInInput = inputRel.getRowType().getFieldCount();
+
+    for (RexNode ce : RelOptUtil.conjunctions(filterRel.getCondition())) {
+      Set<Integer> inputRefs = HiveCalciteUtil.getInputRefs(ce);
+
+      boolean canBePushed = true;
+      for (Integer inputRef : inputRefs) {
+        if (inputRef >= numFieldsInInput) {
+          canBePushed = false;
+          break;
+        }
+      }
+
+      if (canBePushed) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public void onMatch(RelOptRuleCall call) {
+    final Filter filter = call.rel(0);
+    final HiveTableFunctionScan tfs = call.rel(1);
+    final RelNode inputRel = tfs.getInput(0);
+    final int numFieldsInInput = inputRel.getRowType().getFieldCount();
+
+    final List<RexNode> newPartKeyFilterConditions = new ArrayList<>();
+    final List<RexNode> unpushedFilterConditions = new ArrayList<>();
+
+    // Check for each individual 'and' condition so that we can push partial
+    // expressions through.
+    for (RexNode ce : RelOptUtil.conjunctions(filter.getCondition())) {
+      Set<Integer> inputRefs = HiveCalciteUtil.getInputRefs(ce);
+      boolean canBePushed = true;
+      // We can only push if all the InputRef pointers are referencing the
+      // input RelNode to the TableFunctionScan
+      for (Integer inputRef : inputRefs) {
+        if (inputRef >= numFieldsInInput) {
+          canBePushed = false;
+          break;
+        }
+      }

Review Comment:
   Could you please extract this to a method? I think this logic is also used 
in the `matches(RelOptRuleCall call)` method.



##########
ql/src/test/results/clientpositive/llap/lateral_view_onview2.q.out:
##########
@@ -52,6 +52,8 @@ STAGE PLANS:
       Processor Tree:
         TableScan
           alias: lv_table_n1
+          properties:
+            insideView TRUE

Review Comment:
   Why is this new property appeared here?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveTableFunctionScan.java:
##########
@@ -49,22 +57,43 @@ public class HiveTableFunctionScan extends 
TableFunctionScan implements HiveRelN
    *          columnMappings - Column mappings associated with this function
    */
   private HiveTableFunctionScan(RelOptCluster cluster, RelTraitSet traitSet, 
List<RelNode> inputs,
-      RexNode rexCall, Type elementType, RelDataType rowType, 
Set<RelColumnMapping> columnMappings) {
+      RexNode rexCall, Type elementType, RelDataType rowType, 
Set<RelColumnMapping> columnMappings,
+      boolean isLateralView) {
     super(cluster, traitSet, inputs, rexCall, elementType, rowType, 
columnMappings);
+    this.isLateralView = isLateralView;
+  }
+
+  public static HiveTableFunctionScan create(RelOptCluster cluster, 
RelTraitSet traitSet,
+      List<RelNode> inputs, RexNode rexCall, Type elementType, RelDataType 
rowType,
+      Set<RelColumnMapping> columnMappings, boolean isLateralView) throws 
CalciteSemanticException {
+    return new HiveTableFunctionScan(cluster, traitSet,
+        inputs, rexCall, elementType, rowType, columnMappings, isLateralView);
   }
 
   public static HiveTableFunctionScan create(RelOptCluster cluster, 
RelTraitSet traitSet,
       List<RelNode> inputs, RexNode rexCall, Type elementType, RelDataType 
rowType,
       Set<RelColumnMapping> columnMappings) throws CalciteSemanticException {
     return new HiveTableFunctionScan(cluster, traitSet,
-        inputs, rexCall, elementType, rowType, columnMappings);
+        inputs, rexCall, elementType, rowType, columnMappings, false);
   }
 
   @Override
   public TableFunctionScan copy(RelTraitSet traitSet, List<RelNode> inputs, 
RexNode rexCall,
       Type elementType, RelDataType rowType, Set<RelColumnMapping> 
columnMappings) {
     return new HiveTableFunctionScan(getCluster(), traitSet, inputs, rexCall,
-        elementType, rowType, columnMappings);
+        elementType, rowType, columnMappings, isLateralView);
+  }
+
+  // return the field in the return type where the udtf field starts. If it is 
not
+  // a lateral view, the first field in the return type is the udtf return 
field.
+  // Otherwise, we can subtract from the end the amount of udtf fields and the 
rest
+  // are from the input ref.
+  public int getStartUdtfField() {
+    return isLateralView()
+        ? getRowType().getFieldCount() - getCall().getType().getFieldCount() : 
0;

Review Comment:
   This can return `0`. Override this method in the subclass and move the 
lateral view specific code there.



##########
ql/src/test/queries/clientpositive/cbo_rp_windowing_2.q:
##########
@@ -234,11 +234,13 @@ set hive.cbo.returnpath.hiveop=true ;
 select * from mfgr_brand_price_view_n1;        
         
 -- 24. testLateralViews
+set hive.cbo.returnpath.hiveop=false;

Review Comment:
   Maybe lv in cbo return path can be implemented in a follow-up.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +586,64 @@ private QueryBlockInfo convertSource(RelNode r) throws 
CalciteSemanticException
         ast = ASTBuilder.subQuery(left, sqAlias);
         s = new Schema((Union) r, sqAlias);
       }
+    } else if (r instanceof HiveTableFunctionScan &&
+        !canOptimizeOutLateralView((HiveTableFunctionScan) r)) {
+      // In the case where the RelNode is a HiveTableFunctionScan, first we 
check
+      // to see if we can't optimize out the lateral view operator. We can 
optimize the
+      // operator out if only the udtf fields are grabbed out of the RelNode.  
If any
+      // of the base table fields need to be grabbed out, then a 'join' needs 
to be done
+      // and we need the lateral view.
+      TableFunctionScan tfs = ((TableFunctionScan) r);
+
+      // retrieve the base table source.
+      QueryBlockInfo tableFunctionSource = convertSource(tfs.getInput(0));
+      String sqAlias = tableFunctionSource.schema.get(0).table;
+      // the schema will contain the base table source fields
+      s = new Schema(tfs, sqAlias);
+
+      // next, set up the select for the parameters of the UDTF
+      List<ASTNode> children = new ArrayList<>();
+      RexCall call = (RexCall) tfs.getCall();
+      for (RexNode rn : call.getOperands()) {
+        ASTNode expr = rn.accept(new RexVisitor(s, r instanceof RexLiteral,
+            select.getCluster().getRexBuilder()));
+        children.add(expr);
+      }
+      ASTNode function = buildUDTFAST(call.getOperator().getName(), children);
+
+      // Add the function to the SELEXPR
+      ASTBuilder selexpr = ASTBuilder.construct(HiveParser.TOK_SELEXPR, 
"TOK_SELEXPR");
+      selexpr.add(function);
+
+      // Add only the table generated size columns to the select expr for the 
function,
+      // skipping over the base table columns from the input side of the join.
+      int i = 0;
+      for (ColumnInfo c : s) {
+        if (i++ < tableFunctionSource.schema.size()) {
+          continue;
+        }
+        selexpr.add(HiveParser.Identifier, c.column);
+      }
+      // add the table alias for the lateral view.
+      ASTBuilder tabAlias = ASTBuilder.construct(HiveParser.TOK_TABALIAS, 
"TOK_TABALIAS");
+      tabAlias.add(HiveParser.Identifier, sqAlias);
+
+      // add the table alias to the SEL_EXPR
+      selexpr.add(tabAlias.node());
+
+      // create the SELECT clause
+      ASTBuilder sel = ASTBuilder.construct(HiveParser.TOK_SELEXPR, 
"TOK_SELECT");
+      sel.add(selexpr.node());
+
+      // place the SELECT clause under the LATERAL VIEW clause
+      ASTBuilder lateralview = 
ASTBuilder.construct(HiveParser.TOK_LATERAL_VIEW, "TOK_LATERAL_VIEW");
+      lateralview.add(sel.node());
+
+      // finally, add the LATERAL VIEW clause under the left side source which 
is the base table.

Review Comment:
   I assume it is just a question of style but maybe adding an example as a 
comment makes easier to understand the tree we want to construct here WDT?
   Example:
   
https://github.com/apache/hive/blob/24092d1ae3279499c236b0f156cbb707c12f1e12/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java#L145-L151



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java:
##########
@@ -256,9 +256,11 @@ private RelDataType getRetType(RelOptCluster cluster, 
RelNode inputRel,
     Preconditions.checkState(retType.isStruct());
 
     // Add the type names and values from the udtf into the lists that will 
make up the
-    // return type.
+    // return type. Names need to be unique so add the table prefix
     allDataTypes.addAll(Lists.transform(retType.getFieldList(), 
RelDataTypeField::getType));
-    allDataTypeNames.addAll(columnAliases);
+    for (String s : columnAliases) {
+      allDataTypeNames.add(lateralTableAlias + "." + s);

Review Comment:
   Does this handle cases when identifiers has `.` character?
   Could you please add some tests where lateral view name and/or columns has 
special characters. Probably these should be quoted.



##########
ql/src/test/results/clientnegative/udf_assert_true.q.out:
##########
@@ -21,29 +21,17 @@ STAGE PLANS:
       Processor Tree:
         TableScan
           alias: src
-          Lateral View Forward
-            Select Operator
-              Lateral View Join Operator
-                outputColumnNames: _col6
-                Limit
-                  Number of rows: 2
-                  Select Operator
-                    expressions: assert_true((_col6 > 0)) (type: void)
-                    outputColumnNames: _col0
-                    ListSink
-            Select Operator
-              expressions: array(1,2) (type: array<int>)
-              outputColumnNames: _col0
-              UDTF Operator
-                function name: explode
-                Lateral View Join Operator
-                  outputColumnNames: _col6
-                  Limit
-                    Number of rows: 2
-                    Select Operator
-                      expressions: assert_true((_col6 > 0)) (type: void)
-                      outputColumnNames: _col0
-                      ListSink
+          Select Operator

Review Comment:
   Is LV optimized out in ASTConverter?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierForASTConv.java:
##########
@@ -382,6 +387,10 @@ private static boolean validExchangeChild(HiveSortExchange 
sortNode) {
     return sortNode.getInput() instanceof Project;
   }
 
+  private static boolean validTableFunctionScanChild(HiveTableFunctionScan 
htfsNode) {
+    return htfsNode.getInput(0) instanceof Project || htfsNode.getInput(0) 
instanceof HiveTableScan;

Review Comment:
   Can inputs be empty?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.hadoop.hive.ql.optimizer.calcite.rules;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelOptUtil;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
+import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Rule to transpose Filter and TableFunctionScan RelNodes
+ */
+public class HiveFilterTableFunctionTransposeRule extends RelOptRule {
+
+  public static final HiveFilterTableFunctionTransposeRule INSTANCE =
+          new 
HiveFilterTableFunctionTransposeRule(HiveRelFactories.HIVE_BUILDER);
+
+  public HiveFilterTableFunctionTransposeRule(RelBuilderFactory 
relBuilderFactory) {
+    super(operand(HiveFilter.class, operand(HiveTableFunctionScan.class, 
any())),
+        relBuilderFactory, null);
+  }
+
+  @Override
+  public boolean matches(RelOptRuleCall call) {
+    final Filter filterRel = call.rel(0);
+    final HiveTableFunctionScan tableFunctionScanRel = call.rel(1);
+
+    RexNode condition = filterRel.getCondition();
+    if (!HiveCalciteUtil.isDeterministic(condition)) {
+      return false;
+    }
+
+    // If the HiveTableFunctionScan is a special inline(array(...))
+    // udtf, the table is generated from this node. The underlying
+    // RelNode will be a dummy table so no filter condition should
+    // pass through the HiveTableFunctionScan.
+    if (isInlineArray(tableFunctionScanRel)) {
+      return false;
+    }
+
+    // If the HiveTableFunctionScan is not a lateral view, the return type
+    // for the RelNode only contains the output of the udtf so no filter
+    // condition can be passed through.
+    if (!tableFunctionScanRel.isLateralView()) {
+      return false;
+    }
+
+    RelNode inputRel = tableFunctionScanRel.getInput(0);
+
+    // The TableFunctionScan is always created such that all the input RelNode
+    // fields are present in its RelNode.  If a Filter has an InputRef that is
+    // greater then the number of the RelNode below the TableFunctionScan, that
+    // means it was a field created by the TableFunctionScan and thus the 
Filter
+    // cannot be pushed through.
+    //
+    // We check for each individual conjunction (breaking it up by top level 
'and'
+    // conditions).
+    int numFieldsInInput = inputRel.getRowType().getFieldCount();
+
+    for (RexNode ce : RelOptUtil.conjunctions(filterRel.getCondition())) {
+      Set<Integer> inputRefs = HiveCalciteUtil.getInputRefs(ce);
+
+      boolean canBePushed = true;
+      for (Integer inputRef : inputRefs) {
+        if (inputRef >= numFieldsInInput) {
+          canBePushed = false;
+          break;
+        }
+      }
+
+      if (canBePushed) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public void onMatch(RelOptRuleCall call) {
+    final Filter filter = call.rel(0);
+    final HiveTableFunctionScan tfs = call.rel(1);
+    final RelNode inputRel = tfs.getInput(0);
+    final int numFieldsInInput = inputRel.getRowType().getFieldCount();
+
+    final List<RexNode> newPartKeyFilterConditions = new ArrayList<>();
+    final List<RexNode> unpushedFilterConditions = new ArrayList<>();
+
+    // Check for each individual 'and' condition so that we can push partial
+    // expressions through.
+    for (RexNode ce : RelOptUtil.conjunctions(filter.getCondition())) {
+      Set<Integer> inputRefs = HiveCalciteUtil.getInputRefs(ce);
+      boolean canBePushed = true;
+      // We can only push if all the InputRef pointers are referencing the
+      // input RelNode to the TableFunctionScan
+      for (Integer inputRef : inputRefs) {
+        if (inputRef >= numFieldsInInput) {
+          canBePushed = false;
+          break;
+        }
+      }
+      if (canBePushed) {
+        newPartKeyFilterConditions.add(ce);
+      } else {
+        unpushedFilterConditions.add(ce);
+      }
+    }
+
+    // The "matches" check should guarantee there's something to push.
+    Preconditions.checkState(!newPartKeyFilterConditions.isEmpty());

Review Comment:
   Can we silently exit the rule? If not please add an error message.



-- 
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: gitbox-unsubscr...@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscr...@hive.apache.org
For additional commands, e-mail: gitbox-h...@hive.apache.org

Reply via email to