You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@hive.apache.org by "scarlin-cloudera (via GitHub)" <gi...@apache.org> on 2023/06/20 20:47:09 UTC

[GitHub] [hive] scarlin-cloudera opened a new pull request, #4442: HIVE-27399: Add support for lateral views with CBO

scarlin-cloudera opened a new pull request, #4442:
URL: https://github.com/apache/hive/pull/4442

   This commit adds implementation for lateral views using CBO. Previously, the CBO step was skipped.
   
   Among the changes that needed to be done:
   
   One highlight is that the HiveTableFunctionScan needs to know if it is a "lateral view". A non-lateral view HiveTableFunctionScan consists of just the udtf which was supported before this commit. In this case, the generated row type for the HiveTableFunctionScan consists only of the UDTF fields.  In "lateral view" mode, the HiveTableFunctionScan does a join with the base table so the row type contains the base input RelNode table fields followed by the UDTF fields.
   
   The ASTConverter needed to be changed to handle conversion of the lateral view back into an AST that contains the LATERAL_VIEW node. The non-"lateral view" HiveTableFunctionScan still generates an AST without the LATERAL_VIEW node which is more optimal. This commit also allows for the optimization of lateral views to create an AST without the LATERAL_VIEW node.  This can be done when the RelNode above the HiveTableFunctionScan does not need any base table fields, only the UDTF fields.
   
   The OpProcFactory code needed to be changed in order to continue to allow a filter optimization. There is pushdown (ppd) logic that was being hit when there was no CBO for lateral views. CBO runs a different path for the ppd logic which is in the OpProcFactory. The lateral view contains 2 node paths that are joined together. The filter can be pushed down the path that contains the base table, but not the path that contains the UDTF. By adding this logic, it prevents a performance regression.
   
   A new rule was also needed for CBO. There is a HiveFilter-HiveTableFunctionScan transpose rule. These RelNodes can be transposed when there is at least one AND condition that can be pushed through the HiveTableFunctionScan. A condition can be pushed through if there are no inputRefs that rely on the output of the UDTF function. Also, we do not want to pass through the UDTF "inline" function which has a dummy table underneath.
   
   There are various q.out changes that are in this commit because of this push. The first is that we want to make sure the CBO tests are run, so many "EXPLAIN CBO" queries were added to the "q" files.
   
   Other changes to the q.out files include:
   
   As mentioned above, there are various places where the Lateral View Operator is optimized out because the above operator only depends on UDTF fields. This is verified as working since the output of the query did not change, only the plan.
   
   In some places, an additional "Select Operator" was added. This should not have any performance impact.
   
   There should be no changes in the results of any query.
   
   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://cwiki.apache.org/confluence/display/Hive/HowToContribute
     2. Ensure that you have created an issue on the Hive project JIRA: https://issues.apache.org/jira/projects/HIVE/summary
     3. Ensure you have added or run the appropriate tests for your PR: 
     4. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP]HIVE-XXXXX:  Your PR title ...'.
     5. Be sure to keep the PR description updated to reflect all changes.
     6. Please write your PR title to summarize what this PR proposes.
     7. If possible, provide a concise example to reproduce the issue for a faster review.
   
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description, screenshot and/or a reproducable example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Hive versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   
   ### Is the change a dependency upgrade?
   <!--
   If yes, please attach a file with output from mvn dependency:tree to validate a complete upgrade of dependency.
   If no, write 'No'.
   -->
   
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   -->
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1286159251


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,77 @@ 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)) {

Review Comment:
   I don't think this is possible to do with a CBO rule.  Let me try to explain why I think this will be a problem:
   
   This is really a physical optimization, not a logical optimization.  The logical representation is the same so we can't make a rule.  
   
   You can see in some qtests that there are Lateral View Operators created.  This is needed when an explicit join is being made from the base table and the "exploded" array fields.  Each array element produces a separate row.  If a column is needed from the base table, that's when a join is needed.
   
   The optimization that is being done here is to rid ourselves of this join operation.  If the only columns selected out are from the array and none from the base table, no join is needed.  We can therefore just use the UDTF Operator rather than a Lateral Join.
   
   This code could potentially be moved where we do physical operations, but I felt this is the easiest place to implement this since the LATERAL VIEW syntax is cleanly mapped with the Lateral view operator and the UDTF operator is used when the AST tree is created without the LATERAL VIEW syntax.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1326818602


##########
ql/src/test/results/clientpositive/llap/udtf_json_tuple.q.out:
##########
@@ -395,24 +398,27 @@ STAGE PLANS:
                           Lateral View Join Operator
                             outputColumnNames: _col6, _col7, _col8, _col9, _col10
                             Statistics: Num rows: 6 Data size: 3233 Basic stats: COMPLETE Column stats: COMPLETE
-                            Select Operator
-                              expressions: _col7 (type: string)
-                              outputColumnNames: _col7
-                              Statistics: Num rows: 6 Data size: 3233 Basic stats: COMPLETE Column stats: COMPLETE
-                              Group By Operator
-                                aggregations: count()
-                                keys: _col7 (type: string)
-                                minReductionHashAggr: 0.8333333
-                                mode: hash
-                                outputColumnNames: _col0, _col1
-                                Statistics: Num rows: 1 Data size: 8 Basic stats: COMPLETE Column stats: COMPLETE
-                                Reduce Output Operator
-                                  key expressions: _col0 (type: string)
-                                  null sort order: z
-                                  sort order: +
-                                  Map-reduce partition columns: _col0 (type: string)
+                            Filter Operator
+                              predicate: _col6 is not null (type: boolean)

Review Comment:
   Didn't push this on the latest, but this problem is fixed with the change made in OpProcFactory



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1340154634


##########
ql/src/java/org/apache/hadoop/hive/ql/ppd/OpProcFactory.java:
##########
@@ -385,6 +385,23 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
 
   }
 
+  public static class LateralViewJoinerPPD extends JoinerPPD implements SemanticNodeProcessor {
+    @Override
+    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
+        Object... nodeOutputs) throws SemanticException {
+      Object o = super.process(nd, stack, procCtx, nodeOutputs);
+      Operator<?> operator = (Operator<?>) nd;
+      OpWalkerInfo owi = (OpWalkerInfo) procCtx;
+      if (HiveConf.getBoolVar(owi.getParseContext().getConf(),
+          HiveConf.ConfVars.HIVEPPDREMOVEDUPLICATEFILTERS)) {
+        // remove all the candidate filter operators
+        // when we get to the TS

Review Comment:
   I changed the comment for this.
   
   At this point, the filter is both above and below, which is what you saw in the regression in the last push.
   
   If we don't remove the candidate filter here, there is a "clear()" that is called before it hits the TS and the original filter does not get removed. 



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1340003549


##########
ql/src/test/results/clientpositive/llap/lateral_view_cbo.q.out:
##########
@@ -1,34 +1,113 @@
-PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM src 
+PREHOOK: query: CREATE TABLE simple_table (col string, array_col array<string>)
+PREHOOK: type: CREATETABLE
+PREHOOK: Output: database:default
+PREHOOK: Output: default@simple_table
+POSTHOOK: query: CREATE TABLE simple_table (col string, array_col array<string>)
+POSTHOOK: type: CREATETABLE
+POSTHOOK: Output: database:default
+POSTHOOK: Output: default@simple_table
+PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 PREHOOK: type: QUERY
-PREHOOK: Input: default@src
+PREHOOK: Input: default@simple_table
 #### A masked pattern was here ####
-POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM src 
+POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 POSTHOOK: type: QUERY
-POSTHOOK: Input: default@src
+POSTHOOK: Input: default@simple_table
 #### A masked pattern was here ####
 CBO PLAN:
 HiveProject(mycol=[$6])
-  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
-    HiveTableScan(table=[[default, src]], table:alias=[src])
+  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
+    HiveTableScan(table=[[default, simple_table]], table:alias=[simple_table])
 
-PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM src
+PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 LATERAL VIEW explode(array(1,2,3)) myTable2 AS myCol2
 PREHOOK: type: QUERY
-PREHOOK: Input: default@src
+PREHOOK: Input: default@simple_table
 #### A masked pattern was here ####
-POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM src
+POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 LATERAL VIEW explode(array(1,2,3)) myTable2 AS myCol2
 POSTHOOK: type: QUERY
-POSTHOOK: Input: default@src
+POSTHOOK: Input: default@simple_table
 #### A masked pattern was here ####
 CBO PLAN:
 HiveProject(mycol=[$6], mycol2=[$7])
-  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5, $6)], rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol, INTEGER mytable2.mycol2)])
-    HiveProject(key=[$0], value=[$1], BLOCK__OFFSET__INSIDE__FILE=[$2], INPUT__FILE__NAME=[$3], ROW__ID=[$4], ROW__IS__DELETED=[$5], mytable.mycol=[$6])
-      HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
-        HiveTableScan(table=[[default, src]], table:alias=[src])
+  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5, $6)], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol, INTEGER mytable2.mycol2)])
+    HiveProject(col=[$0], array_col=[$1], BLOCK__OFFSET__INSIDE__FILE=[$2], INPUT__FILE__NAME=[$3], ROW__ID=[$4], ROW__IS__DELETED=[$5], mytable.mycol=[$6])
+      HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
+        HiveTableScan(table=[[default, simple_table]], table:alias=[simple_table])
+
+PREHOOK: query: EXPLAIN CBO SELECT tf.col1, tf.col2, tf.col3
+FROM simple_table
+  LATERAL TABLE(VALUES('A', 10, simple_table.col),('B', 20, simple_table.col)) AS tf(col1, col2, col3)
+PREHOOK: type: QUERY
+PREHOOK: Input: default@simple_table
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO SELECT tf.col1, tf.col2, tf.col3
+FROM simple_table
+  LATERAL TABLE(VALUES('A', 10, simple_table.col),('B', 20, simple_table.col)) AS tf(col1, col2, col3)
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@simple_table
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(col1=[$6], col2=[$7], col3=[$8])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, $1, $2, $3, $4, $5, _UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, $1, $2, $3, $4, $5, _UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, VARCHAR(2147483647) tf.col1, INTEGER tf.col2, VARCHAR(2147483647) tf.col3)])

