kgyrtkirk commented on a change in pull request #970: Hive 23100
URL: https://github.com/apache/hive/pull/970#discussion_r408770800
 
 

 ##########
 File path: 
ql/src/java/org/apache/hadoop/hive/ql/parse/type/HiveFunctionHelper.java
 ##########
 @@ -0,0 +1,549 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hive.ql.parse.type;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
+import org.apache.calcite.sql.SqlBinaryOperator;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.SqlOperator;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
+import org.apache.calcite.util.Util;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.exec.FunctionInfo;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.metadata.Hive;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
+import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRexExecutorImpl;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveExtractDate;
+import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFloorDate;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveToDateSqlOperator;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveToUnixTimestampSqlOperator;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveUnixTimestampSqlOperator;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.translator.ExprNodeConverter;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.translator.SqlFunctionConverter;
+import org.apache.hadoop.hive.ql.optimizer.calcite.translator.RexNodeConverter;
+import org.apache.hadoop.hive.ql.optimizer.calcite.translator.TypeConverter;
+import org.apache.hadoop.hive.ql.parse.SemanticAnalyzer;
+import org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.GenericUDAFInfo;
+import org.apache.hadoop.hive.ql.parse.SemanticException;
+import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
+import org.apache.hadoop.hive.ql.plan.ExprNodeDescUtils;
+import org.apache.hadoop.hive.ql.plan.GroupByDesc;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.Mode;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBaseBinary;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBaseCompare;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBetween;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFIn;
+import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
+import 
org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
+import 
org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
+import 
org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
+import 
org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils.PrimitiveGrouping;
+import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Function helper for Hive.
+ */
+public class HiveFunctionHelper implements FunctionHelper {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(HiveFunctionHelper.class);
+
+  private final RexBuilder rexBuilder;
+  private final int maxNodesForInToOrTransformation;
+
+  public HiveFunctionHelper(RexBuilder rexBuilder) {
+    this.rexBuilder = rexBuilder;
+    try {
+      this.maxNodesForInToOrTransformation = HiveConf.getIntVar(
+          Hive.get().getConf(), 
HiveConf.ConfVars.HIVEOPT_TRANSFORM_IN_MAXNODES);
+    } catch (HiveException e) {
+      throw new IllegalStateException(e);
+    }
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public FunctionInfo getFunctionInfo(String functionText)
+      throws SemanticException {
+    return FunctionRegistry.getFunctionInfo(functionText);
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public RelDataType getReturnType(FunctionInfo fi, List<RexNode> inputs)
+      throws SemanticException {
+    // 1) Gather inputs
+    ObjectInspector[] inputsOIs = new ObjectInspector[inputs.size()];
+    for (int i = 0; i < inputsOIs.length; i++) {
+      inputsOIs[i] = createObjectInspector(inputs.get(i));
+    }
+    // 2) Initialize and obtain return type
+    ObjectInspector oi = fi.getGenericUDF() != null ?
+        fi.getGenericUDF().initializeAndFoldConstants(inputsOIs) :
+        fi.getGenericUDTF().initialize(inputsOIs);
+    // 3) Convert to RelDataType
+    return TypeConverter.convert(
+        TypeInfoUtils.getTypeInfoFromObjectInspector(oi), 
rexBuilder.getTypeFactory());
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public List<RexNode> convertInputs(FunctionInfo fi, List<RexNode> inputs,
+      RelDataType returnType)
+      throws SemanticException {
+    // 1) Obtain UDF
+    final GenericUDF genericUDF = fi.getGenericUDF();
+    final TypeInfo typeInfo = TypeConverter.convert(returnType);
+    TypeInfo targetType = null;
+
+    boolean isNumeric = genericUDF instanceof GenericUDFBaseBinary
+        && typeInfo.getCategory() == Category.PRIMITIVE
+        && PrimitiveGrouping.NUMERIC_GROUP == 
PrimitiveObjectInspectorUtils.getPrimitiveGrouping(((PrimitiveTypeInfo) 
typeInfo).getPrimitiveCategory());
+    boolean isCompare = !isNumeric && genericUDF instanceof 
GenericUDFBaseCompare;
+    boolean isBetween = !isNumeric && genericUDF instanceof GenericUDFBetween;
+    boolean isIN = !isNumeric && genericUDF instanceof GenericUDFIn;
+
+    if (isNumeric) {
+      targetType = typeInfo;
+    } else if (genericUDF instanceof GenericUDFBaseCompare) {
+      targetType = FunctionRegistry.getCommonClassForComparison(
+          TypeConverter.convert(inputs.get(0).getType()),
+          TypeConverter.convert(inputs.get(1).getType()));
+    } else if (genericUDF instanceof GenericUDFBetween) {
+      assert inputs.size() == 4;
+      // We skip first child as is not involved (is the revert boolean)
+      // The target type needs to account for all 3 operands
+      targetType = FunctionRegistry.getCommonClassForComparison(
+          TypeConverter.convert(inputs.get(1).getType()),
+          FunctionRegistry.getCommonClassForComparison(
+              TypeConverter.convert(inputs.get(2).getType()),
+              TypeConverter.convert(inputs.get(3).getType())));
+    } else if (genericUDF instanceof GenericUDFIn) {
+      // We're only considering the first element of the IN list for the type
+      assert inputs.size() > 1;
+      targetType = FunctionRegistry.getCommonClassForComparison(
+          TypeConverter.convert(inputs.get(0).getType()),
+          TypeConverter.convert(inputs.get(1).getType()));
+    }
+
+    if (targetType != null) {
+      List<RexNode> newInputs = new ArrayList<>();
+      // Convert inputs if needed
+      for (int i = 0; i < inputs.size(); ++i) {
+        RexNode input = inputs.get(i);
+        TypeInfo inputTypeInfo = TypeConverter.convert(input.getType());
+        RexNode tmpExprNode = input;
+        if (TypeInfoUtils.isConversionRequiredForComparison(targetType, 
inputTypeInfo)) {
+          if (isIN || isCompare) {
+            // For IN and compare, we will convert requisite children
+            tmpExprNode = convert(targetType, input);
+          } else if (isBetween) {
+            // For BETWEEN skip the first child (the revert boolean)
+            if (i > 0) {
+              tmpExprNode = convert(targetType, input);
+            }
+          } else if (isNumeric) {
+            // For numeric, we'll do minimum necessary cast - if we cast to 
the type
+            // of expression, bad things will happen.
+            PrimitiveTypeInfo minArgType = 
ExprNodeDescUtils.deriveMinArgumentCast(inputTypeInfo, targetType);
+            tmpExprNode = convert(minArgType, input);
+          } else {
+            throw new AssertionError("Unexpected " + targetType + " - not a 
numeric op or compare");
+          }
+        }
+
+        newInputs.add(tmpExprNode);
+      }
+      return newInputs;
+    }
+    return inputs;
+  }
+
+  private RexNode convert(TypeInfo targetType, RexNode input) throws 
SemanticException {
+    if (targetType.getCategory() == Category.PRIMITIVE) {
+      return RexNodeTypeCheck.getExprNodeDefaultExprProcessor(rexBuilder)
+          .createConversionCast(input, (PrimitiveTypeInfo) targetType);
+    } else {
+      StructTypeInfo structTypeInfo = (StructTypeInfo) targetType; // struct
+      RexCall call = (RexCall) input;
+      List<RexNode> exprNodes = new ArrayList<>();
+      for (int j = 0; j < structTypeInfo.getAllStructFieldTypeInfos().size(); 
j++) {
+        exprNodes.add(
+            convert(
+                structTypeInfo.getAllStructFieldTypeInfos().get(j), 
call.getOperands().get(j)));
+      }
+      return rexBuilder.makeCall(SqlStdOperatorTable.ROW, exprNodes);
+    }
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public RexNode getExpression(String functionText, FunctionInfo fi,
+      List<RexNode> inputs, RelDataType returnType)
+      throws SemanticException {
+    // See if this is an explicit cast.
+    RexNode expr = RexNodeConverter.handleExplicitCast(
 
 Review comment:
   I think it would be probably cleaner to create a RexNodeConverter; and pass 
a rexBuilder to it
   after that :  remove the static from those methods - and the rexBuilder 
passed to every invocation of 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.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to