xiangfu0 commented on code in PR #20303: URL: https://github.com/apache/pinot/pull/20303#discussion_r4649038216
########## 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)) { + if (throwOnFailure) { + throw callBinding.getValidator().newValidationError(callBinding.operand(1), + Static.RESOURCE.argumentMustBeLiteral(getName())); + } + return false; + } + return super.checkOperandTypes(callBinding, throwOnFailure); + } + + @Override + public RelDataType inferReturnType(SqlOperatorBinding opBinding) { + if (opBinding.getOperandType(0) instanceof OpenStructSqlType openStruct) { + RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); + String key = opBinding.isOperandLiteral(1, false) ? opBinding.getOperandLiteralValue(1, String.class) : null; + RelDataType declared = key == null ? null : openStruct.getDeclaredKeyType(key); + RelDataType type = declared != null ? declared : typeFactory.createSqlType(SqlTypeName.VARCHAR); Review Comment: Fixed in ca5f62f636. The broker now sends the planned key type to the server. A matching segment can still use its per-key index. A mismatched segment converts the key before filtering or sorting. On the original offline fixture, the numeric filter now returns 997 rows, the text filter returns 776, and the first three numeric keys are `[0, 1, 2]`. The committed offline and realtime suites also check lexicographic ordering of the integers 2 and 10. ########## pinot-query-planner/src/main/java/org/apache/pinot/query/type/OpenStructSqlType.java: ########## @@ -0,0 +1,77 @@ +/** + * 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.query.type; + +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import javax.annotation.Nullable; +import org.apache.calcite.rel.type.RelDataType; +import org.apache.calcite.sql.type.MapSqlType; + + +/// Calcite type of an OPEN_STRUCT column. +/// +/// It is a `MAP<VARCHAR, VARCHAR>` so that `col['key']` validates as a map lookup, and it carries the column's +/// declared child field specs as Calcite types. [PinotItemOperator] uses them to type a key read: a declared key has +/// its declared type, an undeclared key is VARCHAR (the single-stage engine reads it as STRING). Selecting the whole +/// column returns JSON text, as in the single-stage engine. +/// +/// The declared types are part of the digest, so two OPEN_STRUCT columns with different declarations are different +/// types after canonicalization. Instances are immutable. +public class OpenStructSqlType extends MapSqlType { + private final Map<String, RelDataType> _declaredKeyTypes; + + public OpenStructSqlType(RelDataType keyType, RelDataType valueType, boolean isNullable, + Map<String, RelDataType> declaredKeyTypes) { + super(keyType, valueType, isNullable); + _declaredKeyTypes = Collections.unmodifiableMap(new TreeMap<>(declaredKeyTypes)); + // MapSqlType computed the digest before the declared types were set; include them now. + computeDigest(); + } + + /// Declared type of `key`, or null when the key is not declared. + @Nullable + public RelDataType getDeclaredKeyType(String key) { + return _declaredKeyTypes.get(key); + } + + public Map<String, RelDataType> getDeclaredKeyTypes() { + return _declaredKeyTypes; + } + + @Override + protected void generateTypeString(StringBuilder sb, boolean withDetail) { + sb.append("OPEN_STRUCT"); + // Null while the super constructor computes its first digest. + if (_declaredKeyTypes != null && !_declaredKeyTypes.isEmpty()) { + sb.append('('); + boolean first = true; + for (Map.Entry<String, RelDataType> entry : _declaredKeyTypes.entrySet()) { + if (!first) { + sb.append(", "); + } + first = false; + sb.append(entry.getKey()).append(' ') Review Comment: Fixed in ca5f62f636. Key names are quoted and escaped in the Calcite digest. Structural equality and hashing include the declared key types. The regression creates both colliding schemas in the same type factory and checks that each lookup retains its own declaration. ########## 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: Fixed in ca5f62f636. The server now converts each present value to the planned logical type before returning its stored representation. The offline regression read `"true"` as BOOLEAN true and `"2024-01-01 00:00:00"` as a TIMESTAMP from dense STRING keys. Missing keys also retain SQL nulls or the target defaults according to the null-handling setting. ########## pinot-query-planner/src/test/java/org/apache/pinot/query/OpenStructMultiStagePlanningTest.java: ########## @@ -0,0 +1,189 @@ +/** + * 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.query; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.calcite.rel.type.RelDataType; +import org.apache.calcite.sql.type.SqlTypeName; +import org.apache.pinot.common.utils.DataSchema; +import org.apache.pinot.common.utils.DataSchema.ColumnDataType; +import org.apache.pinot.query.planner.physical.DispatchableSubPlan; +import org.apache.pinot.query.type.OpenStructSqlType; +import org.apache.pinot.spi.data.ComplexFieldSpec; +import org.apache.pinot.spi.data.DimensionFieldSpec; +import org.apache.pinot.spi.data.FieldSpec; +import org.apache.pinot.spi.data.FieldSpec.DataType; +import org.apache.pinot.spi.data.Schema; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.expectThrows; + + +/// OPEN_STRUCT columns in the multi-stage engine: a key read (`v['n']`) is typed by the key's declared child field +/// spec and falls back to VARCHAR for an undeclared key, matching what the leaf stage returns for it; selecting the +/// whole column is JSON text, as in the single-stage engine; and queries that never touch the column still plan. +public class OpenStructMultiStagePlanningTest extends QueryEnvironmentTestBase { + private QueryEnvironment _env; + + @BeforeClass + public void setUpOpenStructTable() { + Map<String, Schema> schemas = new HashMap<>(TABLE_SCHEMAS); + Schema schema = getSchemaBuilder("d").build(); + Map<String, FieldSpec> declared = Map.of("n", new DimensionFieldSpec("n", DataType.LONG, true), + "price", new DimensionFieldSpec("price", DataType.DOUBLE, true), + "inner", new ComplexFieldSpec("inner", DataType.OPEN_STRUCT, true, Map.of())); + schema.addField(new ComplexFieldSpec("v", DataType.OPEN_STRUCT, true, declared)); + schemas.put("d", schema); + // Same column, declaring `n` with the same type and `price` with another. + Schema other = getSchemaBuilder("d2").build(); + other.addField(new ComplexFieldSpec("v", DataType.OPEN_STRUCT, true, + Map.of("n", new DimensionFieldSpec("n", DataType.LONG, true), + "price", new DimensionFieldSpec("price", DataType.STRING, true)))); + schemas.put("d2", other); + _env = getQueryEnvironment(3, 1, 2, schemas, SERVER1_SEGMENTS, SERVER2_SEGMENTS, PARTITIONED_SEGMENTS_MAP); + } + + private RelDataType validatedRowType(String sql) { + try (QueryEnvironment.CompiledQuery query = _env.compile(sql)) { + return query.getRelRoot().validatedRowType; + } + } + + @Test + public void testDeclaredKeyIsTypedByItsChildFieldSpec() { + RelDataType rowType = validatedRowType("SELECT v['n'], v['price'] FROM d"); + assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), SqlTypeName.BIGINT); + assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(), SqlTypeName.DOUBLE); + assertTrue(rowType.getFieldList().get(0).getType().isNullable()); + } + + @Test + public void testUndeclaredKeyAndNestedPathAreVarchar() { + RelDataType rowType = validatedRowType("SELECT v['name'], v['o.z'] FROM d"); + assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), SqlTypeName.VARCHAR); + assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(), SqlTypeName.VARCHAR); + } + + @Test + public void testNumericFilterAndAggregationOnDeclaredKeyPlan() { + RelDataType rowType = validatedRowType("SELECT SUM(v['n']), COUNT(*) FROM d WHERE v['n'] > 50"); + assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), SqlTypeName.BIGINT); + assertNotNull(_env.planQuery("SELECT SUM(v['n']), COUNT(*) FROM d WHERE v['n'] > 50")); + assertNotNull(_env.planQuery("SELECT CAST(v['name'] AS BIGINT) FROM d")); + } + + @Test + public void testWholeColumnIsJsonText() { + DispatchableSubPlan plan = _env.planQuery("SELECT col1, v FROM d"); + DataSchema schema = plan.getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema(); + assertEquals(schema.getColumnDataTypes()[1], ColumnDataType.JSON); + } + + @Test + public void testComplexDeclaredChildIsVarchar() { + RelDataType rowType = validatedRowType("SELECT v['inner'] FROM d"); + assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), SqlTypeName.VARCHAR); + } + + /// A UNION ALL of two OPEN_STRUCT columns stays OPEN_STRUCT: the whole column is still JSON, and a key both sides + /// declare with the same type keeps it while a key they declare differently is VARCHAR. + @Test + public void testUnionAllKeepsOpenStruct() { + DispatchableSubPlan plan = _env.planQuery("SELECT v FROM d UNION ALL SELECT v FROM d WHERE col3 > 0"); + DataSchema schema = plan.getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema(); + assertEquals(schema.getColumnDataTypes()[0], ColumnDataType.JSON); + // d2 has no segments, so only validate across the two declarations. + String union = "(SELECT v FROM d UNION ALL SELECT v FROM d2)"; + assertTrue(validatedRowType("SELECT v FROM " + union).getFieldList().get(0).getType() + instanceof OpenStructSqlType); + RelDataType rowType = validatedRowType("SELECT u.v['n'], u.v['price'] FROM " + union + " AS u"); + assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(), SqlTypeName.BIGINT); + assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(), SqlTypeName.VARCHAR); + } + + @Test + public void testCaseAndCoalesceWithNullKeepJson() { + for (String sql : List.of("SELECT CASE WHEN col3 > 0 THEN v ELSE NULL END FROM d", + "SELECT COALESCE(v, NULL) FROM d")) { + DataSchema schema = + _env.planQuery(sql).getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema(); + assertEquals(schema.getColumnDataTypes()[0], ColumnDataType.JSON, sql); Review Comment: Fixed in ca5f62f636. The leaf CASE and COALESCE functions read an OPEN_STRUCT operand as document text. The multi-stage output schema retains JSON. The offline and realtime tests execute both CASE branches and check the document and SQL NULL with null handling enabled. ########## 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: Fixed in ca5f62f636. The planner now rejects a computed OPEN_STRUCT operand before dispatch with `OPEN_STRUCT key lookup requires a column reference`. The planner regression covers both a direct CASE and a subquery alias. The original offline query now returns the broker planning error. -- 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]
