This is an automated email from the ASF dual-hosted git repository.

krisztiankasa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git


The following commit(s) were added to refs/heads/master by this push:
     new 4c87878dc67 HIVE-27391: Refactor Calcite node generation from lateral 
views (Stephen Carlin, reviewed by Krisztian Kasa, Kirti Ruge)
4c87878dc67 is described below

commit 4c87878dc6701b68f69f41ddf155e514957876be
Author: scarlin-cloudera <[email protected]>
AuthorDate: Thu Jun 15 08:24:53 2023 -0700

    HIVE-27391: Refactor Calcite node generation from lateral views (Stephen 
Carlin, reviewed by Krisztian Kasa, Kirti Ruge)
    
    This commit serves as a first step in being able to generate all
    lateral views in CBO. Currently, only "inline(array())" udtfs are
    converted into a CBO plan.
    
    The lateral view generation has been extracted from Calcite planner
    and put into a standalone class with the hope that we can trim down
    the CalcitePlanner from a 5000 line class to something more manageable.
    
    In this commit, no "q" test output has been changed. There are some
    CBO statements added within tablevalues.q just to ensure that CBO is
    processing correctly.
    
    The SemanticAnalyzer changes are small changes to make some utility
    methods static so they could be accessed from LateralViewPlan. As
    future cleanup, these static classes should be moved outside of
    SemanticAnalyzer to thin down the 15000+ line file.
    
    The same is true for CalcitePlanner "gen*RexNode*" classes which are
    also now static and accessible from LateralViewPlan
    
    A new rule was also created as a precursor to adding CBO support for
    all lateral views. The only supported lateral view is the "inline(array())"
    lateral view. The special quality of this UDTF is that the lateral
    view does not need a lateral view operator. The table is generated
    through the inline UDTF function and is joined with the base (input) table
    fields. The initial implementation hacked this to work by placing
    the base table fields within the "inline(array())" functions so that
    the top level joined fields are within the array and no join is needed.
    This commit places this special case within a rule to make this
    manipulation. This will allow a commit in the near future to avoid
    special case code in the LateralViewPlan object.
---
 .../hadoop/hive/ql/exec/FunctionRegistry.java      |   8 +-
 .../HiveOptimizeInlineArrayTableFunctionRule.java  | 133 +++++++++++
 .../calcite/translator/SqlFunctionConverter.java   |   3 +-
 .../hadoop/hive/ql/parse/CalcitePlanner.java       | 217 +++++------------
 .../hadoop/hive/ql/parse/SemanticAnalyzer.java     |   6 +-
 .../hive/ql/parse/relnodegen/LateralViewPlan.java  | 265 +++++++++++++++++++++
 .../hadoop/hive/ql/parse/type/FunctionHelper.java  |   7 +
 .../hive/ql/parse/type/HiveFunctionHelper.java     |  20 ++
 .../hive/ql/parse/type/TestHiveFunctionHelper.java |  65 +++++
 ql/src/test/queries/clientpositive/tablevalues.q   |  34 +++
 .../results/clientpositive/llap/tablevalues.q.out  | 126 ++++++++++
 11 files changed, 716 insertions(+), 168 deletions(-)

diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java 
b/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
index 681c18230c8..b2186e5d522 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
@@ -254,6 +254,10 @@ public final class FunctionRegistry {
 
   public static final String BLOOM_FILTER_FUNCTION = "bloom_filter";
   public static final String WINDOWING_TABLE_FUNCTION = 
"windowingtablefunction";
+
+  public static final String ARRAY_FUNC_NAME = "array";
+  public static final String INLINE_FUNC_NAME = "inline";
+
   private static final String NOOP_TABLE_FUNCTION = "noop";
   private static final String NOOP_MAP_TABLE_FUNCTION = "noopwithmap";
   private static final String NOOP_STREAMING_TABLE_FUNCTION = "noopstreaming";
@@ -575,7 +579,7 @@ public final class FunctionRegistry {
     system.registerGenericUDF("java_method", GenericUDFReflect.class);
     system.registerGenericUDF("exception_in_vertex_udf", 
GenericUDFExceptionInVertex.class);
 
-    system.registerGenericUDF("array", GenericUDFArray.class);
+    system.registerGenericUDF(ARRAY_FUNC_NAME, GenericUDFArray.class);
     system.registerGenericUDF("assert_true", GenericUDFAssertTrue.class);
     system.registerGenericUDF("assert_true_oom", 
GenericUDFAssertTrueOOM.class);
     system.registerGenericUDF("map", GenericUDFMap.class);
@@ -635,7 +639,7 @@ public final class FunctionRegistry {
     // Generic UDTF's
     system.registerGenericUDTF("explode", GenericUDTFExplode.class);
     system.registerGenericUDTF("replicate_rows", 
GenericUDTFReplicateRows.class);
-    system.registerGenericUDTF("inline", GenericUDTFInline.class);
+    system.registerGenericUDTF(INLINE_FUNC_NAME, GenericUDTFInline.class);
     system.registerGenericUDTF("json_tuple", GenericUDTFJSONTuple.class);
     system.registerGenericUDTF("parse_url_tuple", 
GenericUDTFParseUrlTuple.class);
     system.registerGenericUDTF("posexplode", GenericUDTFPosExplode.class);
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java
 
b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java
new file mode 100644
index 00000000000..e78b5172edd
--- /dev/null
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java
@@ -0,0 +1,133 @@
+/*
+ * 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.RelOptCluster;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeField;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * This rule optimizes the inline udtf in a HiveTableFunctionScan when it
+ * has an array of structures. The RelNode for a HiveTableFunctionScan places
+ * the input references as the first elements in the return type followed by
+ * the udtf return value which represents the items in the generated table. 
Take the
+ * case where the base (input) table has col1, and the inline function is 
represented by:
+ * inline(array( struct1(col2, col3), struct2(col2, col3), struct3(col2, 
col3), etc...)),
+ * ...and the return value for the table scan node is (col1, col2, col3). In 
this case,
+ * the same col1 value is joined with the structures within the inline array 
for the
+ * col2 and col3 values.
+ *
+ * The optimization is to put the "col1" value within the inline array, 
resulting in
+ * in the new structure:
+ * inline(array(struct1(col1, col2, col3), struct2(col1, col2, col3), ...)
+ * By doing this, we avoid creating a lateral view join operator and a lateral 
view forward
+ * operator at runtime.
+ */
+public class HiveOptimizeInlineArrayTableFunctionRule extends RelOptRule {
+
+  public static final HiveOptimizeInlineArrayTableFunctionRule INSTANCE =
+          new 
HiveOptimizeInlineArrayTableFunctionRule(HiveRelFactories.HIVE_BUILDER);
+
+  public HiveOptimizeInlineArrayTableFunctionRule(RelBuilderFactory 
relBuilderFactory) {
+    super(operand(HiveTableFunctionScan.class, any()), relBuilderFactory, 
null);
+  }
+
+  @Override
+  public boolean matches(RelOptRuleCall call) {
+    final HiveTableFunctionScan tableFunctionScanRel = call.rel(0);
+
+    if (!(tableFunctionScanRel.getCall() instanceof RexCall)) {
+      return false;
+    }
+
+    RexCall udtfCall = (RexCall) tableFunctionScanRel.getCall();
+    if 
(!FunctionRegistry.INLINE_FUNC_NAME.equalsIgnoreCase(udtfCall.getOperator().getName()))
 {
+      return false;
+    }
+
+    Preconditions.checkState(!udtfCall.getOperands().isEmpty());
+    RexNode operand = udtfCall.getOperands().get(0);
+    if (!(operand instanceof RexCall)) {
+      return false;
+    }
+    RexCall firstOperand = (RexCall) operand;
+    if 
(!FunctionRegistry.ARRAY_FUNC_NAME.equalsIgnoreCase(firstOperand.getOperator().getName()))
 {
+      return false;
+    }
+    Preconditions.checkState(!firstOperand.getOperands().isEmpty());
+    int numStructParams = 
firstOperand.getOperands().get(0).getType().getFieldCount();
+
+    if (tableFunctionScanRel.getRowType().getFieldCount() == numStructParams) {
+      return false;
+    }
+
+    return true;
+  }
+
+  public void onMatch(RelOptRuleCall call) {
+    final HiveTableFunctionScan tfs = call.rel(0);
+    RelNode inputRel = tfs.getInput(0);
+    RexCall inlineCall = (RexCall) tfs.getCall();
+    RexCall arrayCall = (RexCall) inlineCall.getOperands().get(0);
+    RelOptCluster cluster = tfs.getCluster();
+
+    List<RexNode> inputRefs = 
Lists.transform(inputRel.getRowType().getFieldList(),
+        input -> new RexInputRef(input.getIndex(), input.getType()));
+    List<RexNode> newStructExprs = new ArrayList<>();
+
+    for (RexNode currentStructOperand : arrayCall.getOperands()) {
+      List<RexNode> allOperands = new ArrayList<>(inputRefs);
+      RexCall structCall = (RexCall) currentStructOperand;
+      allOperands.addAll(structCall.getOperands());
+      newStructExprs.add(cluster.getRexBuilder().makeCall(structCall.op, 
allOperands));
+    }
+
+    List<RelDataType> returnTypes = new ArrayList<>(
+        Lists.transform(inputRel.getRowType().getFieldList(), 
RelDataTypeField::getType));
+    RexCall firstStructCall = (RexCall) arrayCall.getOperands().get(0);
+    returnTypes.addAll(Lists.transform(firstStructCall.getOperands(), 
RexNode::getType));
+
+    List<RexNode> newArrayCall = Collections.singletonList(
+        cluster.getRexBuilder().makeCall(arrayCall.op, newStructExprs));
+    RexNode newInlineCall =
+        cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, 
newArrayCall);
+
+    final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
+        tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
+        tfs.getColumnMappings());
+
+    call.transformTo(newTableFunctionScanNode);
+  }
+}
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java
 
b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java
index 601f5f5b2e0..9fdbfa9a38a 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java
@@ -386,7 +386,8 @@ public class SqlFunctionConverter {
       registerFunction("in", HiveIn.INSTANCE, hToken(HiveParser.Identifier, 
"in"));
       registerFunction("between", HiveBetween.INSTANCE, 
hToken(HiveParser.Identifier, "between"));
       registerFunction("struct", SqlStdOperatorTable.ROW, 
hToken(HiveParser.Identifier, "struct"));
-      registerFunction("array", SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR, 
hToken(HiveParser.Identifier, "array"));
+      registerFunction(FunctionRegistry.ARRAY_FUNC_NAME,
+          SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR, 
hToken(HiveParser.Identifier, FunctionRegistry.ARRAY_FUNC_NAME));
       registerFunction("map", SqlStdOperatorTable.MAP_VALUE_CONSTRUCTOR, 
hToken(HiveParser.Identifier, "map"));
       registerFunction("isnotnull", SqlStdOperatorTable.IS_NOT_NULL, 
hToken(HiveParser.Identifier, "isnotnull"));
       registerFunction("isnull", SqlStdOperatorTable.IS_NULL, 
hToken(HiveParser.Identifier, "isnull"));
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java
index 9e3f02b51b8..662dbecddfa 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java
@@ -17,6 +17,7 @@
  */
 package org.apache.hadoop.hive.ql.parse;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ImmutableBiMap;
 import com.google.common.collect.ImmutableList;
@@ -233,6 +234,7 @@ import 
org.apache.hadoop.hive.ql.optimizer.calcite.rules.HiveJoinProjectTranspos
 import 
org.apache.hadoop.hive.ql.optimizer.calcite.rules.HiveJoinPushTransitivePredicatesRule;
 import 
org.apache.hadoop.hive.ql.optimizer.calcite.rules.HiveJoinToMultiJoinRule;
 import org.apache.hadoop.hive.ql.optimizer.calcite.rules.HiveAntiSemiJoinRule;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.rules.HiveOptimizeInlineArrayTableFunctionRule;
 import 
org.apache.hadoop.hive.ql.optimizer.calcite.rules.HivePartitionPruneRule;
 import 
org.apache.hadoop.hive.ql.optimizer.calcite.rules.HivePointLookupOptimizerRule;
 import org.apache.hadoop.hive.ql.optimizer.calcite.rules.HivePreFilteringRule;
@@ -297,6 +299,7 @@ import 
org.apache.hadoop.hive.ql.parse.WindowingSpec.WindowExpressionSpec;
 import org.apache.hadoop.hive.ql.parse.WindowingSpec.WindowFunctionSpec;
 import org.apache.hadoop.hive.ql.parse.WindowingSpec.WindowSpec;
 import org.apache.hadoop.hive.ql.parse.WindowingSpec.WindowType;
+import org.apache.hadoop.hive.ql.parse.relnodegen.LateralViewPlan;
 import org.apache.hadoop.hive.ql.parse.type.RexNodeTypeCheck;
 import org.apache.hadoop.hive.ql.parse.type.TypeCheckCtx;
 import org.apache.hadoop.hive.ql.parse.type.TypeCheckProcFactory;
@@ -318,7 +321,6 @@ import 
org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
 import 
org.apache.hadoop.hive.serde2.objectinspector.StandardStructObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.StructField;
 import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
-import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
@@ -1836,6 +1838,7 @@ public class CalcitePlanner extends SemanticAnalyzer {
       } else {
         rules.add(HiveFilterProjectTransposeRule.DETERMINISTIC);
       }
+      rules.add(HiveOptimizeInlineArrayTableFunctionRule.INSTANCE);
       rules.add(HiveFilterSetOpTransposeRule.INSTANCE);
       rules.add(HiveFilterSortTransposeRule.INSTANCE);
       rules.add(HiveFilterJoinRule.JOIN);
@@ -2801,7 +2804,7 @@ public class CalcitePlanner extends SemanticAnalyzer {
      * @return
      * @throws SemanticException
      */
-    private RelNode genJoinLogicalPlan(ASTNode joinParseTree, Map<String, 
RelNode> aliasToRel,
+    private RelNode genJoinLogicalPlan(QB qb, ASTNode joinParseTree, 
Map<String, RelNode> aliasToRel,
                                        ImmutableMap<String, Integer> 
outerNameToPosMap, RowResolver outerRR)
         throws SemanticException {
       RelNode leftRel = null;
@@ -2847,9 +2850,9 @@ public class CalcitePlanner extends SemanticAnalyzer {
         leftTableAlias = getTableAlias(left);
         leftRel = aliasToRel.get(leftTableAlias);
       } else if (SemanticAnalyzer.isJoinToken(left)) {
-        leftRel = genJoinLogicalPlan(left, aliasToRel, outerNameToPosMap, 
outerRR);
+        leftRel = genJoinLogicalPlan(qb, left, aliasToRel, outerNameToPosMap, 
outerRR);
       } else if (left.getToken().getType() == HiveParser.TOK_LATERAL_VIEW) {
-        leftRel = genLateralViewPlans(left, aliasToRel);
+        leftRel = genLateralViewPlans(qb, left, aliasToRel);
       } else {
         assert (false);
       }
@@ -2863,7 +2866,7 @@ public class CalcitePlanner extends SemanticAnalyzer {
         rightTableAlias = getTableAlias(right);
         rightRel = aliasToRel.get(rightTableAlias);
       } else if (right.getToken().getType() == HiveParser.TOK_LATERAL_VIEW) {
-        rightRel = genLateralViewPlans(right, aliasToRel);
+        rightRel = genLateralViewPlans(qb, right, aliasToRel);
       }  else {
         assert (false);
       }
@@ -3251,145 +3254,27 @@ public class CalcitePlanner extends SemanticAnalyzer {
       }
     }
 
-    private RelNode genLateralViewPlans(ASTNode lateralView, Map<String, 
RelNode> aliasToRel)
+    private RelNode genLateralViewPlans(QB qb, ASTNode lateralView, 
Map<String, RelNode> aliasToRel)
             throws SemanticException {
-      final RexBuilder rexBuilder = this.cluster.getRexBuilder();
-      final RelDataTypeFactory dtFactory = this.cluster.getTypeFactory();
-      final String inlineFunctionName =
-          GenericUDTFInline.class.getAnnotation(Description.class).name();
-      int numChildren = lateralView.getChildCount();
-      assert (numChildren == 2);
-
-      // 1) Obtain input and all related data structures
+      LateralViewPlan.validateLateralView(lateralView);
+
       ASTNode next = (ASTNode) lateralView.getChild(1);
-      RelNode inputRel = null;
-      switch (next.getToken().getType()) {
-        case HiveParser.TOK_TABREF:
-        case HiveParser.TOK_SUBQUERY:
-        case HiveParser.TOK_PTBLFUNCTION:
-          String inputTableAlias = getTableAlias(next);
-          inputRel = aliasToRel.get(inputTableAlias);
-          break;
-        case HiveParser.TOK_LATERAL_VIEW:
-          inputRel = genLateralViewPlans(next, aliasToRel);
-          break;
-        default:
-          throw new SemanticException(ASTErrorUtils.getMsg(
-              ErrorMsg.LATERAL_VIEW_INVALID_CHILD.getMsg(), lateralView));
-      }
-      // Input row resolver
-      RowResolver inputRR = this.relToHiveRR.get(inputRel);
-      // Extract input refs. They will serve as input for the function 
invocation
-      List<RexNode> inputRefs = 
Lists.transform(inputRel.getRowType().getFieldList(),
-          input -> new RexInputRef(input.getIndex(), input.getType()));
-      // Extract type for the arguments
-      List<RelDataType> inputRefsTypes = new ArrayList<>();
-      for (int i = 0; i < inputRefs.size(); i++) {
-        inputRefsTypes.add(inputRefs.get(i).getType());
-      }
-      // Input name to position map
-      ImmutableMap<String, Integer> inputPosMap = 
this.relToHiveColNameCalcitePosMap.get(inputRel);
-
-      // 2) Generate HiveTableFunctionScan RelNode for lateral view
-      // TODO: Support different functions (not only INLINE) with LATERAL VIEW 
JOIN
-      // ^(TOK_LATERAL_VIEW ^(TOK_SELECT ^(TOK_SELEXPR ^(TOK_FUNCTION 
Identifier["inline"] valuesClause) identifier* tableAlias)))
-      final ASTNode selExprClause =
-          (ASTNode) lateralView.getChild(0).getChild(0);
-      final ASTNode functionCall =
-          (ASTNode) selExprClause.getChild(0);
-      if 
(functionCall.getChild(0).getText().compareToIgnoreCase(inlineFunctionName) != 
0) {
-        throw new SemanticException("CBO only supports inline LVJ");
-      }
-      final ASTNode valuesClause =
-          (ASTNode) functionCall.getChild(1);
-      // Output types. They will be the concatenation of the input refs types 
and
-      // the types of the expressions for the lateral view generated rows
-      // Generate all expressions from lateral view
-      RexCall valuesExpr = (RexCall) genRexNode(
-          valuesClause, inputRR, false, false, cluster.getRexBuilder());
-      RelDataType valuesRowType = valuesExpr.getType().getComponentType();
-      List<RexNode> newStructExprs = new ArrayList<>();
-      for (RexNode structExpr : valuesExpr.getOperands()) {
-        RexCall structCall = (RexCall) structExpr;
-        List<RexNode> exprs = new ArrayList<>(inputRefs);
-        exprs.addAll(structCall.getOperands());
-        newStructExprs.add(rexBuilder.makeCall(structCall.op, exprs));
-      }
-      RexNode convertedFinalValuesExpr =
-          rexBuilder.makeCall(valuesExpr.op, newStructExprs);
-      // The return type will be the concatenation of input type and original 
values type
-      RelDataType retType = 
SqlValidatorUtil.deriveJoinRowType(inputRel.getRowType(),
-          valuesRowType, JoinRelType.INNER, dtFactory, null, 
ImmutableList.of());
-
-      // Create inline SQL operator
-      FunctionInfo inlineFunctionInfo = 
FunctionRegistry.getFunctionInfo(inlineFunctionName);
-      SqlOperator calciteOp = SqlFunctionConverter.getCalciteOperator(
-          inlineFunctionName, inlineFunctionInfo.getGenericUDTF(),
-          ImmutableList.copyOf(inputRefsTypes), retType);
-
-      RelNode htfsRel = HiveTableFunctionScan.create(cluster, 
TraitsUtil.getDefaultTraitSet(cluster),
-          ImmutableList.of(inputRel), rexBuilder.makeCall(calciteOp, 
convertedFinalValuesExpr),
-          null, retType, null);
-
-      // 3) Keep track of colname-to-posmap && RR for new op
-      RowResolver outputRR = new RowResolver();
-      // Add all input columns
-      if (!RowResolver.add(outputRR, inputRR)) {
-        LOG.warn("Duplicates detected when adding columns to RR: see previous 
message");
-      }
-      // Add all columns from lateral view
-      // First we extract the information that the query provides
-      String tableAlias = null;
-      List<String> columnAliases = new ArrayList<>();
-      Set<String> uniqueNames = new HashSet<>();
-      for (int i = 1; i < selExprClause.getChildren().size(); i++) {
-        ASTNode child = (ASTNode) selExprClause.getChild(i);
-        switch (child.getToken().getType()) {
-          case HiveParser.TOK_TABALIAS:
-            tableAlias = unescapeIdentifier(child.getChild(0).getText());
-            break;
-          default:
-            String colAlias = unescapeIdentifier(child.getText());
-            if (uniqueNames.contains(colAlias)) {
-              // Column aliases defined by query for lateral view output are 
duplicated
-              throw new 
SemanticException(ErrorMsg.COLUMN_ALIAS_ALREADY_EXISTS.getMsg(colAlias));
-            }
-            columnAliases.add(colAlias);
-            uniqueNames.add(colAlias);
-        }
-      }
-      if (tableAlias == null) {
-        // Parser enforces that table alias is added, but check again
-        throw new SemanticException("Alias should be specified LVJ");
-      }
-      if (!columnAliases.isEmpty() &&
-              columnAliases.size() != valuesRowType.getFieldCount()) {
-        // Number of columns in the aliases does not match with number of 
columns
-        // generated by the lateral view
-        throw new SemanticException(ErrorMsg.UDTF_ALIAS_MISMATCH.getMsg());
-      }
-      if (columnAliases.isEmpty()) {
-        // Auto-generate column aliases
-        for (int i = 0; i < valuesRowType.getFieldCount(); i++) {
-          columnAliases.add(SemanticAnalyzer.getColumnInternalName(i));
-        }
-      }
-      ListTypeInfo listTypeInfo = (ListTypeInfo) 
TypeConverter.convert(valuesExpr.getType()); // Array should have ListTypeInfo
-      StructTypeInfo typeInfos = (StructTypeInfo) 
listTypeInfo.getListElementTypeInfo(); // Within the list, we extract types
-      for (int i = 0, j = 0; i < columnAliases.size(); i++) {
-        String internalColName;
-        do {
-          internalColName = SemanticAnalyzer.getColumnInternalName(j++);
-        } while (inputRR.getPosition(internalColName) != -1);
-        outputRR.put(tableAlias, columnAliases.get(i),
-            new ColumnInfo(internalColName,  
typeInfos.getAllStructFieldTypeInfos().get(i),
-                tableAlias, false));
-      }
-      this.relToHiveColNameCalcitePosMap.put(htfsRel, 
buildHiveToCalciteColumnMap(outputRR));
-      this.relToHiveRR.put(htfsRel, outputRR);
 
-      // 4) Return new operator
-      return htfsRel;
+      // next token is either the table alias name or another lateral view 
(which we will call
+      // recursively)
+      RelNode inputRel = next.getToken().getType() == 
HiveParser.TOK_LATERAL_VIEW
+          ? genLateralViewPlans(qb, next, aliasToRel)
+          : aliasToRel.get(getTableAlias(next));
+
+      LateralViewPlan lateralViewPlan = new LateralViewPlan(lateralView, 
this.cluster,
+          inputRel, this.relToHiveRR.get(inputRel), unparseTranslator, conf,
+          functionHelper);
+
+      qb.addAlias(lateralViewPlan.lateralTableAlias);
+      this.relToHiveColNameCalcitePosMap.put(lateralViewPlan.lateralViewRel,
+          buildHiveToCalciteColumnMap(lateralViewPlan.outputRR));
+      this.relToHiveRR.put(lateralViewPlan.lateralViewRel, 
lateralViewPlan.outputRR);
+      return lateralViewPlan.lateralViewRel;
     }
 
     private boolean genSubQueryRelNode(QB qb, ASTNode node, RelNode srcRel, 
boolean forHavingClause,
@@ -3714,7 +3599,8 @@ public class CalcitePlanner extends SemanticAnalyzer {
         // We allow stateful functions in the SELECT list (but nowhere else)
         tcCtx.setAllowStatefulFunctions(true);
         tcCtx.setAllowDistinctFunctions(false);
-        RexNode exp = genRexNode((ASTNode) aggAst.getChild(0), inputRR, tcCtx);
+        tcCtx.setUnparseTranslator(unparseTranslator);
+        RexNode exp = genRexNode((ASTNode) aggAst.getChild(0), inputRR, tcCtx, 
conf);
         aInfo = new AggregateInfo(
             aggParameters, TypeConverter.convert(exp.getType()), aggName, 
isDistinct);
       }
@@ -4215,7 +4101,8 @@ public class CalcitePlanner extends SemanticAnalyzer {
         for (PartitionExpression pExpr : pExprs) {
           TypeCheckCtx tcCtx = new TypeCheckCtx(inputRR, 
cluster.getRexBuilder());
           tcCtx.setAllowStatefulFunctions(true);
-          RexNode exp = genRexNode(pExpr.getExpression(), inputRR, tcCtx);
+          tcCtx.setUnparseTranslator(unparseTranslator);
+          RexNode exp = genRexNode(pExpr.getExpression(), inputRR, tcCtx, 
conf);
           pKeys.add(exp);
         }
       }
@@ -4231,7 +4118,8 @@ public class CalcitePlanner extends SemanticAnalyzer {
         for (OrderExpression oExpr : oExprs) {
           TypeCheckCtx tcCtx = new TypeCheckCtx(inputRR, 
cluster.getRexBuilder());
           tcCtx.setAllowStatefulFunctions(true);
-          RexNode ordExp = genRexNode(oExpr.getExpression(), inputRR, tcCtx);
+          tcCtx.setUnparseTranslator(unparseTranslator);
+          RexNode ordExp = genRexNode(oExpr.getExpression(), inputRR, tcCtx, 
conf);
           Set<SqlKind> flags = new HashSet<SqlKind>();
           if (oExpr.getOrder() == 
org.apache.hadoop.hive.ql.parse.PTFInvocationSpec.Order.DESC) {
             flags.add(SqlKind.DESCENDING);
@@ -4740,12 +4628,13 @@ public class CalcitePlanner extends SemanticAnalyzer {
             TypeCheckCtx tcCtx = new TypeCheckCtx(inputRR, 
cluster.getRexBuilder());
             // We allow stateful functions in the SELECT list (but nowhere 
else)
             tcCtx.setAllowStatefulFunctions(true);
+            tcCtx.setUnparseTranslator(unparseTranslator);
             if (!qbp.getDestToGroupBy().isEmpty()) {
               // Special handling of grouping function
               expr = rewriteGroupingFunctionAST(getGroupByForClause(qbp, 
selClauseName), expr,
                       !cubeRollupGrpSetPresent);
             }
-            RexNode expression = genRexNode(expr, inputRR, tcCtx);
+            RexNode expression = genRexNode(expr, inputRR, tcCtx, conf);
 
             String recommended = recommendName(expression, colAlias, inputRR);
             if (recommended != null && outputRR.get(null, recommended) == 
null) {
@@ -5146,7 +5035,7 @@ public class CalcitePlanner extends SemanticAnalyzer {
 
       // 1.3.2 process the actual join
       if (qb.getParseInfo().getJoinExpr() != null) {
-        srcRel = genJoinLogicalPlan(qb.getParseInfo().getJoinExpr(), 
aliasToRel, outerNameToPosMap, outerRR);
+        srcRel = genJoinLogicalPlan(qb, qb.getParseInfo().getJoinExpr(), 
aliasToRel, outerNameToPosMap, outerRR);
       } else {
         // If no join then there should only be either 1 TS or 1 SubQuery
         Map.Entry<String, RelNode> uniqueAliasToRel = 
aliasToRel.entrySet().iterator().next();
@@ -5154,7 +5043,7 @@ public class CalcitePlanner extends SemanticAnalyzer {
         // If it contains a LV
         List<ASTNode> lateralViews = 
getQBParseInfo(qb).getAliasToLateralViews().get(uniqueAliasToRel.getKey());
         if (lateralViews != null) {
-          srcRel = genLateralViewPlans(Iterables.getLast(lateralViews), 
aliasToRel);
+          srcRel = genLateralViewPlans(qb, Iterables.getLast(lateralViews), 
aliasToRel);
         }
       }
 
@@ -5430,7 +5319,8 @@ public class CalcitePlanner extends SemanticAnalyzer {
     TypeCheckCtx tcCtx = new TypeCheckCtx(input, rexBuilder, useCaching, 
false);
     tcCtx.setOuterRR(outerRR);
     tcCtx.setSubqueryToRelNode(subqueryToRelNode);
-    return genRexNode(expr, input, tcCtx);
+    tcCtx.setUnparseTranslator(unparseTranslator);
+    return genRexNode(expr, input, tcCtx, conf);
   }
 
   /**
@@ -5446,7 +5336,8 @@ public class CalcitePlanner extends SemanticAnalyzer {
   RexNode genRexNode(ASTNode expr, RowResolver input, boolean useCaching,
       boolean foldExpr, RexBuilder rexBuilder) throws SemanticException {
     TypeCheckCtx tcCtx = new TypeCheckCtx(input, rexBuilder, useCaching, 
foldExpr);
-    return genRexNode(expr, input, tcCtx);
+    tcCtx.setUnparseTranslator(unparseTranslator);
+    return genRexNode(expr, input, tcCtx, conf);
   }
 
   /**
@@ -5456,21 +5347,22 @@ public class CalcitePlanner extends SemanticAnalyzer {
   Map<ASTNode, RexNode> genAllRexNode(ASTNode expr, RowResolver input, 
RexBuilder rexBuilder)
       throws SemanticException {
     TypeCheckCtx tcCtx = new TypeCheckCtx(input, rexBuilder);
-    return genAllRexNode(expr, input, tcCtx);
+    tcCtx.setUnparseTranslator(unparseTranslator);
+    return genAllRexNode(expr, input, tcCtx, conf);
   }
 
   /**
    * Returns a Calcite {@link RexNode} for the expression.
    * If it is evaluated already in previous operator, it can be retrieved from 
cache.
    */
-  RexNode genRexNode(ASTNode expr, RowResolver input,
-      TypeCheckCtx tcCtx) throws SemanticException {
+  public static RexNode genRexNode(ASTNode expr, RowResolver input,
+      TypeCheckCtx tcCtx, HiveConf conf) throws SemanticException {
     RexNode cached = null;
     if (tcCtx.isUseCaching()) {
       cached = getRexNodeCached(expr, input, tcCtx);
     }
     if (cached == null) {
-      Map<ASTNode, RexNode> allExprs = genAllRexNode(expr, input, tcCtx);
+      Map<ASTNode, RexNode> allExprs = genAllRexNode(expr, input, tcCtx, conf);
       return allExprs.get(expr);
     }
     return cached;
@@ -5479,13 +5371,14 @@ public class CalcitePlanner extends SemanticAnalyzer {
   /**
    * Find RexNode for the expression cached in the RowResolver. Returns null 
if not exists.
    */
-  private RexNode getRexNodeCached(ASTNode node, RowResolver input,
+  private static RexNode getRexNodeCached(ASTNode node, RowResolver input,
       TypeCheckCtx tcCtx) throws SemanticException {
+    Preconditions.checkNotNull(tcCtx.getUnparseTranslator());
     ColumnInfo colInfo = input.getExpression(node);
     if (colInfo != null) {
       ASTNode source = input.getExpressionSource(node);
       if (source != null) {
-        unparseTranslator.addCopyTranslation(node, source);
+        tcCtx.getUnparseTranslator().addCopyTranslation(node, source);
       }
       return RexNodeTypeCheck.toExprNode(colInfo, input, 0, 
tcCtx.getRexBuilder());
     }
@@ -5506,10 +5399,10 @@ public class CalcitePlanner extends SemanticAnalyzer {
    * @return expression to exprNodeDesc mapping
    * @throws SemanticException Failed to evaluate expression
    */
-  Map<ASTNode, RexNode> genAllRexNode(ASTNode expr, RowResolver input,
-      TypeCheckCtx tcCtx) throws SemanticException {
+  private static Map<ASTNode, RexNode> genAllRexNode(ASTNode expr, RowResolver 
input,
+      TypeCheckCtx tcCtx, HiveConf conf) throws SemanticException {
     // Create the walker and  the rules dispatcher.
-    tcCtx.setUnparseTranslator(unparseTranslator);
+    Preconditions.checkNotNull(tcCtx.getUnparseTranslator());
 
     Map<ASTNode, RexNode> nodeOutputs =
         RexNodeTypeCheck.genExprNode(expr, tcCtx);
@@ -5531,7 +5424,7 @@ public class CalcitePlanner extends SemanticAnalyzer {
       throw new SemanticException("TOK_ALLCOLREF is not supported in current 
context");
     }
 
-    if (!unparseTranslator.isEnabled()) {
+    if (!tcCtx.getUnparseTranslator().isEnabled()) {
       // Not creating a view, so no need to track view expansions.
       return nodeOutputs;
     }
@@ -5574,13 +5467,13 @@ public class CalcitePlanner extends SemanticAnalyzer {
       replacementText.append(HiveUtils.unparseIdentifier(tmp[0], conf));
       replacementText.append(".");
       replacementText.append(HiveUtils.unparseIdentifier(tmp[1], conf));
-      unparseTranslator.addTranslation(node, replacementText.toString());
+      tcCtx.getUnparseTranslator().addTranslation(node, 
replacementText.toString());
     }
 
     for (ASTNode node : fieldDescList) {
-      Map<ASTNode, String> map = translateFieldDesc(node);
+      Map<ASTNode, String> map = translateFieldDesc(node, conf);
       for (Entry<ASTNode, String> entry : map.entrySet()) {
-        unparseTranslator.addTranslation(entry.getKey(), 
entry.getValue().toLowerCase());
+        tcCtx.getUnparseTranslator().addTranslation(entry.getKey(), 
entry.getValue().toLowerCase());
       }
     }
 
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
index 2f7f92279b4..0e8d309210b 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
@@ -13303,7 +13303,7 @@ public class SemanticAnalyzer extends 
BaseSemanticAnalyzer {
     }
 
     for (ASTNode node : fieldDescList) {
-      Map<ASTNode, String> map = translateFieldDesc(node);
+      Map<ASTNode, String> map = translateFieldDesc(node, conf);
       for (Entry<ASTNode, String> entry : map.entrySet()) {
         unparseTranslator.addTranslation(entry.getKey(), 
entry.getValue().toLowerCase());
       }
@@ -13312,11 +13312,11 @@ public class SemanticAnalyzer extends 
BaseSemanticAnalyzer {
     return nodeOutputs;
   }
 
-  protected final Map<ASTNode, String> translateFieldDesc(ASTNode node) {
+  public static final Map<ASTNode, String> translateFieldDesc(ASTNode node, 
HiveConf conf) {
     Map<ASTNode, String> map = new HashMap<>();
     if (node.getType() == HiveParser.DOT) {
       for (Node child : node.getChildren()) {
-        map.putAll(translateFieldDesc((ASTNode) child));
+        map.putAll(translateFieldDesc((ASTNode) child, conf));
       }
     } else if (node.getType() == HiveParser.Identifier) {
       map.put(node, HiveUtils.unparseIdentifier(node.getText(), conf));
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java
new file mode 100644
index 00000000000..24421489e70
--- /dev/null
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java
@@ -0,0 +1,265 @@
+/*
+ * 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.parse.relnodegen;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeField;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.apache.hadoop.hive.ql.exec.ColumnInfo;
+import org.apache.hadoop.hive.ql.lib.Node;
+import org.apache.hadoop.hive.ql.optimizer.calcite.TraitsUtil;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
+import org.apache.hadoop.hive.ql.optimizer.calcite.translator.TypeConverter;
+import org.apache.hadoop.hive.ql.parse.ASTErrorUtils;
+import org.apache.hadoop.hive.ql.parse.ASTNode;
+import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer;
+import org.apache.hadoop.hive.ql.parse.CalcitePlanner;
+import org.apache.hadoop.hive.ql.parse.HiveParser;
+import org.apache.hadoop.hive.ql.parse.RowResolver;
+import org.apache.hadoop.hive.ql.parse.SemanticAnalyzer;
+import org.apache.hadoop.hive.ql.parse.SemanticException;
+import org.apache.hadoop.hive.ql.parse.UnparseTranslator;
+import org.apache.hadoop.hive.ql.parse.type.FunctionHelper;
+import org.apache.hadoop.hive.ql.parse.type.TypeCheckCtx;
+import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * LateralViewPlan is a helper class holding the objects needed for generating 
a Calcite
+ * plan from an ASTNode. The object is to be generated when a LATERAL_VIEW 
token is detected.
+ * From the ASTNode and relevant input node information, the following objects 
are created:
+ * * A HiveTableFunctionScan RelNode
+ * * A RowResolver containing the row resolving information output from the 
RelNode
+ * * The table alias for the table generated by the UDTF and Lateral View
+ */
+public class LateralViewPlan {
+  protected static final Logger LOG = 
LoggerFactory.getLogger(LateralViewPlan.class.getName());
+
+  // Only acceptable token types under the TOK_LATERAL_VIEW token.
+  public static final ImmutableSet<Integer> TABLE_ALIAS_TOKEN_TYPES =
+      ImmutableSet.of(HiveParser.TOK_SUBQUERY, HiveParser.TOK_TABREF, 
HiveParser.TOK_PTBLFUNCTION);
+
+  // The RelNode created for this lateral view
+  public final RelNode lateralViewRel;
+
+  // The output RowResolver created for this lateral view.
+  public final RowResolver outputRR;
+
+  // The alias provided for the lateral table in the query
+  public final String lateralTableAlias;
+
+  private final RelOptCluster cluster;
+  private final UnparseTranslator unparseTranslator;
+  private final HiveConf conf;
+  private final FunctionHelper functionHelper;
+
+  public LateralViewPlan(ASTNode lateralView, RelOptCluster cluster, RelNode 
inputRel,
+      RowResolver inputRR, UnparseTranslator unparseTranslator,
+      HiveConf conf, FunctionHelper functionHelper
+      ) throws SemanticException {
+    // initialize global variables containing helper information
+    this.cluster = cluster;
+    this.unparseTranslator = unparseTranslator;
+    this.conf = conf;
+    this.functionHelper = functionHelper;
+
+    // AST should have form of LATERAL_VIEW -> SELECT -> SELEXPR -> FUNCTION 
-> function info tree
+    ASTNode selExprAST = (ASTNode) lateralView.getChild(0).getChild(0);
+    ASTNode functionAST = (ASTNode) selExprAST.getChild(0);
+
+    this.lateralTableAlias = getTableAliasFromASTNode(selExprAST);
+
+    // The RexCall for the udtf function (e.g. inline)
+    RexCall udtfCall = getUDTFFunction(functionAST, inputRR);
+
+    // Column aliases provided by the query.
+    List<String> columnAliases = getColumnAliasesFromASTNode(selExprAST, 
udtfCall);
+
+    this.outputRR = getOutputRR(inputRR, udtfCall, columnAliases, 
this.lateralTableAlias);
+
+    RelDataType retType = getRetType(cluster, inputRel, udtfCall, 
columnAliases);
+
+    this.lateralViewRel = HiveTableFunctionScan.create(cluster,
+        TraitsUtil.getDefaultTraitSet(cluster), ImmutableList.of(inputRel), 
udtfCall,
+        null, retType, null);
+  }
+
+  public static void validateLateralView(ASTNode lateralView) throws 
SemanticException {
+    if (lateralView.getChildCount() != 2) {
+      throw new SemanticException("Token Lateral View contains " + 
lateralView.getChildCount() +
+          " children.");
+    }
+    ASTNode next = (ASTNode) lateralView.getChild(1);
+    if (!TABLE_ALIAS_TOKEN_TYPES.contains(next.getToken().getType()) &&
+          HiveParser.TOK_LATERAL_VIEW != next.getToken().getType()) {
+        throw new SemanticException(ASTErrorUtils.getMsg(
+            ErrorMsg.LATERAL_VIEW_INVALID_CHILD.getMsg(), lateralView));
+    }
+  }
+
+  private RexCall getUDTFFunction(ASTNode functionAST, RowResolver inputRR)
+      throws SemanticException {
+
+    String functionName = functionAST.getChild(0).getText().toLowerCase();
+
+    // create the RexNode operands for the UDTF RexCall
+    List<RexNode> operandsForUDTF = getOperandsForUDTF(functionAST, inputRR);
+
+    return this.functionHelper.getUDTFFunction(functionName, operandsForUDTF);
+  }
+
+  private String getTableAliasFromASTNode(ASTNode selExprClause) throws 
SemanticException {
+    // loop through the AST and find the TOK_TABALIAS object
+    for (Node obj : selExprClause.getChildren()) {
+      ASTNode child = (ASTNode) obj;
+      if (child.getToken().getType() == HiveParser.TOK_TABALIAS) {
+        return 
BaseSemanticAnalyzer.unescapeIdentifier(child.getChild(0).getText().toLowerCase());
+      }
+    }
+
+    // Parser enforces that table alias is added, but check again
+    throw new SemanticException("Alias should be specified LVJ");
+  }
+
+  private List<String> getColumnAliasesFromASTNode(ASTNode selExprClause,
+      RexCall udtfCall) throws SemanticException {
+    Set<String> uniqueNames = new HashSet<>();
+    List<String> colAliases = new ArrayList<>();
+    for (Node obj : selExprClause.getChildren()) {
+      ASTNode child = (ASTNode) obj;
+      // Skip the token values.  The rest should be the identifier column 
aliases
+      if (child.getToken().getType() == HiveParser.TOK_TABALIAS ||
+          child.getToken().getType() == HiveParser.TOK_FUNCTION) {
+        continue;
+      }
+      String colAlias = 
BaseSemanticAnalyzer.unescapeIdentifier(child.getText().toLowerCase());
+      if (uniqueNames.contains(colAlias)) {
+        // Column aliases defined by query for lateral view output are 
duplicated
+        throw new 
SemanticException(ErrorMsg.COLUMN_ALIAS_ALREADY_EXISTS.getMsg(colAlias));
+      }
+      uniqueNames.add(colAlias);
+      colAliases.add(colAlias);
+    }
+
+    // if no column aliases were provided, just retrieve them from the return 
type
+    // of the udtf RexCall
+    if (colAliases.isEmpty()) {
+      colAliases.addAll(
+          Lists.transform(udtfCall.getType().getFieldList(), 
RelDataTypeField::getName));
+    }
+
+    // Verify that there is an alias for all the columns returned by the udtf 
call.
+    int udtfFieldCount = udtfCall.getType().getFieldCount();
+    if (colAliases.size() != udtfFieldCount) {
+      // Number of columns in the aliases does not match with number of columns
+      // generated by the lateral view
+      throw new SemanticException(ErrorMsg.UDTF_ALIAS_MISMATCH.getMsg(
+          "expected " + udtfFieldCount + " aliases but got " + 
colAliases.size()));
+    }
+
+    return colAliases;
+  }
+
+  private List<RexNode> getOperandsForUDTF(ASTNode functionCall,
+      RowResolver inputRR) throws SemanticException {
+    List<RexNode> operands = new ArrayList<>();
+    TypeCheckCtx tcCtx = new TypeCheckCtx(inputRR, 
this.cluster.getRexBuilder(), false, false);
+    tcCtx.setUnparseTranslator(this.unparseTranslator);
+    // Start at 1 because value 0 is the function name.  Use the 
CalcitePlanner.genRexNode
+    // to retrieve the RexNode for all the function parameters.
+    for (int i = 1; i < functionCall.getChildren().size(); ++i) {
+      ASTNode functionParam = (ASTNode) functionCall.getChild(i);
+      operands.add(CalcitePlanner.genRexNode(functionParam, inputRR, tcCtx, 
this.conf));
+    }
+    return operands;
+  }
+
+  private RowResolver getOutputRR(RowResolver inputRR, RexCall udtfCall,
+      List<String> columnAliases, String lateralTableAlias) throws 
SemanticException {
+
+    RowResolver localOutputRR = new RowResolver();
+
+    // After calling RowResolver, outputRR will be mutated to contain the row 
resolver
+    // fields
+    if (!RowResolver.add(localOutputRR, inputRR)) {
+      LOG.warn("Duplicates detected when adding columns to RR: see previous 
message");
+    }
+
+    // The RexNode return value for a udtf is always a struct.
+    TypeInfo typeInfo = TypeConverter.convert(udtfCall.getType());
+    Preconditions.checkState(typeInfo instanceof StructTypeInfo);
+
+    StructTypeInfo typeInfos = (StructTypeInfo) typeInfo;
+    // Match up the column alias with the return value of the udtf and
+    // place in the outputRR
+    for (int i = 0, j = 0; i < columnAliases.size(); i++) {
+      String internalColName;
+      do {
+        internalColName = SemanticAnalyzer.getColumnInternalName(j++);
+      } while (localOutputRR.getPosition(internalColName) != -1);
+      localOutputRR.put(lateralTableAlias, columnAliases.get(i),
+          new ColumnInfo(internalColName,  
typeInfos.getAllStructFieldTypeInfos().get(i),
+              lateralTableAlias, false));
+    }
+    return localOutputRR;
+  }
+
+  /**
+   * get the return type for the lateral view. The return type will be a 
structure
+   * where the first values are from the input RelNode. Then the output values 
from the
+   * udtf will be added into the structure for the return type.
+   */
+  private RelDataType getRetType(RelOptCluster cluster, RelNode inputRel,
+      RexNode udtfCall, List<String> columnAliases) {
+
+    // initialize allDataTypes and allDataTypeNames from the fields in the 
inputRel
+    List<RelDataType> allDataTypes = new ArrayList<>(
+        Lists.transform(inputRel.getRowType().getFieldList(), 
RelDataTypeField::getType));
+    List<String> allDataTypeNames = new ArrayList<>(
+        Lists.transform(inputRel.getRowType().getFieldList(), 
RelDataTypeField::getName));
+
+    RelDataType retType = udtfCall.getType();
+
+    Preconditions.checkState(retType.isStruct());
+
+    // Add the type names and values from the udtf into the lists that will 
make up the
+    // return type.
+    allDataTypes.addAll(Lists.transform(retType.getFieldList(), 
RelDataTypeField::getType));
+    allDataTypeNames.addAll(columnAliases);
+
+    return cluster.getTypeFactory().createStructType(allDataTypes, 
allDataTypeNames);
+  }
+}
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/parse/type/FunctionHelper.java 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/type/FunctionHelper.java
index c74c2aad93b..49fa83b8505 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/type/FunctionHelper.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/type/FunctionHelper.java
@@ -22,6 +22,7 @@ import com.google.common.collect.ImmutableList;
 import java.util.Collections;
 import java.util.List;
 import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexNode;
 import org.apache.hadoop.hive.ql.exec.FunctionInfo;
 import org.apache.hadoop.hive.ql.parse.SemanticException;
@@ -78,6 +79,12 @@ public interface FunctionHelper {
       String aggregateName, List<RexNode> aggregateParameters)
       throws SemanticException;
 
+  /**
+   * Returns RexCall for UDTF from the appropriate function registry based on 
given parameters
+   */
+  RexCall getUDTFFunction(String functionName, List<RexNode> operands)
+      throws SemanticException;
+
   /**
    * Folds expression according to function semantics.
    */
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/parse/type/HiveFunctionHelper.java 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/type/HiveFunctionHelper.java
index 69327390bfe..7ebbb95efb9 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/type/HiveFunctionHelper.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/type/HiveFunctionHelper.java
@@ -17,7 +17,9 @@
  */
 package org.apache.hadoop.hive.ql.parse.type;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
@@ -70,6 +72,7 @@ import 
org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual;
 import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqualNS;
 import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNotEqualNS;
 import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
 import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
@@ -448,6 +451,23 @@ public class HiveFunctionHelper implements FunctionHelper {
         new AggregateInfo(aggregateParameters, returnType, aggregateName, 
isDistinct) : null;
   }
 
+  public RexCall getUDTFFunction(String functionName, List<RexNode> operands)
+      throws SemanticException {
+    // Extract the argument types for the operands into a list
+    List<RelDataType> operandTypes = Lists.transform(operands, 
RexNode::getType);
+
+    FunctionInfo functionInfo = FunctionRegistry.getFunctionInfo(functionName);
+    GenericUDTF genericUDTF = functionInfo.getGenericUDTF();
+    Preconditions.checkNotNull(genericUDTF, "Generic UDTF not found: " + 
functionName);
+
+    RelDataType udtfRetType = getReturnType(functionInfo, operands);
+
+    SqlOperator calciteOp = 
SqlFunctionConverter.getCalciteOperator(functionName, genericUDTF,
+        ImmutableList.copyOf(operandTypes), udtfRetType);
+
+    return (RexCall) rexBuilder.makeCall(calciteOp, operands);
+  }
+
   private ObjectInspector createObjectInspector(RexNode expr) {
     ObjectInspector oi = createConstantObjectInspector(expr);
     if (oi != null) {
diff --git 
a/ql/src/test/org/apache/hadoop/hive/ql/parse/type/TestHiveFunctionHelper.java 
b/ql/src/test/org/apache/hadoop/hive/ql/parse/type/TestHiveFunctionHelper.java
new file mode 100644
index 00000000000..2e7acf6f002
--- /dev/null
+++ 
b/ql/src/test/org/apache/hadoop/hive/ql/parse/type/TestHiveFunctionHelper.java
@@ -0,0 +1,65 @@
+/*
+ * 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.parse.type;
+
+import static org.junit.Assert.assertEquals;
+
+import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
+import org.apache.hadoop.hive.ql.parse.SemanticException;
+
+import com.google.common.collect.Lists;
+
+import java.util.List;
+
+
+import org.junit.Test;
+
+public class TestHiveFunctionHelper {
+
+  @Test
+  public void testGetUDTFFunction() throws SemanticException {
+    RelDataTypeFactory typeFactory = new JavaTypeFactoryImpl();
+    RexBuilder rexBuilder = new RexBuilder(typeFactory);
+    List<RexNode> operands =
+        Lists.newArrayList(rexBuilder.makeLiteral("hello"), 
rexBuilder.makeLiteral("world"));
+    List<RexNode> arrayNode =
+        
Lists.newArrayList(rexBuilder.makeCall(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR,
 operands));
+
+    FunctionHelper functionHelper = new HiveFunctionHelper(rexBuilder);
+    RexCall explodeNode = (RexCall) functionHelper.getUDTFFunction("explode", 
arrayNode);
+
+    assertEquals(explodeNode.toString(), "explode(ARRAY('hello', 'world'))");
+    assertEquals(explodeNode.getType().toString(), "RecordType(CHAR(5) col)");
+  }
+
+  @Test(expected = Exception.class)
+  public void testGetUDTFFunctionThrowingException() throws SemanticException {
+    RelDataTypeFactory typeFactory = new JavaTypeFactoryImpl();
+    RexBuilder rexBuilder = new RexBuilder(typeFactory);
+    List<RexNode> operands = 
Lists.newArrayList(rexBuilder.makeLiteral("hello"));
+
+    FunctionHelper functionHelper = new HiveFunctionHelper(rexBuilder);
+    // 'upper' is not a udtf so should throw exception
+    functionHelper.getUDTFFunction("upper", operands);
+  }
+}
diff --git a/ql/src/test/queries/clientpositive/tablevalues.q 
b/ql/src/test/queries/clientpositive/tablevalues.q
index 6d1f96ef451..39f77c3e5fa 100644
--- a/ql/src/test/queries/clientpositive/tablevalues.q
+++ b/ql/src/test/queries/clientpositive/tablevalues.q
@@ -25,6 +25,13 @@ FROM
   LATERAL VIEW
   INLINE(array(struct('A', 10, t.key),struct('B', 20, t.key))) tf AS col1, 
col2, col3;
 
+EXPLAIN CBO
+SELECT tf.col1, tf.col2, tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t
+  LATERAL VIEW
+  INLINE(array(struct('A', 10, t.key),struct('B', 20, t.key))) tf AS col1, 
col2, col3;
+
 SELECT tf.col1, tf.col2, tf.col3
 FROM
   (SELECT key, value FROM mytbl_n1) t
@@ -34,6 +41,9 @@ FROM
 EXPLAIN
 SELECT INLINE(array(struct('A', 10, 30),struct('B', 20, 30))) AS (col1, col2, 
col3);
 
+EXPLAIN CBO
+SELECT INLINE(array(struct('A', 10, 30),struct('B', 20, 30))) AS (col1, col2, 
col3);
+
 SELECT INLINE(array(struct('A', 10, 30),struct('B', 20, 30))) AS (col1, col2, 
col3);
 
 EXPLAIN
@@ -90,6 +100,12 @@ FROM
   (SELECT key, value FROM mytbl_n1) t,
   LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3);
 
+EXPLAIN CBO
+SELECT tf.col1, tf.col2, tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3);
+
 SELECT tf.col1, tf.col2, tf.col3
 FROM
   (SELECT key, value FROM mytbl_n1) t,
@@ -101,6 +117,12 @@ FROM
   (SELECT key, value FROM mytbl_n1) t,
   LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf;
 
+EXPLAIN CBO
+SELECT t.key
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf;
+
 SELECT t.key
 FROM
   (SELECT key, value FROM mytbl_n1) t,
@@ -112,6 +134,12 @@ FROM
   (SELECT key, value FROM mytbl_n1) t,
   LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3);
 
+EXPLAIN CBO
+SELECT tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3);
+
 SELECT tf.col3
 FROM
   (SELECT key, value FROM mytbl_n1) t,
@@ -123,6 +151,12 @@ FROM
   (SELECT row_number() over (order by key desc) as r FROM mytbl_n1) t,
   LATERAL TABLE(VALUES('A', 10, t.r),('B', 20, t.r)) AS tf(col1, col2, col3);
 
+EXPLAIN CBO
+SELECT tf.col3
+FROM
+  (SELECT row_number() over (order by key desc) as r FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.r),('B', 20, t.r)) AS tf(col1, col2, col3);
+
 SELECT tf.col3
 FROM
   (SELECT row_number() over (order by key desc) as r FROM mytbl_n1) t,
diff --git a/ql/src/test/results/clientpositive/llap/tablevalues.q.out 
b/ql/src/test/results/clientpositive/llap/tablevalues.q.out
index 3aa1a3639c3..de228e14bc0 100644
--- a/ql/src/test/results/clientpositive/llap/tablevalues.q.out
+++ b/ql/src/test/results/clientpositive/llap/tablevalues.q.out
@@ -184,6 +184,30 @@ STAGE PLANS:
                 outputColumnNames: _col0, _col1, _col2
                 ListSink
 
+PREHOOK: query: EXPLAIN CBO
+SELECT tf.col1, tf.col2, tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t
+  LATERAL VIEW
+  INLINE(array(struct('A', 10, t.key),struct('B', 20, t.key))) tf AS col1, 
col2, col3
+PREHOOK: type: QUERY
+PREHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO
+SELECT tf.col1, tf.col2, tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t
+  LATERAL VIEW
+  INLINE(array(struct('A', 10, t.key),struct('B', 20, t.key))) tf AS col1, 
col2, col3
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(col1=[$2], col2=[$3], col3=[$4])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, $1, 
_UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, $1, 
_UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], 
rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, 
VARCHAR(2147483647) col1, INTEGER col2, VARCHAR(2147483647) col3)])
+    HiveProject(key=[$0], value=[$1])
+      HiveTableScan(table=[[default, mytbl_n1]], table:alias=[mytbl_n1])
+
 PREHOOK: query: SELECT tf.col1, tf.col2, tf.col3
 FROM
   (SELECT key, value FROM mytbl_n1) t
@@ -241,6 +265,20 @@ STAGE PLANS:
                 outputColumnNames: _col0, _col1, _col2
                 ListSink
 
+PREHOOK: query: EXPLAIN CBO
+SELECT INLINE(array(struct('A', 10, 30),struct('B', 20, 30))) AS (col1, col2, 
col3)
+PREHOOK: type: QUERY
+PREHOOK: Input: _dummy_database@_dummy_table
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO
+SELECT INLINE(array(struct('A', 10, 30),struct('B', 20, 30))) AS (col1, col2, 
col3)
+POSTHOOK: type: QUERY
+POSTHOOK: Input: _dummy_database@_dummy_table
+#### A masked pattern was here ####
+CBO PLAN:
+HiveTableFunctionScan(invocation=[inline(ARRAY(ROW(_UTF-16LE'A':VARCHAR(2147483647)
 CHARACTER SET "UTF-16LE", 10, 30), ROW(_UTF-16LE'B':VARCHAR(2147483647) 
CHARACTER SET "UTF-16LE", 20, 30)))], rowType=[RecordType(VARCHAR(2147483647) 
col1, INTEGER col2, INTEGER col3)])
+  HiveTableScan(table=[[_dummy_database, _dummy_table]], 
table:alias=[_dummy_table])
+
 PREHOOK: query: SELECT INLINE(array(struct('A', 10, 30),struct('B', 20, 30))) 
AS (col1, col2, col3)
 PREHOOK: type: QUERY
 PREHOOK: Input: _dummy_database@_dummy_table
@@ -686,6 +724,28 @@ STAGE PLANS:
                 outputColumnNames: _col0, _col1, _col2
                 ListSink
 
+PREHOOK: query: EXPLAIN CBO
+SELECT tf.col1, tf.col2, tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3)
+PREHOOK: type: QUERY
+PREHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO
+SELECT tf.col1, tf.col2, tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3)
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(col1=[$2], col2=[$3], col3=[$4])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, $1, 
_UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, $1, 
_UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], 
rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, 
VARCHAR(2147483647) col1, INTEGER col2, VARCHAR(2147483647) col3)])
+    HiveProject(key=[$0], value=[$1])
+      HiveTableScan(table=[[default, mytbl_n1]], table:alias=[mytbl_n1])
+
 PREHOOK: query: SELECT tf.col1, tf.col2, tf.col3
 FROM
   (SELECT key, value FROM mytbl_n1) t,
@@ -746,6 +806,28 @@ STAGE PLANS:
                 outputColumnNames: _col0
                 ListSink
 
+PREHOOK: query: EXPLAIN CBO
+SELECT t.key
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf
+PREHOOK: type: QUERY
+PREHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO
+SELECT t.key
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(key=[$0])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, $1, 
_UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, $1, 
_UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], 
rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, 
VARCHAR(2147483647) col1, INTEGER col2, VARCHAR(2147483647) col3)])
+    HiveProject(key=[$0], value=[$1])
+      HiveTableScan(table=[[default, mytbl_n1]], table:alias=[mytbl_n1])
+
 PREHOOK: query: SELECT t.key
 FROM
   (SELECT key, value FROM mytbl_n1) t,
@@ -806,6 +888,28 @@ STAGE PLANS:
                 outputColumnNames: _col0
                 ListSink
 
+PREHOOK: query: EXPLAIN CBO
+SELECT tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3)
+PREHOOK: type: QUERY
+PREHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO
+SELECT tf.col3
+FROM
+  (SELECT key, value FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.key),('B', 20, t.key)) AS tf(col1, col2, 
col3)
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(col3=[$4])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, $1, 
_UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, $1, 
_UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], 
rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, 
VARCHAR(2147483647) col1, INTEGER col2, VARCHAR(2147483647) col3)])
+    HiveProject(key=[$0], value=[$1])
+      HiveTableScan(table=[[default, mytbl_n1]], table:alias=[mytbl_n1])
+
 PREHOOK: query: SELECT tf.col3
 FROM
   (SELECT key, value FROM mytbl_n1) t,
@@ -923,6 +1027,28 @@ STAGE PLANS:
       Processor Tree:
         ListSink
 
+PREHOOK: query: EXPLAIN CBO
+SELECT tf.col3
+FROM
+  (SELECT row_number() over (order by key desc) as r FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.r),('B', 20, t.r)) AS tf(col1, col2, col3)
+PREHOOK: type: QUERY
+PREHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO
+SELECT tf.col3
+FROM
+  (SELECT row_number() over (order by key desc) as r FROM mytbl_n1) t,
+  LATERAL TABLE(VALUES('A', 10, t.r),('B', 20, t.r)) AS tf(col1, col2, col3)
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@mytbl_n1
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(col3=[$3])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, 
_UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, 
_UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], 
rowType=[RecordType(INTEGER r, VARCHAR(2147483647) col1, INTEGER col2, INTEGER 
col3)])
+    HiveProject(r=[row_number() OVER (PARTITION BY 0 ORDER BY $0 DESC NULLS 
FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)])
+      HiveTableScan(table=[[default, mytbl_n1]], table:alias=[mytbl_n1])
+
 PREHOOK: query: SELECT tf.col3
 FROM
   (SELECT row_number() over (order by key desc) as r FROM mytbl_n1) t,

Reply via email to