Review Comment:
   I'm not sure this is a regression.  I looked in tablevalues.q.out previous to this checkin and this is the way it was previously done.
   
   We can look into this optimization later.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320422129


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -383,8 +386,16 @@ private ASTNode convert() throws CalciteSemanticException {
       ASTBuilder sel = ASTBuilder.construct(HiveParser.TOK_SELEXPR, "TOK_SELEXPR");
       ASTNode function = buildUDTFAST(call.getOperator().getName(), children);
       sel.add(function);
-      for (String alias : udtf.getRowType().getFieldNames()) {
-        sel.add(HiveParser.Identifier, alias);
+
+      // When we are treating a UDTF as a 'select', it is not a lateral view.
+      // In this case, it means that only the fields from the UDTF are selected
+      // out of the RelNode and placed into the SELEXPR. So we want to ignore
+      // any field in the inputRef mapping.
+      List<String> fields = udtf.getRowType().getFieldNames();
+      for (int i = 0; i < udtf.getRowType().getFieldCount(); ++i) {
+        if (!udtf.containsInputRefMapping(i)) {

Review Comment:
   Removed



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,18 @@ private QueryBlockInfo convertSource(RelNode r) throws CalciteSemanticException
         ast = ASTBuilder.subQuery(left, sqAlias);
         s = new Schema((Union) r, sqAlias);
       }
+    } else if (r instanceof HiveTableFunctionScan &&

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244982472


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveLVTableFunctionScan.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.reloperators;
+
+import java.lang.reflect.Type;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.TableFunctionScan;
+import org.apache.calcite.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException;
+
+/**
+  *  HiveLVTableFunctionScan (LV stands for lateral views).
+  * This RelNode is created through a lateral view. This class differs from its
+  * parent's class in that the fields in the child RelNode are present in the output
+  * RelDataType. The output of the UDTF is joined to these base table types on each
+  * row.
+  */
+public class HiveLVTableFunctionScan extends HiveTableFunctionScan {

Review Comment:
   ```
   The output of the UDTF is joined to these base table types on each row.
   ```
   According to the current description we are introducing a new operator that according to the description could be expressed by existing simpler operators:
   ```
   Join
     TableFunctionScan
     TableScan
   ```
   Why do we need this new compound operator and we didn't opt for the simpler primitives?
   
   Every new RelNode needs to be handled in various places (rules, factories, builders, transformers, etc.,) so its better if we can rely on existing ones.
   
   If we collapse/hide the join inside the table function scan then for sure join specific rules will not trigger. Aren't we losing potential optimizations by doing this?
   
   Ideally the representation that we pick for supporting lateral views in CBO should allow us to perform more powerful optimizations at the CBO level that are more powerful than those (if any) applied at the physical plan.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1612310242

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [19 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] kasakrisz commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "kasakrisz (via GitHub)" <gi...@apache.org>.
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1612493368

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [15 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1286168676


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

Review Comment:
   I found this code kinda weird as I went through it.  
   
   My observation, and perhaps it is wrong, is that this module makes up for some defects in the ASTConverter.  The ASTConverter requires that the level underneath it be a Project or HiveTableFunctionScan.  If it isn't, the caller "introduces" a Project so that the ASTConverter can handle it properly.
   
   I potentially misunderstood this code, but while I was testing, I hit this issue in the ASTConverter and this seems to follow the trend of already existing code.  I do think ASTConverter should be rewritten, but if we went that far, we should perhaps go to the physical operator directly rather than convert to AST and then convert to the physical operator.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1668706912

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [17 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306301646


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java:
##########
@@ -256,10 +257,20 @@ 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

Review Comment:
   It didn't work when I did it this way.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1670121934

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [17 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1288646268


##########
ql/src/test/queries/clientpositive/lateral_view.q:
##########
@@ -10,6 +10,11 @@ EXPLAIN SELECT myTable.* FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS
 EXPLAIN SELECT myTable.myCol, myTable2.myCol2 FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol LATERAL VIEW explode(array('a', 'b', 'c')) myTable2 AS myCol2 LIMIT 9;
 EXPLAIN SELECT myTable2.* FROM src LATERAL VIEW explode(array(array(1,2,3))) myTable AS myCol LATERAL VIEW explode(myTable.myCol) myTable2 AS myCol2 LIMIT 3;
 
+EXPLAIN CBO SELECT * FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol SORT BY key ASC, myCol ASC LIMIT 1;

Review Comment:
   It is a good idea to verify the `EXPLAIN CBO` plan in the presence of lateral views. I am wondering if it would be better to identify a few representative queries and then put the EXPLAIN CBO statements in a new .q file (e.g., `cbo_lateral_views.q`) going from the simpler to the more complicate queries. These would make testing more explicit and it would also reduce the changes in existing .q.out files leading to fewer merge conflicts when backporting. WDYT?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +125,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use empty listfor columnMappings. The return row type of the RelNode now comprises of
+    // all the fields within the UDTF, so there is no mapping from the output fields
+    // directly to the input fields anymore.
     final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
         tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
-        tfs.getColumnMappings());
+        new HashSet<>());

Review Comment:
   nit: `Collections.emptySet()` is a more efficient choice unless we want to modify the set.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,77 @@ 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)) {

Review Comment:
   Is this optimization something that we could defer to a follow-up ticket so that we converge and merge this PR faster ? That would also make the diff and git history easier to follow.
   
   If we want to push it here then let me share what I was thinking with a concrete SQL example grabbed from existing tests.
   ```sql
   SELECT myCol from tmp_pyang_lv LATERAL VIEW explode(array(1,2,3)) myTab as myCol limit 3
   ```
   The current plan is the following:
   ```
   CBO PLAN:
   HiveSortLimit(fetch=[3])
     HiveProject(mycol=[$5])
       HiveTableFunctionScan(invocation=[explode(ARRAY(1, 2, 3))], rowType=[RecordType(VARCHAR(2147483647) inputs, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytab.mycol)])
         HiveTableScan(table=[[default, tmp_pyang_lv]], table:alias=[tmp_pyang_lv])
   ```
   I was thinking that we could have a CBO optimization that turns the plan above to something like the following:
   ```
   CBO PLAN:
   HiveSortLimit(fetch=[3])
     HiveTableFunctionScan(invocation=[explode(ARRAY(1, 2, 3))], rowType=[RecordType(INTEGER mytab.mycol)])
   ```



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +644,109 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  private ASTNode createASTLateralView(TableFunctionScan tfs, Schema s,
+      QueryBlockInfo tableFunctionSource, String sqAlias) {
+    // 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.
+    //

Review Comment:
   The comment seems misplaced here. Maybe it is also a bit redundant given the javadoc in `canOptimizeOutLateralView` method.



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java:
##########
@@ -114,7 +115,7 @@ public LateralViewPlan(ASTNode lateralView, RelOptCluster cluster, RelNode input
 
     this.lateralViewRel = HiveTableFunctionScan.create(cluster,
         TraitsUtil.getDefaultTraitSet(cluster), ImmutableList.of(inputRel), udtfCall,
-        null, retType, null);
+        null, retType, createColumnMappings(inputRel));

Review Comment:
   I was thinking that there is also a third category:
   3. Columns from the `inputRel` that are transformed based on the UDTF and appear in the result (something that would enable the derived attribute in `RelColumnMapping`).
   
   Anyways I don't fully understand how `RelColumnMapping` is supposed to work so I suppose we can leave with this mapping for the moment.



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

Review Comment:
   Thanks for the explanation. Not fully understand either but now I see the pattern so the changes look reasonable.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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
+ *
+ * This differs from the FilterTableFunctionTransposeRule for a number of reasons:
+ *   - We check if the filter condition is deterministic under Hive rules. We cannot
+ *     push filters that aren't deterministic.
+ *   - We check if the filter only references columns that are not part of the udtf.
+ *     If the input ref in the filter references a column that is generated by the
+ *     udtf, the filter cannot be pushed through.

Review Comment:
   I get the impression that `FilterTableFunctionTransposeRule` also does the same check using column mappings.
   
   I would also suggest to isolate this transformation to a separate patch if that is possible. The reasoning is the same less code to review faster to merge.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306577506


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,77 @@ 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.
+      //
+      // The structure of the AST in this "else if" branch will be:

Review Comment:
   Changed the code a bit.  Not sure if I can write up a test case for this, but there are extensive q tests which cover all the cases.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306577438


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,77 @@ 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)) {

Review Comment:
   I've made some changes for the plan which now includes a lateral function definition.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244459376


##########
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:
   I just removed this.  This is overkill because this condition is guaranteed by the "matches" portion.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244460300


##########
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:
   Not sure if I applied this correctly.  I couldn't use the relBuilder to build the HiveLVTableFunctionScan, so I kept it the same way.
   
   I suppose I could override the "functionScan()" method in HiveRelBuilder?  Didnt' feel great about doing that since we now have both HiveTableFunctionScan and HiveLVTableFunctionScan, but maybe I should?  Thoughts?



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244460449


##########
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:
   Added comment



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306577624


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +644,109 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  private ASTNode createASTLateralView(TableFunctionScan tfs, Schema s,
+      QueryBlockInfo tableFunctionSource, String sqAlias) {
+    // 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.
+    //

Review Comment:
   Code has been changed so canOptimizeLateralView is not needed anymore



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1340150106


##########
ql/src/java/org/apache/hadoop/hive/ql/ppd/OpProcFactory.java:
##########
@@ -385,6 +385,23 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
 
   }
 
+  public static class LateralViewJoinerPPD extends JoinerPPD implements SemanticNodeProcessor {
+    @Override
+    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
+        Object... nodeOutputs) throws SemanticException {
+      Object o = super.process(nd, stack, procCtx, nodeOutputs);
+      Operator<?> operator = (Operator<?>) nd;

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1721355307

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [31 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


Re: [PR] HIVE-27399: Add support for lateral views with CBO [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak closed pull request #4442: HIVE-27399: Add support for lateral views with CBO
URL: https://github.com/apache/hive/pull/4442


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1326810413


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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
+ *
+ * We cannot use Calcite's FilterTableFunctionTransposeRule because that rule
+ * uses LogicalFilter and LogicalTableFunctionScan.  We should remove this
+ * class when CALCITE-5985 is fixed (and remove the CALCITE_5985_FIXED entry

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1326809778


##########
ql/src/test/results/clientpositive/llap/lineage2.q.out:
##########
@@ -710,7 +710,7 @@ PREHOOK: query: select identity, ep1_id from relations
 PREHOOK: type: QUERY
 PREHOOK: Input: default@relations
 #### A masked pattern was here ####
-{"version":"1.0","engine":"tez","database":"default","hash":"436a649a0d9540e8f093f8353d86813a","queryText":"select identity, ep1_id from relations\n  lateral view explode(ep1_ids) nav_rel as ep1_id","edges":[{"sources":[2],"targets":[0],"edgeType":"PROJECTION"},{"sources":[3],"targets":[1],"expression":"nav_rel._col12","edgeType":"PROJECTION"}],"vertices":[{"id":0,"vertexType":"COLUMN","vertexId":"identity"},{"id":1,"vertexType":"COLUMN","vertexId":"ep1_id"},{"id":2,"vertexType":"COLUMN","vertexId":"default.relations.identity"},{"id":3,"vertexType":"COLUMN","vertexId":"default.relations.ep1_ids"}]}

Review Comment:
   I looked at the lineage code, and I don't think this will cause any regressions either.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244464370


##########
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:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244463980


##########
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:
   Put in code to handle the empty case.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1613850703

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [15 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1317011777


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +644,80 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  private ASTNode createASTLateralView(TableFunctionScan tfs, Schema s,

Review Comment:
   If its static let's declare it explicitly.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -383,8 +386,16 @@ private ASTNode convert() throws CalciteSemanticException {
       ASTBuilder sel = ASTBuilder.construct(HiveParser.TOK_SELEXPR, "TOK_SELEXPR");
       ASTNode function = buildUDTFAST(call.getOperator().getName(), children);
       sel.add(function);
-      for (String alias : udtf.getRowType().getFieldNames()) {
-        sel.add(HiveParser.Identifier, alias);
+
+      // When we are treating a UDTF as a 'select', it is not a lateral view.
+      // In this case, it means that only the fields from the UDTF are selected
+      // out of the RelNode and placed into the SELEXPR. So we want to ignore
+      // any field in the inputRef mapping.
+      List<String> fields = udtf.getRowType().getFieldNames();
+      for (int i = 0; i < udtf.getRowType().getFieldCount(); ++i) {
+        if (!udtf.containsInputRefMapping(i)) {

Review Comment:
   With the newly introduced `lateral` operator this `if` check and the related code checking for containment may be redundant. Can we get here with more fields than necessary?



##########
ql/src/test/results/clientnegative/udf_assert_true2.q.out:
##########
@@ -36,7 +36,7 @@ STAGE PLANS:
                   Limit
                     Number of rows: 2
                     Select Operator
-                      expressions: (1 + assert_true((_col6 < 2))) (type: int)
+                      expressions: (1 + UDFToInteger(assert_true((_col6 < 2)))) (type: int)

Review Comment:
   What caused this change? It looks a bit weird.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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
+ *
+ * This differs from the FilterTableFunctionTransposeRule for a number of reasons:
+ *   - We check if the filter condition is deterministic under Hive rules. We cannot
+ *     push filters that aren't deterministic.
+ *   - We check if the filter only references columns that are not part of the udtf.
+ *     If the input ref in the filter references a column that is generated by the
+ *     udtf, the filter cannot be pushed through.

Review Comment:
   Thanks for the analysis. Please do the following:
   1. Log a CALCITE ticket reporting the problem with `Logical` operators in `FilterTableFunctionTransposeRule`. 
   2. Add an entry in `org.apache.hadoop.hive.ql.optimizer.calcite.Bug`
   3. Reference the new entry somewhere in the rule similarly to how the entries are references elsewhere.
   4. Update the Javadoc since as far as I understand this is the main reason that we cannot use the respective Calcite rule.



##########
ql/src/test/queries/clientpositive/lateral_view.q:
##########
@@ -10,6 +10,11 @@ EXPLAIN SELECT myTable.* FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS
 EXPLAIN SELECT myTable.myCol, myTable2.myCol2 FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol LATERAL VIEW explode(array('a', 'b', 'c')) myTable2 AS myCol2 LIMIT 9;
 EXPLAIN SELECT myTable2.* FROM src LATERAL VIEW explode(array(array(1,2,3))) myTable AS myCol LATERAL VIEW explode(myTable.myCol) myTable2 AS myCol2 LIMIT 3;
 
+EXPLAIN CBO SELECT * FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol SORT BY key ASC, myCol ASC LIMIT 1;

Review Comment:
   If the goal of adding `EXPLAIN CBO` in every `LATERAL VIEW` query was to ensure that CBO doesn't fail then maybe we could enforce this differently (e.g., `set hive.cbo.fallback.strategy=never`).



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +644,80 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  private ASTNode createASTLateralView(TableFunctionScan tfs, Schema s,
+      QueryBlockInfo tableFunctionSource, String sqAlias) {
+    // The structure of the AST LATERAL VIEW will be:
+    //
+    //   TOK_LATERAL_VIEW
+    //     TOK_SELECT
+    //       TOK_SELEXPR
+    //         TOK_FUNCTION
+    //           <udtf func>
+    //           ...
+    //         <col alias for function>
+    //         TOK_TABALIAS
+    //           <table alias for lateral view>
+
+    // set up the select for the parameters of the UDTF
+    List<ASTNode> children = new ArrayList<>();
+    // The UDTF function call within the table function scan will be of the form:
+    // lateral(my_udtf_func(...), $0, $1, ...).  For recreating the AST, we need
+    // the inner "my_udtf_func".
+    RexCall lateralCall = (RexCall) tfs.getCall();
+    RexCall call = (RexCall) lateralCall.getOperands().get(0);
+    for (RexNode rn : call.getOperands()) {
+      ASTNode expr = rn.accept(new RexVisitor(s, rn 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.
+    lateralview.add(tableFunctionSource.ast);
+
+    return lateralview.node();
+  }
+
+  /**
+   * Check to see if we can optimize out the lateral view operators
+   * We do not need to use the lateral view syntax if all of the fields
+   * selected out of the table scan come from the UDTF call.  No join
+   * is needed because all the fields come from the table level rather
+   * than the row level.
+   */

Review Comment:
   The comment seems obsolete since the method does not check any fields.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,18 @@ private QueryBlockInfo convertSource(RelNode r) throws CalciteSemanticException
         ast = ASTBuilder.subQuery(left, sqAlias);
         s = new Schema((Union) r, sqAlias);
       }
+    } else if (r instanceof HiveTableFunctionScan &&

Review Comment:
   We can put the `instanceof` check inside the `isLateralView` method and simplify the code here to be simply `isLateralView(r)`.



##########
ql/src/test/results/clientpositive/llap/tablevalues.q.out:
##########
@@ -175,14 +175,27 @@ STAGE PLANS:
         TableScan
           alias: mytbl_n1
           Select Operator
-            expressions: array(struct(key,value,'A',10,key),struct(key,value,'B',20,key)) (type: array<struct<col1:string,col2:string,col3:string,col4:int,col5:string>>)
+            expressions: key (type: string)
             outputColumnNames: _col0
-            UDTF Operator
-              function name: inline
+            Lateral View Forward
               Select Operator
-                expressions: col3 (type: string), col4 (type: int), col5 (type: string)
-                outputColumnNames: _col0, _col1, _col2
-                ListSink
+                Lateral View Join Operator
+                  outputColumnNames: _col2, _col3, _col4
+                  Select Operator
+                    expressions: _col2 (type: string), _col3 (type: int), _col4 (type: string)
+                    outputColumnNames: _col0, _col1, _col2
+                    ListSink
+              Select Operator
+                expressions: array(struct('A',10,_col0),struct('B',20,_col0)) (type: array<struct<col1:string,col2:int,col3:string>>)
+                outputColumnNames: _col0
+                UDTF Operator
+                  function name: inline
+                  Lateral View Join Operator
+                    outputColumnNames: _col2, _col3, _col4
+                    Select Operator
+                      expressions: _col2 (type: string), _col3 (type: int), _col4 (type: string)
+                      outputColumnNames: _col0, _col1, _col2
+                      ListSink

Review Comment:
   This seems like a regression. Probably it was caused by the introduction of lateral in `HiveTableFunctionScan`. Do we need to revisit that choice?



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java:
##########
@@ -1024,30 +1022,8 @@ boolean isCBOExecuted() {
 
   @Override
   boolean isCBOSupportedLateralView(ASTNode lateralView) {
-    // Lateral view AST has the following shape:
-    // ^(TOK_LATERAL_VIEW
-    //   ^(TOK_SELECT ^(TOK_SELEXPR ^(TOK_FUNCTION Identifier params) identifier* tableAlias)))
-    if (lateralView.getToken().getType() == HiveParser.TOK_LATERAL_VIEW_OUTER) {
-      // LATERAL VIEW OUTER not supported in CBO
-      return false;
-    }
-    // Only INLINE followed by ARRAY supported in CBO
-    ASTNode lvFunc = (ASTNode) lateralView.getChild(0).getChild(0).getChild(0);
-    String lvFuncName = lvFunc.getChild(0).getText();
-    if (lvFuncName.compareToIgnoreCase(
-            GenericUDTFInline.class.getAnnotation(Description.class).name()) != 0) {
-      return false;
-    }
-    if (lvFunc.getChildCount() != 2) {
-      return false;
-    }

Review Comment:
   I believe the `if (lvFunc.getChildCount() != 2)` check was redundant anyways since at this line we already checked that the function is `GenericUDTFInline` and by definition it cannot have more than one input.
   
   Since here we are reasoning at the AST level I believe the first child corresponds to the function name token and the second child to the token representing the input argument to the inline function.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +125,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use empty listfor columnMappings. The return row type of the RelNode now comprises of
+    // all the fields within the UDTF, so there is no mapping from the output fields
+    // directly to the input fields anymore.
     final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
         tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
-        tfs.getColumnMappings());
+        Collections.emptySet());
 
     call.transformTo(newTableFunctionScanNode);

Review Comment:
   Does this rule still work as it is now that we are wrapping the table function with the `LATERAL` operator? Do we want/need to add special cases if we have lateral + inline array? 



##########
ql/src/java/org/apache/hadoop/hive/ql/ppd/OpProcFactory.java:
##########
@@ -504,27 +504,32 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       // We try to push the full Filter predicate iff:
       // - the Filter is on top of a TableScan, or
       // - the Filter is on top of a PTF (between PTF and Filter, there might be Select operators)
+      // - the Filter is on top of a LateralViewJoinOperator (the filter can be pushed through one
+      //   side of the join with the base table predicate, but not the UDTF side.)

Review Comment:
   I don't fully understand this optimization. The comment says that we want to fully push the filter if it is on top of a LateralViewJoinOperator but then it seems that we have restrictions on which side of the join we are going to push the filter. Are these restrictions enforced somewhere later on?



##########
ql/src/test/queries/clientpositive/lateral_view.q:
##########
@@ -10,6 +10,11 @@ EXPLAIN SELECT myTable.* FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS
 EXPLAIN SELECT myTable.myCol, myTable2.myCol2 FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol LATERAL VIEW explode(array('a', 'b', 'c')) myTable2 AS myCol2 LIMIT 9;
 EXPLAIN SELECT myTable2.* FROM src LATERAL VIEW explode(array(array(1,2,3))) myTable AS myCol LATERAL VIEW explode(myTable.myCol) myTable2 AS myCol2 LIMIT 3;
 
+EXPLAIN CBO SELECT * FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol SORT BY key ASC, myCol ASC LIMIT 1;

Review Comment:
   I suggested to create a new .q file (`cbo_lateral_views.q`) and add test cases there to put more focus on what we really want to test as part of this change. We want to verify that the CBO plan for certain types of queries is the expected one. Determining the types of queries is the whole point of having a dedicated .q file.
   
   **Examples**
   Do we care about LIMIT clause and the actual number there? Probably not so we don't need to add EXPLAIN CBO for that one.
   
   Do we care about how many times we have `LATERAL VIEW explode(array(1,2,3))` in the query? Probably not, one or two should suffice.
   ```sql
   --Q1
   SELECT myTable.myCol FROM src 
   LATERAL VIEW explode(array(1,2,3)) myTable AS myCol;
   --Q2
   SELECT myTable.myCol, myTable2.myCol2 FROM src
   LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
   LATERAL VIEW explode(array(1,2,3)) myTable2 AS myCol2;
   --Q3
   SELECT myTable.myCol, myTable2.myCol2, myTable3.myCol3 FROM src 
   LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
   LATERAL VIEW explode(array(1,2,3)) myTable2 AS myCol2
   LATERAL VIEW explode(array(1,2,3)) myTable3 AS myCol3;
   ```
   If the CBO plan is correct for Q1 and Q2 there is no reason to be wrong for Q3, Q4, etc.
   
   Do we care about what is the actual table function inside the `LATERAL VIEW` clause. Probably not, we don't need to test every possible variation of `explode`, `inline`, etc.
   
   Do we want our tables to have data and thus use the `src` and other similar tables? Probably not.
   
   All that to say that having many EXPLAIN CBO statements does not necessarily increase test coverage and has some drawbacks as well. Picking representatives queries and putting them in a file seems like a better alternative.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,18 @@ private QueryBlockInfo convertSource(RelNode r) throws CalciteSemanticException
         ast = ASTBuilder.subQuery(left, sqAlias);
         s = new Schema((Union) r, sqAlias);
       }
+    } else if (r instanceof HiveTableFunctionScan &&

Review Comment:
   Maybe it suffices to check for the super-class type `TableFunctionScan` since it is the one used in the cast just below.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1694152701

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [22 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1694547109

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [22 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1610411535

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [20 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306302306


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java:
##########
@@ -1024,30 +1022,8 @@ boolean isCBOExecuted() {
 
   @Override
   boolean isCBOSupportedLateralView(ASTNode lateralView) {
-    // Lateral view AST has the following shape:
-    // ^(TOK_LATERAL_VIEW
-    //   ^(TOK_SELECT ^(TOK_SELEXPR ^(TOK_FUNCTION Identifier params) identifier* tableAlias)))
-    if (lateralView.getToken().getType() == HiveParser.TOK_LATERAL_VIEW_OUTER) {
-      // LATERAL VIEW OUTER not supported in CBO
-      return false;
-    }
-    // Only INLINE followed by ARRAY supported in CBO
-    ASTNode lvFunc = (ASTNode) lateralView.getChild(0).getChild(0).getChild(0);
-    String lvFuncName = lvFunc.getChild(0).getText();
-    if (lvFuncName.compareToIgnoreCase(
-            GenericUDTFInline.class.getAnnotation(Description.class).name()) != 0) {
-      return false;
-    }
-    if (lvFunc.getChildCount() != 2) {
-      return false;
-    }

Review Comment:
   I'm not sure I understand this check.  But all lateral views are supported now, with the exception of OUTER.  
   
   This method only checks if CBO can support lateral views.  This shouldn't be a limitation here.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306301835


##########
ql/src/test/queries/clientpositive/lateral_view.q:
##########
@@ -10,6 +10,11 @@ EXPLAIN SELECT myTable.* FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS
 EXPLAIN SELECT myTable.myCol, myTable2.myCol2 FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol LATERAL VIEW explode(array('a', 'b', 'c')) myTable2 AS myCol2 LIMIT 9;
 EXPLAIN SELECT myTable2.* FROM src LATERAL VIEW explode(array(array(1,2,3))) myTable AS myCol LATERAL VIEW explode(myTable.myCol) myTable2 AS myCol2 LIMIT 3;
 
+EXPLAIN CBO SELECT * FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol SORT BY key ASC, myCol ASC LIMIT 1;

Review Comment:
   I actually thought about doing it this way, but I think it makes sense to always run a CBO plan with any query that we run.  My personal opinion is that we should add this to the framework and run it by default without having to explciitly specify it, but that's a change for another day.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1335607615


##########
ql/src/java/org/apache/hadoop/hive/ql/ppd/OpProcFactory.java:
##########
@@ -385,6 +385,23 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
 
   }
 
+  public static class LateralViewJoinerPPD extends JoinerPPD implements SemanticNodeProcessor {
+    @Override
+    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
+        Object... nodeOutputs) throws SemanticException {
+      Object o = super.process(nd, stack, procCtx, nodeOutputs);
+      Operator<?> operator = (Operator<?>) nd;
+      OpWalkerInfo owi = (OpWalkerInfo) procCtx;
+      if (HiveConf.getBoolVar(owi.getParseContext().getConf(),
+          HiveConf.ConfVars.HIVEPPDREMOVEDUPLICATEFILTERS)) {
+        // remove all the candidate filter operators
+        // when we get to the TS

Review Comment:
   I don't think we are in the TS op here? I think we are in the `LateralViewJoinOperator` (LVJ).



##########
ql/src/java/org/apache/hadoop/hive/ql/ppd/OpProcFactory.java:
##########
@@ -385,6 +385,23 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
 
   }
 
+  public static class LateralViewJoinerPPD extends JoinerPPD implements SemanticNodeProcessor {
+    @Override
+    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
+        Object... nodeOutputs) throws SemanticException {
+      Object o = super.process(nd, stack, procCtx, nodeOutputs);
+      Operator<?> operator = (Operator<?>) nd;

Review Comment:
   unused variable/dead code?



##########
ql/src/test/results/clientpositive/llap/lateral_view_cbo.q.out:
##########
@@ -1,34 +1,113 @@
-PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM src 
+PREHOOK: query: CREATE TABLE simple_table (col string, array_col array<string>)
+PREHOOK: type: CREATETABLE
+PREHOOK: Output: database:default
+PREHOOK: Output: default@simple_table
+POSTHOOK: query: CREATE TABLE simple_table (col string, array_col array<string>)
+POSTHOOK: type: CREATETABLE
+POSTHOOK: Output: database:default
+POSTHOOK: Output: default@simple_table
+PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 PREHOOK: type: QUERY
-PREHOOK: Input: default@src
+PREHOOK: Input: default@simple_table
 #### A masked pattern was here ####
-POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM src 
+POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 POSTHOOK: type: QUERY
-POSTHOOK: Input: default@src
+POSTHOOK: Input: default@simple_table
 #### A masked pattern was here ####
 CBO PLAN:
 HiveProject(mycol=[$6])
-  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
-    HiveTableScan(table=[[default, src]], table:alias=[src])
+  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
+    HiveTableScan(table=[[default, simple_table]], table:alias=[simple_table])
 
-PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM src
+PREHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 LATERAL VIEW explode(array(1,2,3)) myTable2 AS myCol2
 PREHOOK: type: QUERY
-PREHOOK: Input: default@src
+PREHOOK: Input: default@simple_table
 #### A masked pattern was here ####
-POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM src
+POSTHOOK: query: EXPLAIN CBO SELECT myTable.myCol, myTable2.myCol2 FROM simple_table
 LATERAL VIEW explode(array(1,2,3)) myTable AS myCol
 LATERAL VIEW explode(array(1,2,3)) myTable2 AS myCol2
 POSTHOOK: type: QUERY
-POSTHOOK: Input: default@src
+POSTHOOK: Input: default@simple_table
 #### A masked pattern was here ####
 CBO PLAN:
 HiveProject(mycol=[$6], mycol2=[$7])
-  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5, $6)], rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol, INTEGER mytable2.mycol2)])
-    HiveProject(key=[$0], value=[$1], BLOCK__OFFSET__INSIDE__FILE=[$2], INPUT__FILE__NAME=[$3], ROW__ID=[$4], ROW__IS__DELETED=[$5], mytable.mycol=[$6])
-      HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) key, VARCHAR(2147483647) value, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
-        HiveTableScan(table=[[default, src]], table:alias=[src])
+  HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5, $6)], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol, INTEGER mytable2.mycol2)])
+    HiveProject(col=[$0], array_col=[$1], BLOCK__OFFSET__INSIDE__FILE=[$2], INPUT__FILE__NAME=[$3], ROW__ID=[$4], ROW__IS__DELETED=[$5], mytable.mycol=[$6])
+      HiveTableFunctionScan(invocation=[LATERAL(explode(ARRAY(1, 2, 3)), $0, $1, $2, $3, $4, $5)], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, INTEGER mytable.mycol)])
+        HiveTableScan(table=[[default, simple_table]], table:alias=[simple_table])
+
+PREHOOK: query: EXPLAIN CBO SELECT tf.col1, tf.col2, tf.col3
+FROM simple_table
+  LATERAL TABLE(VALUES('A', 10, simple_table.col),('B', 20, simple_table.col)) AS tf(col1, col2, col3)
+PREHOOK: type: QUERY
+PREHOOK: Input: default@simple_table
+#### A masked pattern was here ####
+POSTHOOK: query: EXPLAIN CBO SELECT tf.col1, tf.col2, tf.col3
+FROM simple_table
+  LATERAL TABLE(VALUES('A', 10, simple_table.col),('B', 20, simple_table.col)) AS tf(col1, col2, col3)
+POSTHOOK: type: QUERY
+POSTHOOK: Input: default@simple_table
+#### A masked pattern was here ####
+CBO PLAN:
+HiveProject(col1=[$6], col2=[$7], col3=[$8])
+  HiveTableFunctionScan(invocation=[inline(ARRAY(ROW($0, $1, $2, $3, $4, $5, _UTF-16LE'A':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 10, $0), ROW($0, $1, $2, $3, $4, $5, _UTF-16LE'B':VARCHAR(2147483647) CHARACTER SET "UTF-16LE", 20, $0)))], rowType=[RecordType(VARCHAR(2147483647) col, VARCHAR(2147483647) ARRAY array_col, BIGINT BLOCK__OFFSET__INSIDE__FILE, VARCHAR(2147483647) INPUT__FILE__NAME, RecordType(BIGINT writeid, INTEGER bucketid, BIGINT rowid) ROW__ID, BOOLEAN ROW__IS__DELETED, VARCHAR(2147483647) tf.col1, INTEGER tf.col2, VARCHAR(2147483647) tf.col3)])

Review Comment:
   Do we need to keep `$0, $1, $2, $3, $4, $5,` in this case. They seem redundant should we pass them as an input to the table function? 
   
   Does this affect runtime plan/performance? Are we going to copy all these columns and pass them as input to the function?



##########
ql/src/test/results/clientpositive/llap/lateral_view_ppd.q.out:
##########
@@ -316,29 +332,36 @@ STAGE PLANS:
           filterExpr: (key = '0') (type: boolean)
           Filter Operator
             predicate: (key = '0') (type: boolean)
-            Lateral View Forward
-              Select Operator
-                expressions: value (type: string)
-                outputColumnNames: value
-                Lateral View Join Operator
-                  outputColumnNames: _col1, _col6
-                  Select Operator
-                    expressions: _col1 (type: string), _col6 (type: int)
-                    outputColumnNames: _col0, _col1
-                    ListSink
-              Select Operator
-                expressions: array(1,2,3) (type: array<int>)
-                outputColumnNames: _col0
-                UDTF Operator
-                  function name: explode
-                  Filter Operator
-                    predicate: (col > 1) (type: boolean)

Review Comment:
   Can't find the other comment with the extra details. Can you please share the link? 



##########
ql/src/java/org/apache/hadoop/hive/ql/ppd/OpProcFactory.java:
##########
@@ -385,6 +385,23 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
 
   }
 
+  public static class LateralViewJoinerPPD extends JoinerPPD implements SemanticNodeProcessor {
+    @Override
+    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
+        Object... nodeOutputs) throws SemanticException {
+      Object o = super.process(nd, stack, procCtx, nodeOutputs);
+      Operator<?> operator = (Operator<?>) nd;
+      OpWalkerInfo owi = (OpWalkerInfo) procCtx;
+      if (HiveConf.getBoolVar(owi.getParseContext().getConf(),
+          HiveConf.ConfVars.HIVEPPDREMOVEDUPLICATEFILTERS)) {
+        // remove all the candidate filter operators
+        // when we get to the TS

Review Comment:
   Why do we need to do this here and not as part of `TableScanPPD` as it is done in every other case? Why is it specific to LVJ?



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1740744437

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [22 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1741635215

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [22 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320422068


##########
ql/src/test/queries/clientpositive/lateral_view.q:
##########
@@ -10,6 +10,11 @@ EXPLAIN SELECT myTable.* FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS
 EXPLAIN SELECT myTable.myCol, myTable2.myCol2 FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol LATERAL VIEW explode(array('a', 'b', 'c')) myTable2 AS myCol2 LIMIT 9;
 EXPLAIN SELECT myTable2.* FROM src LATERAL VIEW explode(array(array(1,2,3))) myTable AS myCol LATERAL VIEW explode(myTable.myCol) myTable2 AS myCol2 LIMIT 3;
 
+EXPLAIN CBO SELECT * FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol SORT BY key ASC, myCol ASC LIMIT 1;

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320427074


##########
ql/src/test/results/clientnegative/udf_assert_true2.q.out:
##########
@@ -36,7 +36,7 @@ STAGE PLANS:
                   Limit
                     Number of rows: 2
                     Select Operator
-                      expressions: (1 + assert_true((_col6 < 2))) (type: int)
+                      expressions: (1 + UDFToInteger(assert_true((_col6 < 2)))) (type: int)

Review Comment:
   I haven't done research on this, but I would guess this was caused by the fact that in the previous version, it didn't go through CBO, whereas CBO must have added this slight performance regression.  I can file a separate Jira on this.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1285620207


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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 tfs = 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(tfs)) {
+      return false;
+    }

Review Comment:
   Why do we need to check explicitly for inlineArray and rely upon FunctionRegistry? Isn't `RelColumnMapping` sufficient to give us this information?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,77 @@ 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.
+      //
+      // The structure of the AST in this "else if" branch will be:

Review Comment:
   Would it make sense to refactor this new code in a separate method? Maybe also add a test similar to `TestASTConverter` to enforce the expected output.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +703,45 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  /**
+   * Check to see if we can optimize out the lateral view operators
+   * We do not need to use the lateral view syntax if all of the fields
+   * selected out of the table scan come from the UDTF call.  No join
+   * is needed because all the fields come from the table level rather
+   * than the row level.
+   */
+  private boolean canOptimizeOutLateralView(HiveTableFunctionScan htfs) {
+    Set<Integer> inputRefs = new HashSet<>();
+    if (this.select instanceof HiveProject) {

Review Comment:
   Is `this` operator always the parent of `htfs` or it can be multiple levels up (grand-grand-...-parent)?
   
   If it is just the parent then I get again the feeling that this should be a separate CBO rule. If we are talking about operators at multiple levels up then I am not sure to what inputRefs refer to.
   
   The code here looks like something that the `HiveRelFieldTrimmer` should do before dropping unnecessary references.



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

Review Comment:
   I am not sure how this will work if we are transposing Filters (potentially other ops) below a `HiveTableFunctionScan`?
   
   Is htfsNode.getInputs().size() > 1 possible? Should we put guards against this case somewhere in the code?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -577,6 +588,77 @@ 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)) {

Review Comment:
   I didn't follow all the details about this `canOptimizeOutLateralView` method and related code but the comment gives me the impression that this is a CBO level optimization. Would it be possible to model this with a CBO rule?



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java:
##########
@@ -256,10 +257,20 @@ 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

Review Comment:
   Shouldn't we do this disambiguation inside `getColumnAliasesFromASTNode` so that other places where we use `columnAliases` have the same content?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +124,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use null for columnMappings. The return row type of the RelNode now comprises of

Review Comment:
   According to the javadoc of TableFunctionScan#getColumnMappings() a `null` indicates unknown and is different from empty. What semantics do we want here?
   
   



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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

Review Comment:
   Please highlight the main differences with `org.apache.calcite.rel.rules.FilterTableFunctionTransposeRule` to clarify why a separate class is necessary.



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java:
##########
@@ -1024,30 +1022,8 @@ boolean isCBOExecuted() {
 
   @Override
   boolean isCBOSupportedLateralView(ASTNode lateralView) {
-    // Lateral view AST has the following shape:
-    // ^(TOK_LATERAL_VIEW
-    //   ^(TOK_SELECT ^(TOK_SELEXPR ^(TOK_FUNCTION Identifier params) identifier* tableAlias)))
-    if (lateralView.getToken().getType() == HiveParser.TOK_LATERAL_VIEW_OUTER) {
-      // LATERAL VIEW OUTER not supported in CBO
-      return false;
-    }
-    // Only INLINE followed by ARRAY supported in CBO
-    ASTNode lvFunc = (ASTNode) lateralView.getChild(0).getChild(0).getChild(0);
-    String lvFuncName = lvFunc.getChild(0).getText();
-    if (lvFuncName.compareToIgnoreCase(
-            GenericUDTFInline.class.getAnnotation(Description.class).name()) != 0) {
-      return false;
-    }
-    if (lvFunc.getChildCount() != 2) {
-      return false;
-    }

Review Comment:
   Do we support arbitrary number of childs for lateral views? Is this a new feature?



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java:
##########
@@ -114,7 +115,7 @@ public LateralViewPlan(ASTNode lateralView, RelOptCluster cluster, RelNode input
 
     this.lateralViewRel = HiveTableFunctionScan.create(cluster,
         TraitsUtil.getDefaultTraitSet(cluster), ImmutableList.of(inputRel), udtfCall,
-        null, retType, null);
+        null, retType, createColumnMappings(inputRel));

Review Comment:
   It is a bit strange that the column mapping depends only on the `inputRel` and the `udtfCall` does not have any impact on the result. Why is that?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +124,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use null for columnMappings. The return row type of the RelNode now comprises of
+    // all the fields within the UDTF, so there is no mapping from the output fields
+    // directly to the input fields anymore.
     final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
         tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
-        tfs.getColumnMappings());
+        /*columnMappings*/ null);

Review Comment:
   nit: Putting the name of the variable inside comments is not necessary. IDEs are pretty intelligent these days.
   
   ![columnMappings](https://github.com/apache/hive/assets/15013153/448d0e88-8a66-4ad2-a9f4-ce7385417f0e)
   



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306308639


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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
+ *
+ * This differs from the FilterTableFunctionTransposeRule for a number of reasons:
+ *   - We check if the filter condition is deterministic under Hive rules. We cannot
+ *     push filters that aren't deterministic.
+ *   - We check if the filter only references columns that are not part of the udtf.
+ *     If the input ref in the filter references a column that is generated by the
+ *     udtf, the filter cannot be pushed through.

Review Comment:
   Unfortunately, the FilterTableFunctionTransposeRule uses LogicalFilter and LogicalTableFunctionScan, so it is not reusable here.
   
   Also, unfortunately, we cannot isolate the transformation.  We actually need the transformation here so we don't cause a regression.  This optimization was done in the physical optimizer specifically for non-CBO plans, but it didn't hit the optimization in the CBO path.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1720780616

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [24 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1326809494


##########
ql/src/test/results/clientpositive/llap/lateral_view_ppd.q.out:
##########
@@ -316,29 +332,36 @@ STAGE PLANS:
           filterExpr: (key = '0') (type: boolean)
           Filter Operator
             predicate: (key = '0') (type: boolean)
-            Lateral View Forward
-              Select Operator
-                expressions: value (type: string)
-                outputColumnNames: value
-                Lateral View Join Operator
-                  outputColumnNames: _col1, _col6
-                  Select Operator
-                    expressions: _col1 (type: string), _col6 (type: int)
-                    outputColumnNames: _col0, _col1
-                    ListSink
-              Select Operator
-                expressions: array(1,2,3) (type: array<int>)
-                outputColumnNames: _col0
-                UDTF Operator
-                  function name: explode
-                  Filter Operator
-                    predicate: (col > 1) (type: boolean)

Review Comment:
   This, like others, happened because we are going through the CBO path.
   
   In this case, the optimizer for the planner changed.  There was code missing in OpProcFactory (more details in a different comment)



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320421951


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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
+ *
+ * This differs from the FilterTableFunctionTransposeRule for a number of reasons:
+ *   - We check if the filter condition is deterministic under Hive rules. We cannot
+ *     push filters that aren't deterministic.
+ *   - We check if the filter only references columns that are not part of the udtf.
+ *     If the input ref in the filter references a column that is generated by the
+ *     udtf, the filter cannot be pushed through.

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1712378735

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [23 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1246991408


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveLVTableFunctionScan.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.reloperators;
+
+import java.lang.reflect.Type;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.TableFunctionScan;
+import org.apache.calcite.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException;
+
+/**
+  *  HiveLVTableFunctionScan (LV stands for lateral views).
+  * This RelNode is created through a lateral view. This class differs from its
+  * parent's class in that the fields in the child RelNode are present in the output
+  * RelDataType. The output of the UDTF is joined to these base table types on each
+  * row.
+  */
+public class HiveLVTableFunctionScan extends HiveTableFunctionScan {

Review Comment:
   I relooked at this and I think the Calcite TableFunctionScan node actually turns out to be the correct primitive.  Its purpose is to take an input row structure and output a table with multiple rows.
   
   The reason I added an extra operator (which was actually done as part of the code review) was because I added additional functionality as to how the TableFunctionScan operator worked.  The lateral views put in the input RelNode fields as the first <n> fields and then add on the output of the UDTF fields.  This is different from UDTF operators which only contain the output of the UDTF function.  The second operator was used to distinguish these different use cases.
   
   After looking at the Calcite API a bit deeper, it turns out they have the capability to support both of these use cases already.  By taking advantage of the Set<RelColumnMapping>, both use cases are now represented so we now are using a core Calcite operator for this feature.  
   
   Thanks for making me look into this a little deeper because I think the code is now better!



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1613330920

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [15 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244462496


##########
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:
   We don't have to worry about special characters.  This step takes place only after parsing and it should guarantee a unique value.  
   
   I suppose it may be possible to create an alias for the lateral view even with special characters where the names aren't unique.  But if we do?  There's no way to catch it here.



-- 
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-unsubscribe@hive.apache.org

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


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


Re: [PR] HIVE-27399: Add support for lateral views with CBO [hive]

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1743127620

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [22 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244458166


##########
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:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244463245


##########
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:
   Yes.  I mentioned this in the comment.  Basically, this can happen when the select above the lateral view only contains columns that are produced by the UDTF.  In that case, there is no need to do the lateral join back to the base table.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244463808


##########
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:
   I think this is a result of using CalcitePlanner.  The query here contains a view, so this seems correct to me. 



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1286162327


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +703,45 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  /**
+   * Check to see if we can optimize out the lateral view operators
+   * We do not need to use the lateral view syntax if all of the fields
+   * selected out of the table scan come from the UDTF call.  No join
+   * is needed because all the fields come from the table level rather
+   * than the row level.
+   */
+  private boolean canOptimizeOutLateralView(HiveTableFunctionScan htfs) {
+    Set<Integer> inputRefs = new HashSet<>();
+    if (this.select instanceof HiveProject) {

Review Comment:
   "this" is always the parent.  As mentioned above, this only checks to see if the join is needed and if the parent makes reference to any field within the child that needs joining.  No need to check grandparents because those inputs are on a different level.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1286174831


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/relnodegen/LateralViewPlan.java:
##########
@@ -114,7 +115,7 @@ public LateralViewPlan(ASTNode lateralView, RelOptCluster cluster, RelNode input
 
     this.lateralViewRel = HiveTableFunctionScan.create(cluster,
         TraitsUtil.getDefaultTraitSet(cluster), ImmutableList.of(inputRel), udtfCall,
-        null, retType, null);
+        null, retType, createColumnMappings(inputRel));

Review Comment:
   I'm not sure I understand the question here, but lemme try to explain how I made this work.  I think it fits in with what is meant by column mappings...
   
   The idea of the TableFunctionScan is to create multiple rows from a single row coming in.  The columns in the new rows can be broken down into 2 categories:
   
   1) Columns with "exploded" or "created" data.  For instance, if the input row had a column of type array, each new row might contain an element from that array.
   2) Columns directly from the inputRel.  This will be denormalized data and "joined" to the data created in the columns mentioned in 1)
   
   The column mapping here depends on the columns mentioned in 2).  Thus, they will always map only to inputRel columns (from 2) and never to udtfCall columns (from 1).



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1321538915


##########
ql/src/test/results/clientpositive/llap/lateral_view_ppd.q.out:
##########
@@ -316,29 +332,36 @@ STAGE PLANS:
           filterExpr: (key = '0') (type: boolean)
           Filter Operator
             predicate: (key = '0') (type: boolean)
-            Lateral View Forward
-              Select Operator
-                expressions: value (type: string)
-                outputColumnNames: value
-                Lateral View Join Operator
-                  outputColumnNames: _col1, _col6
-                  Select Operator
-                    expressions: _col1 (type: string), _col6 (type: int)
-                    outputColumnNames: _col0, _col1
-                    ListSink
-              Select Operator
-                expressions: array(1,2,3) (type: array<int>)
-                outputColumnNames: _col0
-                UDTF Operator
-                  function name: explode
-                  Filter Operator
-                    predicate: (col > 1) (type: boolean)

Review Comment:
   The `(col > 1)` predicate is applied twice after the changes in this PR; once before the `Lateral View Join Operator` and once afterwards. Is this normal? Do we know why?
   
   Can we add the `EXPLAIN CBO` for this or an equivalent query inside `lateral_view_cbo.q`?



##########
ql/src/test/results/clientpositive/llap/create_view.q.out:
##########
@@ -1121,7 +1121,7 @@ Sort Columns:       	[]
 	 	 
 # View Information	 	 
 Original Query:     	SELECT * FROM src LATERAL VIEW explode(array(1,2,3)) myTable AS myCol	 
-Expanded Query:     	SELECT `src`.`key`, `src`.`value`, `mytable`.`mycol` FROM `default`.`src` LATERAL VIEW explode(array(1,2,3)) `myTable` AS `myCol`	 

Review Comment:
   Is it okay that the backticks were removed from the expanded query?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/Bug.java:
##########
@@ -88,4 +88,9 @@ public final class Bug {
    * Whether <a href="https://issues.apache.org/jira/browse/CALCITE-5669">CALCITE-5669</a> is fixed.
    */
   public static final boolean CALCITE_5669_FIXED = false;
+
+  /**
+   * Whether <a href="https://issues.apache.org/jira/browse/CALCITE-5669">CALCITE-5985</a> is fixed.

Review Comment:
   `s/CALCITE-5669/CALCITE-5985`



##########
ql/src/test/queries/clientpositive/lateral_view_cbo.q:
##########
@@ -0,0 +1,8 @@
+--! qt:dataset:src
+--Q1
+EXPLAIN CBO SELECT myTable.myCol FROM src 
+LATERAL VIEW explode(array(1,2,3)) myTable AS myCol;

Review Comment:
   Please include an `EXPLAIN CBO` query with `inline(array(1,2,3)` which seems to be handled differently.



##########
ql/src/test/queries/clientpositive/lateral_view_cbo.q:
##########
@@ -0,0 +1,8 @@
+--! qt:dataset:src

Review Comment:
   nit: We don't really need data for the plans here so we can drop the usage of `src`. A very simple DDL (`CREATE TABLE simple_t (col STRING)`) suffices and would make the test self-contained.



##########
ql/src/test/results/clientpositive/tez/tez_union_udtf.q.out:
##########
@@ -140,7 +137,7 @@ POSTHOOK: Input: default@src
 POSTHOOK: Input: default@src1
 POSTHOOK: Output: database:default
 POSTHOOK: Output: default@x
-POSTHOOK: Lineage: x.key EXPRESSION [(src)src.FieldSchema(name:key, type:string, comment:default), (src1)src1.FieldSchema(name:key, type:string, comment:default), ]

Review Comment:
   This seems lineage change seems like a regression that we may need to look into. Did we lose the information that the "key" column comes from the `src` table?



##########
ql/src/test/results/clientpositive/llap/lineage2.q.out:
##########
@@ -710,7 +710,7 @@ PREHOOK: query: select identity, ep1_id from relations
 PREHOOK: type: QUERY
 PREHOOK: Input: default@relations
 #### A masked pattern was here ####
-{"version":"1.0","engine":"tez","database":"default","hash":"436a649a0d9540e8f093f8353d86813a","queryText":"select identity, ep1_id from relations\n  lateral view explode(ep1_ids) nav_rel as ep1_id","edges":[{"sources":[2],"targets":[0],"edgeType":"PROJECTION"},{"sources":[3],"targets":[1],"expression":"nav_rel._col12","edgeType":"PROJECTION"}],"vertices":[{"id":0,"vertexType":"COLUMN","vertexId":"identity"},{"id":1,"vertexType":"COLUMN","vertexId":"ep1_id"},{"id":2,"vertexType":"COLUMN","vertexId":"default.relations.identity"},{"id":3,"vertexType":"COLUMN","vertexId":"default.relations.ep1_ids"}]}

Review Comment:
   I don't know much about how the lineage info is used but I suppose the change in the edge name shouldn't generate regressions. Do you have any thoughts about this?



##########
ql/src/test/results/clientpositive/llap/udtf_json_tuple.q.out:
##########
@@ -395,24 +398,27 @@ STAGE PLANS:
                           Lateral View Join Operator
                             outputColumnNames: _col6, _col7, _col8, _col9, _col10
                             Statistics: Num rows: 6 Data size: 3233 Basic stats: COMPLETE Column stats: COMPLETE
-                            Select Operator
-                              expressions: _col7 (type: string)
-                              outputColumnNames: _col7
-                              Statistics: Num rows: 6 Data size: 3233 Basic stats: COMPLETE Column stats: COMPLETE
-                              Group By Operator
-                                aggregations: count()
-                                keys: _col7 (type: string)
-                                minReductionHashAggr: 0.8333333
-                                mode: hash
-                                outputColumnNames: _col0, _col1
-                                Statistics: Num rows: 1 Data size: 8 Basic stats: COMPLETE Column stats: COMPLETE
-                                Reduce Output Operator
-                                  key expressions: _col0 (type: string)
-                                  null sort order: z
-                                  sort order: +
-                                  Map-reduce partition columns: _col0 (type: string)
+                            Filter Operator
+                              predicate: _col6 is not null (type: boolean)

Review Comment:
   A few lines above I see `Filter: c0 is not null`. Is `_col6` the same with `c0`? Is this new filter redundant?



##########
ql/src/test/results/clientnegative/udf_assert_true2.q.out:
##########
@@ -36,7 +36,7 @@ STAGE PLANS:
                   Limit
                     Number of rows: 2
                     Select Operator
-                      expressions: (1 + assert_true((_col6 < 2))) (type: int)
+                      expressions: (1 + UDFToInteger(assert_true((_col6 < 2)))) (type: int)

Review Comment:
   On a second, I guess we don't have to follow up on this. I assume using `assert_true` with arithmetic operations would cause the same conversion even when lateral views are not present in the query.



##########
ql/src/test/results/clientpositive/llap/ppd_field_garbage.q.out:
##########
@@ -17,7 +17,7 @@ POSTHOOK: Input: default@test_issue
 POSTHOOK: Output: database:default
 POSTHOOK: Output: default@v_test_issue
 POSTHOOK: Lineage: v_test_issue.age EXPRESSION [(test_issue)test_issue.FieldSchema(name:test_c, type:struct<user_c:struct<age:int>>, comment:null), ]
-POSTHOOK: Lineage: v_test_issue.fileid EXPRESSION [(test_issue)test_issue.FieldSchema(name:fileid, type:int, comment:null), ]

Review Comment:
   I am not very familiar with lineage to comment if this change from `EXPRESSION` to `SIMPLE` is an improvement or a regression. I checked a bit `org.apache.hadoop.hive.ql.hooks.LineageInfo.DependencyType` but not really sure what should be the type here. Do you happen to know something more about it?



##########
ql/src/test/results/clientpositive/llap/reduce_deduplicate_null_keys.q.out:
##########
@@ -82,7 +82,7 @@ STAGE PLANS:
                           outputColumnNames: _col0, _col1
                           Statistics: Num rows: 1 Data size: 4 Basic stats: COMPLETE Column stats: COMPLETE
                           Reduce Output Operator
-                            key expressions: CASE WHEN ((_col0 = _col1)) THEN (1) ELSE (2) END (type: int)

Review Comment:
   I guess a result of HIVE-21152 + the fact that now we are using CBO for lateral views.



##########
ql/src/test/queries/clientpositive/lateral_view_cbo.q:
##########
@@ -0,0 +1,8 @@
+--! qt:dataset:src
+--Q1
+EXPLAIN CBO SELECT myTable.myCol FROM src 
+LATERAL VIEW explode(array(1,2,3)) myTable AS myCol;

Review Comment:
   Please include an `EXPLAIN CBO` query where the arguments of the table function are not constants:  `explode(table.array_col)`.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterTableFunctionTransposeRule.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.rel.metadata.RelColumnMapping;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.commons.collections4.CollectionUtils;
+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
+ *
+ * We cannot use Calcite's FilterTableFunctionTransposeRule because that rule
+ * uses LogicalFilter and LogicalTableFunctionScan.  We should remove this
+ * class when CALCITE-5985 is fixed (and remove the CALCITE_5985_FIXED entry

Review Comment:
   Please add the following inside `matches` or `onMatch` method.
   ```java
   if (Bug.CALCITE_5985_FIXED) {
     throw new IllegalStateException("Class is redundant after fix is merged into Calcite");
   }
   ```
   This makes it easier to find the code that needs to be replaced once the issue is fixed.



##########
ql/src/test/results/clientpositive/llap/udtf_json_tuple.q.out:
##########
@@ -395,24 +398,27 @@ STAGE PLANS:
                           Lateral View Join Operator
                             outputColumnNames: _col6, _col7, _col8, _col9, _col10
                             Statistics: Num rows: 6 Data size: 3233 Basic stats: COMPLETE Column stats: COMPLETE
-                            Select Operator
-                              expressions: _col7 (type: string)
-                              outputColumnNames: _col7
-                              Statistics: Num rows: 6 Data size: 3233 Basic stats: COMPLETE Column stats: COMPLETE
-                              Group By Operator
-                                aggregations: count()
-                                keys: _col7 (type: string)
-                                minReductionHashAggr: 0.8333333
-                                mode: hash
-                                outputColumnNames: _col0, _col1
-                                Statistics: Num rows: 1 Data size: 8 Basic stats: COMPLETE Column stats: COMPLETE
-                                Reduce Output Operator
-                                  key expressions: _col0 (type: string)
-                                  null sort order: z
-                                  sort order: +
-                                  Map-reduce partition columns: _col0 (type: string)
+                            Filter Operator
+                              predicate: _col6 is not null (type: boolean)

Review Comment:
   I see the same pattern (new filter appears) in a few other .q.out files.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +125,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use empty listfor columnMappings. The return row type of the RelNode now comprises of
+    // all the fields within the UDTF, so there is no mapping from the output fields
+    // directly to the input fields anymore.
     final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
         tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
-        tfs.getColumnMappings());
+        Collections.emptySet());
 
     call.transformTo(newTableFunctionScanNode);

Review Comment:
   I saw the new changes in `LateralViewPlan` and this made me thinking that an equivalent thing could be done as part of this rule. Something like match `lateral(inline(array(1,2)))` and transform to `inline(array($0,1,2))`.
   
   I don't feel strongly about it so if you prefer to keep the `LateralViewPlan.isInlineArray` method there I am OK with it.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320426662


##########
ql/src/test/results/clientpositive/llap/tablevalues.q.out:
##########
@@ -175,14 +175,27 @@ STAGE PLANS:
         TableScan
           alias: mytbl_n1
           Select Operator
-            expressions: array(struct(key,value,'A',10,key),struct(key,value,'B',20,key)) (type: array<struct<col1:string,col2:string,col3:string,col4:int,col5:string>>)
+            expressions: key (type: string)
             outputColumnNames: _col0
-            UDTF Operator
-              function name: inline
+            Lateral View Forward
               Select Operator
-                expressions: col3 (type: string), col4 (type: int), col5 (type: string)
-                outputColumnNames: _col0, _col1, _col2
-                ListSink
+                Lateral View Join Operator
+                  outputColumnNames: _col2, _col3, _col4
+                  Select Operator
+                    expressions: _col2 (type: string), _col3 (type: int), _col4 (type: string)
+                    outputColumnNames: _col0, _col1, _col2
+                    ListSink
+              Select Operator
+                expressions: array(struct('A',10,_col0),struct('B',20,_col0)) (type: array<struct<col1:string,col2:int,col3:string>>)
+                outputColumnNames: _col0
+                UDTF Operator
+                  function name: inline
+                  Lateral View Join Operator
+                    outputColumnNames: _col2, _col3, _col4
+                    Select Operator
+                      expressions: _col2 (type: string), _col3 (type: int), _col4 (type: string)
+                      outputColumnNames: _col0, _col1, _col2
+                      ListSink

Review Comment:
   Ok, so this one is interesting and leaves us with a few choices. 
   
   This regression is indeed because of the introduction of lateral in HIveTableFunctionScan. The previous iteration was doing an extra performance enhancement that handled this case as well as others.  The addition of the "lateral" function allowed the ASTConverter to convert the RelNodes back to its original AST with the lateral keyword.
   
   The regression here is that the original code had one special case that went through CBO.  When the lateral view contained an "Inline(array(...))", it went through the CBO path. When it got converted back to an AST, there was no code to handle the lateral syntax, so it did the optimization to remove the Lateral View Operator.
   
   I have thought of 3 options on how to handle this.
   1) Leave the regression in and handle this in a separate Jira.  The separate Jira can handle all the other places where the Lateral View Operator can be removed and it can be done in a generic way.  It would be too much to combine with this review, so it should be done separately.  We can probably get away with the regression because the "inline(array(..))" entails that the rows are specified within the "array" function, which would limit the number of rows to be processed.  It would probably never be used with more than tens of rows, so the performance regression would never be felt by an end user.
   2) Roll back one previous version in this pull request which does not have the regression.  I don't think I like this option because your previous suggestions did make the code better
   3) Put in some special case logic to ensure the "lateral" function does not get added in this one special cases.  I included this in the most recent pull request.  I'm not sure I like it because it does add special case code here as well as a new rule that was created.
   
   I'll let you call which is best.  If we go with option 3, you can review the most recent code in this pull request.  If you go with option 1), I'll roll back that one change and remove the rule that handles the special case.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1739823813

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![C](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/C-16px.png 'C')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [4 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [90 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1326810590


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/Bug.java:
##########
@@ -88,4 +88,9 @@ public final class Bug {
    * Whether <a href="https://issues.apache.org/jira/browse/CALCITE-5669">CALCITE-5669</a> is fixed.
    */
   public static final boolean CALCITE_5669_FIXED = false;
+
+  /**
+   * Whether <a href="https://issues.apache.org/jira/browse/CALCITE-5669">CALCITE-5985</a> is fixed.

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1326810156


##########
ql/src/test/queries/clientpositive/lateral_view_cbo.q:
##########
@@ -0,0 +1,8 @@
+--! qt:dataset:src
+--Q1
+EXPLAIN CBO SELECT myTable.myCol FROM src 
+LATERAL VIEW explode(array(1,2,3)) myTable AS myCol;

Review Comment:
   Done



##########
ql/src/test/queries/clientpositive/lateral_view_cbo.q:
##########
@@ -0,0 +1,8 @@
+--! qt:dataset:src

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1684559981

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [13 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarcloud.io/appendices/scanner-environment/)
   
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1306577534


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +125,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use empty listfor columnMappings. The return row type of the RelNode now comprises of
+    // all the fields within the UDTF, so there is no mapping from the output fields
+    // directly to the input fields anymore.
     final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
         tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
-        tfs.getColumnMappings());
+        new HashSet<>());

Review Comment:
   Done



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] zabetak commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1335516668


##########
ql/src/test/results/clientpositive/tez/tez_union_udtf.q.out:
##########
@@ -140,7 +137,7 @@ POSTHOOK: Input: default@src
 POSTHOOK: Input: default@src1
 POSTHOOK: Output: database:default
 POSTHOOK: Output: default@x
-POSTHOOK: Lineage: x.key EXPRESSION [(src)src.FieldSchema(name:key, type:string, comment:default), (src1)src1.FieldSchema(name:key, type:string, comment:default), ]

Review Comment:
   No lineage for constants is not something caused by this patch and not something that really requires a fix. For tracking purposes, I created https://issues.apache.org/jira/browse/HIVE-27726 but it doesn't require any immediate action.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1330130220


##########
ql/src/test/results/clientpositive/tez/tez_union_udtf.q.out:
##########
@@ -140,7 +137,7 @@ POSTHOOK: Input: default@src
 POSTHOOK: Input: default@src1
 POSTHOOK: Output: database:default
 POSTHOOK: Output: default@x
-POSTHOOK: Lineage: x.key EXPRESSION [(src)src.FieldSchema(name:key, type:string, comment:default), (src1)src1.FieldSchema(name:key, type:string, comment:default), ]

Review Comment:
   Upon debugging this, I noticed that the information is getting lost because the column is "key" and there is a filter that makes sure that key is always "238".  
   
   The change of making this run through CBO is changing the operator so that the expression within the select operator is now "238" instead of key, so that's why the information is getting lost.
   
   This seems to be slightly inconsistent on the lateral view side which also has the same filter.
   
   Having said all that, it doesn't look like this issue is related to this change, other than changing to CBO.  I'm not sure what the correct lineage is here, since the column will always be a constant.  But this issue is not specific to this patch, so I think we should push ahead with the patch anyway.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320427554


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveOptimizeInlineArrayTableFunctionRule.java:
##########
@@ -124,9 +125,12 @@ public void onMatch(RelOptRuleCall call) {
     RexNode newInlineCall =
         cluster.getRexBuilder().makeCall(tfs.getRowType(), inlineCall.op, newArrayCall);
 
+    // Use empty listfor columnMappings. The return row type of the RelNode now comprises of
+    // all the fields within the UDTF, so there is no mapping from the output fields
+    // directly to the input fields anymore.
     final RelNode newTableFunctionScanNode = tfs.copy(tfs.getTraitSet(),
         tfs.getInputs(), newInlineCall, tfs.getElementType(), tfs.getRowType(),
-        tfs.getColumnMappings());
+        Collections.emptySet());
 
     call.transformTo(newTableFunctionScanNode);

Review Comment:
   In my writeup in an earlier comment, I mentioned this rule as being extraneous if we go with option 1) and cause the regression with sql statements which contain  lateral view inline(array(...)).



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1320422209


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/ASTConverter.java:
##########
@@ -621,6 +644,80 @@ private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {
     }
   }
 
+  private ASTNode createASTLateralView(TableFunctionScan tfs, Schema s,
+      QueryBlockInfo tableFunctionSource, String sqAlias) {
+    // The structure of the AST LATERAL VIEW will be:
+    //
+    //   TOK_LATERAL_VIEW
+    //     TOK_SELECT
+    //       TOK_SELEXPR
+    //         TOK_FUNCTION
+    //           <udtf func>
+    //           ...
+    //         <col alias for function>
+    //         TOK_TABALIAS
+    //           <table alias for lateral view>
+
+    // set up the select for the parameters of the UDTF
+    List<ASTNode> children = new ArrayList<>();
+    // The UDTF function call within the table function scan will be of the form:
+    // lateral(my_udtf_func(...), $0, $1, ...).  For recreating the AST, we need
+    // the inner "my_udtf_func".
+    RexCall lateralCall = (RexCall) tfs.getCall();
+    RexCall call = (RexCall) lateralCall.getOperands().get(0);
+    for (RexNode rn : call.getOperands()) {
+      ASTNode expr = rn.accept(new RexVisitor(s, rn 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.
+    lateralview.add(tableFunctionSource.ast);
+
+    return lateralview.node();
+  }
+
+  /**
+   * Check to see if we can optimize out the lateral view operators
+   * We do not need to use the lateral view syntax if all of the fields
+   * selected out of the table scan come from the UDTF call.  No join
+   * is needed because all the fields come from the table level rather
+   * than the row level.
+   */

Review Comment:
   Removed



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] scarlin-cloudera commented on a diff in pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "scarlin-cloudera (via GitHub)" <gi...@apache.org>.
scarlin-cloudera commented on code in PR #4442:
URL: https://github.com/apache/hive/pull/4442#discussion_r1244464126


##########
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:
   Added comment with a newly created Jira.



-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1615148567

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [15 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1614592572

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [15 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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


[GitHub] [hive] sonarcloud[bot] commented on pull request #4442: HIVE-27399: Add support for lateral views with CBO

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4442:
URL: https://github.com/apache/hive/pull/4442#issuecomment-1599758115

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4442)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4442&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL) [18 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4442&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4442&metric=duplicated_lines_density&view=list) No Duplication information
   
   


-- 
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-unsubscribe@hive.apache.org

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


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