yunfengzhou-hub commented on code in PR #27330:
URL: https://github.com/apache/flink/pull/27330#discussion_r2671378203


##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ItemAtTypeStrategy.java:
##########
@@ -33,27 +34,29 @@
 /**
  * An output type strategy for {@link BuiltInFunctionDefinitions#AT}.
  *
- * <p>Returns either the element of an {@link LogicalTypeFamily#COLLECTION} 
type or the value of
- * {@link LogicalTypeRoot#MAP}.
+ * <p>Returns either the element of an {@link LogicalTypeFamily#COLLECTION} 
type, the value of
+ * {@link LogicalTypeRoot#MAP}, or the variant itself for {@link 
LogicalTypeRoot#VARIANT}.

Review Comment:
   The returned type might not equal to the original variant in aspect of 
nullability.



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExprCodeGenerator.scala:
##########
@@ -743,7 +743,11 @@ class ExprCodeGenerator(ctx: CodeGeneratorContext, 
nullableInput: Boolean)
           case LogicalTypeRoot.ROW | LogicalTypeRoot.STRUCTURED_TYPE =>
             generateDot(ctx, operands)
 
-          case _ => throw new CodeGenException("Expect an array, a map or a 
row.")
+          case LogicalTypeRoot.VARIANT =>
+            val key = operands(1)
+            generateVariantGet(ctx, operands.head, key)

Review Comment:
   Would it be better to directly support nested field access in one codegen 
invocation? Currently this method only resolves the uppermost level of 
expressions like `v['k0']['kk1'][1]`, and leaves the rest levels to the next 
ExprCodeGenerator invocation.



##########
flink-table/flink-sql-parser/src/main/java/org/apache/calcite/sql/fun/SqlItemOperator.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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.calcite.sql.fun;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.rel.type.RelDataTypeField;
+import org.apache.calcite.sql.SqlCall;
+import org.apache.calcite.sql.SqlCallBinding;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.SqlNode;
+import org.apache.calcite.sql.SqlOperandCountRange;
+import org.apache.calcite.sql.SqlOperatorBinding;
+import org.apache.calcite.sql.SqlSpecialOperator;
+import org.apache.calcite.sql.SqlWriter;
+import org.apache.calcite.sql.parser.SqlParserPos;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlOperandCountRanges;
+import org.apache.calcite.sql.type.SqlSingleOperandTypeChecker;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.sql.type.SqlTypeUtil;
+
+import java.util.Arrays;
+
+import static java.util.Objects.requireNonNull;
+import static 
org.apache.calcite.sql.type.NonNullableAccessors.getComponentTypeOrThrow;
+import static 
org.apache.calcite.sql.validate.SqlNonNullableAccessors.getOperandLiteralValueOrThrow;
+
+/**
+ * The item operator {@code [ ... ]}, used to access a given element of an 
array, map or struct. For
+ * example, {@code myArray[3]}, {@code "myMap['foo']"}, {@code myStruct[2]} or 
{@code
+ * myStruct['fieldName']}.
+ *
+ * <p>This class was copied over from Calcite 1.39.0 version to support access 
variant
+ * (FLINK-37924).
+ *
+ * <p>Line 148, CALCITE-7325, should be removed after upgrading Calcite to 
1.42.0.

Review Comment:
   Hi @snuyanzin, do you think it would be better to update Calcite version in 
or before this PR, so that this PR could avoid adding this class? I see that 
you made the last upgrade of Calcite dependency, and that PR does seem to have 
been of great workload.
   https://github.com/apache/flink/pull/26827



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/ScalarOperatorGens.scala:
##########
@@ -1668,6 +1668,108 @@ object ScalarOperatorGens {
     generateUnaryOperatorIfNotNull(ctx, resultType, map)(_ => 
s"${map.resultTerm}.size()")
   }
 
+  def generateVariantGet(
+      ctx: CodeGeneratorContext,
+      variant: GeneratedExpression,
+      key: GeneratedExpression): GeneratedExpression = {
+    val Seq(resultTerm, nullTerm) = newNames(ctx, "result", "isNull")
+    val binaryVariantTerm = newName(ctx, "binaryVariantTerm")
+
+    val variantType = variant.resultType.asInstanceOf[VariantType]
+    val keyType = key.resultType
+
+    val variantTypeTerm = primitiveTypeTermForType(variantType)
+    val variantDefault = primitiveDefaultValue(variantType)
+    val variantTerm = variant.resultTerm
+    val keyTerm = key.resultTerm
+
+    val accessCode = if (isInteger(keyType)) {
+      generateIntegerKeyAccess(
+        variantTerm,
+        binaryVariantTerm,
+        keyTerm,
+        resultTerm,
+        nullTerm
+      )
+    } else if (isCharacterString(keyType)) {
+      generateCharacterStringKeyAccess(
+        variantTerm,
+        binaryVariantTerm,
+        keyTerm,
+        resultTerm,
+        nullTerm
+      )
+    } else {
+      throw new CodeGenException(s"Unsupported key type for variant: $keyType")
+    }
+
+    val finalCode =
+      s"""
+         |${variant.code}
+         |${key.code}
+         |boolean $nullTerm = (${variant.nullTerm}|| ${key.nullTerm});
+         |$variantTypeTerm $resultTerm = $variantDefault;
+         |if (!$nullTerm) {
+         |  $accessCode
+         |}
+      """.stripMargin
+
+    GeneratedExpression(resultTerm, nullTerm, finalCode, variantType)
+  }
+
+  private def generateCharacterStringKeyAccess(
+      variantTerm: String,
+      binaryVariantTerm: String,
+      keyTerm: String,
+      resultTerm: String,
+      nullTerm: String): String = {
+    s"""
+       |  if ($variantTerm.isObject()){
+       |    if ($variantTerm instanceof $BINARY_VARIANT) {
+       |      $BINARY_VARIANT $binaryVariantTerm = ($BINARY_VARIANT) 
$variantTerm;
+       |
+       |      String keyStr = null;
+       |      if ($keyTerm instanceof $BINARY_STRING) {
+       |       keyStr = (($BINARY_STRING) $keyTerm).toString();
+       |      } else {
+       |       keyStr = String.valueOf($keyTerm);
+       |      }
+       |
+       |      if (keyStr != null) {
+       |        $resultTerm = $binaryVariantTerm.getField(keyStr);
+       |      } else {
+       |        $nullTerm = true;
+       |      }
+       |    } else {
+       |     $nullTerm = true;
+       |    }
+       |  } else {
+       |    throw new org.apache.flink.table.api.TableRuntimeException("String 
key access on variant requires an object variant, but a non-object variant was 
provided.");
+       |  }
+    """.stripMargin
+  }
+
+  private def generateIntegerKeyAccess(
+      variantTerm: String,
+      binaryVariantTerm: String,
+      keyTerm: String,
+      resultTerm: String,
+      nullTerm: String): String = {
+    s"""
+       |  if ($variantTerm.isArray()){
+       |    if ($variantTerm instanceof $BINARY_VARIANT) {
+       |      $BINARY_VARIANT $binaryVariantTerm = ($BINARY_VARIANT) 
$variantTerm;
+       |      $resultTerm = $binaryVariantTerm.getElement((int)$keyTerm - 1);

Review Comment:
   The index should be 0 based, and no `- 1` is needed.



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/ScalarOperatorGens.scala:
##########
@@ -1668,6 +1668,108 @@ object ScalarOperatorGens {
     generateUnaryOperatorIfNotNull(ctx, resultType, map)(_ => 
s"${map.resultTerm}.size()")
   }
 
+  def generateVariantGet(
+      ctx: CodeGeneratorContext,
+      variant: GeneratedExpression,
+      key: GeneratedExpression): GeneratedExpression = {
+    val Seq(resultTerm, nullTerm) = newNames(ctx, "result", "isNull")
+    val binaryVariantTerm = newName(ctx, "binaryVariantTerm")
+
+    val variantType = variant.resultType.asInstanceOf[VariantType]
+    val keyType = key.resultType
+
+    val variantTypeTerm = primitiveTypeTermForType(variantType)
+    val variantDefault = primitiveDefaultValue(variantType)
+    val variantTerm = variant.resultTerm
+    val keyTerm = key.resultTerm
+
+    val accessCode = if (isInteger(keyType)) {
+      generateIntegerKeyAccess(
+        variantTerm,
+        binaryVariantTerm,
+        keyTerm,
+        resultTerm,
+        nullTerm
+      )
+    } else if (isCharacterString(keyType)) {
+      generateCharacterStringKeyAccess(
+        variantTerm,
+        binaryVariantTerm,
+        keyTerm,
+        resultTerm,
+        nullTerm
+      )
+    } else {
+      throw new CodeGenException(s"Unsupported key type for variant: $keyType")
+    }
+
+    val finalCode =
+      s"""
+         |${variant.code}
+         |${key.code}
+         |boolean $nullTerm = (${variant.nullTerm}|| ${key.nullTerm});
+         |$variantTypeTerm $resultTerm = $variantDefault;
+         |if (!$nullTerm) {
+         |  $accessCode
+         |}
+      """.stripMargin
+
+    GeneratedExpression(resultTerm, nullTerm, finalCode, variantType)
+  }
+
+  private def generateCharacterStringKeyAccess(
+      variantTerm: String,
+      binaryVariantTerm: String,
+      keyTerm: String,
+      resultTerm: String,
+      nullTerm: String): String = {
+    s"""
+       |  if ($variantTerm.isObject()){
+       |    if ($variantTerm instanceof $BINARY_VARIANT) {
+       |      $BINARY_VARIANT $binaryVariantTerm = ($BINARY_VARIANT) 
$variantTerm;
+       |
+       |      String keyStr = null;
+       |      if ($keyTerm instanceof $BINARY_STRING) {

Review Comment:
   It should be avoided to rely on concrete subclasses like `BinaryStringData` 
and `BinaryVariant`. Better use `StringData` and `Variant` instead.
   
   Furthermore, code like follows might get you rid of complex toString 
implementations.
   ```scala
   val fieldName = key.literalValue.get.toString
   val inputCode =
   s"""
      |$nullTerm = $inputTerm.isNull();
      |$fieldTerm = null;
      |if (!$nullTerm) {
      |  $fieldTerm = $inputTerm.getField("$fieldName");
      |}
            """.stripMargin.trim
   GeneratedExpression(fieldTerm, nullTerm, inputCode, variantType)
   ```



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to