xiangfu0 commented on code in PR #20303:
URL: https://github.com/apache/pinot/pull/20303#discussion_r4646696561


##########
pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/utils/TypeUtils.java:
##########
@@ -18,16 +18,51 @@
  */
 package org.apache.pinot.query.runtime.operator.utils;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import java.lang.reflect.Array;
 import java.math.BigDecimal;
 import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
 import org.apache.pinot.spi.utils.ByteArray;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.spi.utils.PinotDataType;
 
 
 public class TypeUtils {
   private TypeUtils() {
   }
 
+  /// Converts a value whose logical type is `inputType` to 
`outputStoredType`. Same as [#convert(Object,
+  /// ColumnDataType)], except where the stored value alone does not say how 
to convert it:
+  /// - To STRING, a BOOLEAN reads as `true`/`false` and a TIMESTAMP as its 
timestamp text, as `CAST(x AS VARCHAR)`
+  ///   does, rather than as the stored `1`/`0` or epoch millis; an array 
reads as JSON text.
+  /// - Text to a numeric type is converted the way ingestion converts it 
([PinotDataType]). A segment can serve a key
+  ///   as STRING while the plan types it from the table's declaration, for 
example an OPEN_STRUCT key declared after
+  ///   older segments were built. Text that does not convert (`"abc"`, 
`"1.9"` or an out-of-range value for INT/LONG)
+  ///   fails with an [IllegalStateException] naming both types, rather than 
reading as a value it does not hold.
+  public static Object convert(Object value, ColumnDataType inputType, 
ColumnDataType outputStoredType) {
+    if (outputStoredType == ColumnDataType.STRING && !(value instanceof 
String)) {
+      if (inputType == ColumnDataType.BOOLEAN || inputType == 
ColumnDataType.TIMESTAMP) {
+        return inputType.convertAndFormat(value).toString();
+      }
+      if (inputType.isArray()) {
+        try {
+          return JsonUtils.objectToString(inputType.convertAndFormat(value));
+        } catch (JsonProcessingException e) {
+          throw new IllegalStateException("Cannot convert " + inputType + " to 
STRING", e);
+        }
+      }
+    }
+    if (value instanceof String && outputStoredType.isNumber()) {
+      try {
+        return outputStoredType.toPinotDataType().convert(value, 
PinotDataType.STRING);

Review Comment:
   A previously built dense segment can return the STRING `"true"` after `flag` 
is declared BOOLEAN. `SELECT v['flag']` reaches this branch with 
`outputStoredType == INT`, so `PinotDataType.STRING.toInt` calls 
`Integer.parseInt("true")` and the query fails. A timestamp string such as 
`"2024-01-01 00:00:00"` likewise reaches `Long.parseLong` for a TIMESTAMP 
declaration. Please pass the planned logical output type into the conversion so 
these values use Pinot’s boolean or timestamp parser before being written in 
their stored representation.
   
   I also executed both projections on an offline cluster at `4f936bfe22`. The 
server returned `Cannot convert STRING value 'true' to INT` for the BOOLEAN key 
and `Cannot convert STRING value '2024-01-01 00:00:00' to LONG` for the 
TIMESTAMP key.



##########
pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotItemOperator.java:
##########
@@ -0,0 +1,72 @@
+/**
+ * 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.pinot.calcite.sql.fun;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.sql.SqlCallBinding;
+import org.apache.calcite.sql.SqlOperatorBinding;
+import org.apache.calcite.sql.fun.SqlItemOperator;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
+import org.apache.calcite.sql.type.SqlSingleOperandTypeChecker;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Static;
+import org.apache.pinot.query.type.OpenStructSqlType;
+
+
+/// The SQL `ITEM` operator (`x[i]`, `m['k']`), typed for OPEN_STRUCT columns.
+///
+/// Every operand type behaves as Calcite's standard ITEM. When the operand is 
an [OpenStructSqlType] and the key is a
+/// literal, the result is the key's declared type, so `v['n'] > 50` and 
`SUM(v['n'])` are numeric when `n` is
+/// declared numeric; an undeclared key is VARCHAR. Either way the result is 
nullable, since any row may lack the key.
+/// This matches the single-stage engine, which reads a declared key with its 
declared type and an undeclared key as
+/// STRING. The key must be a literal: the leaf stage resolves it once per 
segment, so `col[otherCol]` is rejected at
+/// validation. Stateless and thread-safe.
+public class PinotItemOperator extends SqlItemOperator {
+  public static final PinotItemOperator INSTANCE = new PinotItemOperator();
+
+  private PinotItemOperator() {
+    // Calcite's ITEM is built with a single-operand checker (the operand-type 
rules for MAP, ARRAY and ROW).
+    super("ITEM", (SqlSingleOperandTypeChecker) 
SqlStdOperatorTable.ITEM.getOperandTypeChecker(), 0, false);
+  }
+
+  @Override
+  public boolean checkOperandTypes(SqlCallBinding callBinding, boolean 
throwOnFailure) {
+    if (callBinding.getOperandType(0) instanceof OpenStructSqlType && 
!callBinding.isOperandLiteral(1, false)) {

Review Comment:
   The leaf also requires the left operand of `ITEM` to be a column identifier. 
With two OPEN_STRUCT columns, `(CASE WHEN id = 0 THEN v ELSE w END)['k']` 
validates here and plans as `ITEM(CASE(...), 'k')` directly over a table scan. 
On the server, `ItemTransformFunction.init` rejects the CASE with `Map Item: 
Left operand must be an identifier`. Could we push the key read into the CASE 
branches, or reject this unsupported operand during validation with a clear 
error?
   
   I verified this on an offline cluster at `4f936bfe22` with `(CASE WHEN 
metrics['latencyMs'] = 0 THEN metrics ELSE NULL END)['latencyMs']`. EXPLAIN 
placed `ITEM(CASE(...), 'latencyMs')` directly above the table scan. Execution 
returned `Map Item: Left operand must be an identifier`.



-- 
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]


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

Reply via email to