This is an automated email from the ASF dual-hosted git repository.
yashmayya pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new b3ab87fd8ad Add an option to resolve GROUP BY names to SELECT aliases
before columns in MSE (#20091)
b3ab87fd8ad is described below
commit b3ab87fd8ad0f0524c93385736becb22b4fe17c3
Author: Gonzalo Ortiz Jaureguizar <[email protected]>
AuthorDate: Wed Nov 18 01:18:55 2026 +0100
Add an option to resolve GROUP BY names to SELECT aliases before columns in
MSE (#20091)
---
.../MultiStageBrokerRequestHandler.java | 11 +-
.../apache/pinot/common/metrics/BrokerMeter.java | 10 ++
.../common/utils/config/QueryOptionsUtils.java | 6 +
.../api/resources/PinotQueryResource.java | 41 +++++-
.../api/resources/PinotQueryResourceTest.java | 60 ++++++++
.../org/apache/pinot/query/QueryEnvironment.java | 29 ++++
.../apache/pinot/query/context/PlannerContext.java | 9 +-
.../GroupByAliasShadowedByColumnException.java | 37 +++++
.../org/apache/pinot/query/validate/Validator.java | 155 ++++++++++++++++++++-
.../GroupByAliasShadowedByColumnExceptionTest.java | 72 ++++++++++
.../GroupByAliasShadowedByColumnMeterTest.java | 142 +++++++++++++++++++
.../src/test/resources/queries/GroupByPlans.json | 125 +++++++++++++++++
.../src/test/resources/queries/Aggregates.json | 72 ++++++++++
.../apache/pinot/spi/utils/CommonConstants.java | 17 +++
14 files changed, 774 insertions(+), 12 deletions(-)
diff --git
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
index 4486b199bd9..410570d36fd 100644
---
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
+++
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
@@ -603,6 +603,9 @@ public class MultiStageBrokerRequestHandler extends
BaseBrokerRequestHandler {
int sealedInListThreshold = _config.getProperty(
CommonConstants.Broker.CONFIG_OF_SEALED_IN_LIST_THRESHOLD,
CommonConstants.Broker.DEFAULT_SEALED_IN_LIST_THRESHOLD);
+ boolean preferSelectAliasInGroupBy = _config.getProperty(
+ CommonConstants.Broker.CONFIG_OF_PREFER_SELECT_ALIAS_IN_GROUP_BY,
+ CommonConstants.Broker.DEFAULT_PREFER_SELECT_ALIAS_IN_GROUP_BY);
boolean defaultUnnestColumnPruning = _config.getProperty(
CommonConstants.Broker.CONFIG_OF_UNNEST_COLUMN_PRUNING,
CommonConstants.Broker.DEFAULT_UNNEST_COLUMN_PRUNING);
@@ -642,6 +645,8 @@ public class MultiStageBrokerRequestHandler extends
BaseBrokerRequestHandler {
.defaultDisabledPlannerRules(_defaultDisabledPlannerRules)
.defaultSortExchangeCopyLimit(sortExchangeCopyThreshold)
.defaultSealedInListThreshold(sealedInListThreshold)
+ .defaultPreferSelectAliasInGroupBy(preferSelectAliasInGroupBy)
+ .meterGroupByAliasShadowedByColumn(true)
.build();
}
@@ -757,8 +762,10 @@ public class MultiStageBrokerRequestHandler extends
BaseBrokerRequestHandler {
try {
SqlNodeAndOptions sqlNodeAndOptions =
CalciteSqlParser.compileToSqlNodeAndOptions(subquery);
RequestUtils.setOptions(sqlNodeAndOptions, queryOptions);
- QueryEnvironment queryEnv = new QueryEnvironment(
- getQueryEnvConf(httpHeaders, sqlNodeAndOptions.getOptions(),
requestId), _multiClusterRoutingContext);
+ // The subquery is compiled again later, either on its own or inside the
query, so do not mark the meter here
+ ImmutableQueryEnvironment.Config queryEnvConf =
getQueryEnvConf(httpHeaders, sqlNodeAndOptions.getOptions(),
+ requestId).withMeterGroupByAliasShadowedByColumn(false);
+ QueryEnvironment queryEnv = new QueryEnvironment(queryEnvConf,
_multiClusterRoutingContext);
queryEnv.validate(sqlNodeAndOptions);
return true;
} catch (RuntimeException e) {
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
index cfd1a6b5cbe..b1fdaa2b3c6 100644
---
a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
+++
b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
@@ -275,6 +275,16 @@ public class BrokerMeter implements AbstractMetrics.Meter {
/// For each query with at least one window function, this meter is
increased as many times as window functions in the
/// query.
public static final BrokerMeter WINDOW_COUNT = create("WINDOW_COUNT",
"queries", true);
+ /// How many multi-stage queries group by a name that is both a column and
the alias of a different `SELECT`
+ /// expression, as in `SELECT CASE WHEN c = 'a' THEN 'x' ELSE c END AS c,
COUNT(*) FROM t GROUP BY c`.
+ ///
+ /// Since Calcite 1.42 (CALCITE-7052) such a name resolves to the column.
Before, it resolved to the alias. The query
+ /// can then fail with `Expression '...' is not being grouped` or return
different groups. The broker config
+ /// `pinot.broker.multistage.prefer.select.alias.in.group.by` and the query
option `preferSelectAliasInGroupBy`
+ /// restore the old resolution. This meter is marked at most once per query,
whether that option is set or not, and
+ /// also when the query then fails.
+ public static final BrokerMeter
QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN =
+ create("QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN", "queries",
true);
public static final BrokerMeter MSE_STAGES_STARTED =
create("MSE_STAGES_STARTED", "stages", true);
public static final BrokerMeter MSE_STAGES_COMPLETED =
create("MSE_STAGES_COMPLETED", "stages", true);
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
index eaf8d981edc..5ca41c0810e 100644
---
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
+++
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
@@ -1147,4 +1147,10 @@ public class QueryOptionsUtils {
uncheckedParseInt(QueryOptionKey.SEALED_IN_LIST_THRESHOLD, threshold
!= null ? threshold.trim() : null);
return value != null ? value : defaultValue;
}
+
+ /// Returns the [QueryOptionKey#PREFER_SELECT_ALIAS_IN_GROUP_BY] option, or
`defaultValue` when the option is not set.
+ public static boolean isPreferSelectAliasInGroupBy(Map<String, String>
options, boolean defaultValue) {
+ String option =
options.get(QueryOptionKey.PREFER_SELECT_ALIAS_IN_GROUP_BY);
+ return option != null ? Boolean.parseBoolean(option) : defaultValue;
+ }
}
diff --git
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotQueryResource.java
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotQueryResource.java
index 1aea07566b2..7536e7b6360 100644
---
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotQueryResource.java
+++
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotQueryResource.java
@@ -86,6 +86,7 @@ import org.apache.pinot.core.auth.TargetType;
import org.apache.pinot.core.query.executor.sql.SqlQueryExecutor;
import org.apache.pinot.query.QueryEnvironment;
import org.apache.pinot.query.parser.utils.ParserUtils;
+import org.apache.pinot.query.validate.GroupByAliasShadowedByColumnException;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.data.LogicalTableConfig;
import org.apache.pinot.spi.data.Schema;
@@ -642,10 +643,23 @@ public class PinotQueryResource {
private List<String> getTableNames(String query, SqlNodeAndOptions
sqlNodeAndOptions, String database) {
QueryEnvironment queryEnvironment =
new QueryEnvironment(database,
_pinotHelixResourceManager.getTableCache(), null);
- List<String> tableNames;
-
- try (QueryEnvironment.CompiledQuery compiledQuery =
queryEnvironment.compile(query, sqlNodeAndOptions)) {
- tableNames = new ArrayList<>(compiledQuery.getTableNames());
+ try {
+ try {
+ return compileTableNames(queryEnvironment, query, sqlNodeAndOptions);
+ } catch (GroupByAliasShadowedByColumnException e) {
+ if
(sqlNodeAndOptions.getOptions().containsKey(QueryOptionKey.PREFER_SELECT_ALIAS_IN_GROUP_BY))
{
+ throw e;
+ }
+ // The controller does not read the broker config
CONFIG_OF_PREFER_SELECT_ALIAS_IN_GROUP_BY, so a query that
+ // is valid on the broker can fail here. Table names do not depend on
how GROUP BY names resolve, so retry
+ // with the option set and let the broker validate the query with its
own config.
+ try {
+ return compileTableNames(queryEnvironment, query,
preferSelectAliasInGroupBy(query, sqlNodeAndOptions));
+ } catch (Exception retryException) {
+ e.addSuppressed(retryException);
+ throw e;
+ }
+ }
} catch (QueryException e) {
if (e.getErrorCode() != QueryErrorCode.UNKNOWN) {
throw e;
@@ -655,7 +669,24 @@ public class PinotQueryResource {
} catch (Exception e) {
throw QueryErrorCode.SQL_PARSING.asException("Unable to find table for
this query", e);
}
- return tableNames;
+ }
+
+ /// Returns the query parsed again, with the options of `sqlNodeAndOptions`,
which include the options of the request,
+ /// and with [QueryOptionKey#PREFER_SELECT_ALIAS_IN_GROUP_BY] set. The query
is parsed again because the validation
+ /// modifies the parsed query.
+ @VisibleForTesting
+ static SqlNodeAndOptions preferSelectAliasInGroupBy(String query,
SqlNodeAndOptions sqlNodeAndOptions) {
+ Map<String, String> options = new
HashMap<>(sqlNodeAndOptions.getOptions());
+ options.put(QueryOptionKey.PREFER_SELECT_ALIAS_IN_GROUP_BY, "true");
+ SqlNodeAndOptions reparsed =
CalciteSqlParser.compileToSqlNodeAndOptions(query);
+ return new SqlNodeAndOptions(reparsed.getSqlNode(), reparsed.getSqlType(),
options);
+ }
+
+ private static List<String> compileTableNames(QueryEnvironment
queryEnvironment, String query,
+ SqlNodeAndOptions sqlNodeAndOptions) {
+ try (QueryEnvironment.CompiledQuery compiledQuery =
queryEnvironment.compile(query, sqlNodeAndOptions)) {
+ return new ArrayList<>(compiledQuery.getTableNames());
+ }
}
private List<String> getInstanceIds(String query, List<String> tableNames,
String database) {
diff --git
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotQueryResourceTest.java
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotQueryResourceTest.java
index c961f42aa78..f7d3b0724cf 100644
---
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotQueryResourceTest.java
+++
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotQueryResourceTest.java
@@ -21,6 +21,7 @@ package org.apache.pinot.controller.api.resources;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -31,6 +32,7 @@ import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.apache.pinot.common.auth.BasicAuthTokenUtils;
+import org.apache.pinot.common.config.provider.StaticTableCache;
import org.apache.pinot.common.config.provider.TableCache;
import org.apache.pinot.common.response.broker.BrokerResponseNative;
import org.apache.pinot.common.utils.config.QueryOptionsUtils;
@@ -45,6 +47,8 @@ import
org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
import org.apache.pinot.core.auth.Actions;
import org.apache.pinot.core.auth.TargetType;
import org.apache.pinot.core.query.executor.sql.SqlQueryExecutor;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec;
import org.apache.pinot.spi.data.LogicalTableConfig;
import org.apache.pinot.spi.data.PhysicalTableConfig;
import org.apache.pinot.spi.data.Schema;
@@ -52,6 +56,7 @@ import org.apache.pinot.spi.env.PinotConfiguration;
import org.apache.pinot.spi.exception.QueryErrorCode;
import org.apache.pinot.spi.utils.CommonConstants;
import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
import org.apache.pinot.sql.parsers.SqlNodeAndOptions;
import org.apache.pinot.sql.parsers.dml.DataManipulationStatement;
import org.apache.pinot.sql.parsers.dml.DataManipulationStatementParser;
@@ -75,6 +80,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotSame;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.expectThrows;
@@ -786,6 +792,60 @@ public class PinotQueryResourceTest {
Assert.assertTrue(response.contains("useMultistageEngine"), response);
}
+ @DataProvider
+ public Object[][] groupByAliasQueries() {
+ String query = "SELECT col2 AS col1, COUNT(*) FROM a GROUP BY col1";
+ return new Object[][]{
+ // Valid on a broker with CONFIG_OF_PREFER_SELECT_ALIAS_IN_GROUP_BY:
the controller finds the tables and the
+ // query reaches broker selection, which fails because no table exists
in the cluster
+ {"SET useMultistageEngine = 'true'; " + query,
QueryErrorCode.TABLE_DOES_NOT_EXIST},
+ // The query option is set explicitly, so the controller does not retry
+ {"SET useMultistageEngine = 'true'; SET preferSelectAliasInGroupBy =
false; " + query,
+ QueryErrorCode.QUERY_VALIDATION},
+ // Invalid with or without the option
+ {"SET useMultistageEngine = 'true'; SELECT col2, COUNT(*) FROM a GROUP
BY col1",
+ QueryErrorCode.QUERY_VALIDATION},
+ };
+ }
+
+ @Test(dataProvider = "groupByAliasQueries")
+ public void testMultiStageTableNamesIgnoreHowGroupByNamesResolve(String sql,
QueryErrorCode expectedError) {
+ Schema schema = new Schema.SchemaBuilder().setSchemaName("a")
+ .addSingleValueDimension("col1", FieldSpec.DataType.STRING)
+ .addSingleValueDimension("col2", FieldSpec.DataType.STRING)
+ .build();
+ TableCache tableCache = new StaticTableCache(
+ List.of(new
TableConfigBuilder(TableType.OFFLINE).setTableName("a").build()),
List.of(schema), null, false);
+ when(_resourceManager.getTableCache()).thenReturn(tableCache);
+ when(_resourceManager.getActualTableName(any(),
any())).then(AdditionalAnswers.returnsFirstArg());
+
when(_controllerConf.getProperty(eq(CommonConstants.Helix.CONFIG_OF_MULTI_STAGE_ENGINE_ENABLED),
+ any(Boolean.class))).thenReturn(true);
+ AccessControl accessControl = mock(AccessControl.class);
+ when(accessControl.hasAccess(any(AccessType.class), any(),
any())).thenReturn(true);
+ when(_accessControlFactory.create()).thenReturn(accessControl);
+
+ String response =
streamingOutputToString(_pinotQueryResource.handleGetSql(sql, null, null,
null));
+
+ assertTrue(response.contains("\"errorCode\":" + expectedError.getId()),
response);
+ }
+
+ @Test
+ public void testRetryWithSelectAliasKeepsRequestOptions() {
+ String query = "SET timeoutMs = 1000; SELECT col2 AS col1, COUNT(*) FROM a
GROUP BY col1";
+ SqlNodeAndOptions original = RequestUtils.parseQuery(query);
+ RequestUtils.setOptions(original,
Map.of(CommonConstants.Broker.Request.QueryOptionKey.USE_MULTISTAGE_ENGINE,
+ "true"));
+ Map<String, String> originalOptions = Map.copyOf(original.getOptions());
+
+ SqlNodeAndOptions retry =
PinotQueryResource.preferSelectAliasInGroupBy(query, original);
+
+ Map<String, String> expectedOptions = new HashMap<>(originalOptions);
+
expectedOptions.put(CommonConstants.Broker.Request.QueryOptionKey.PREFER_SELECT_ALIAS_IN_GROUP_BY,
"true");
+ assertEquals(retry.getOptions(), expectedOptions);
+ assertEquals(original.getOptions(), originalOptions, "The retry must not
change the original options");
+ assertNotSame(retry.getSqlNode(), original.getSqlNode(), "The retry must
use a new parsed query");
+ }
+
@DataProvider
public Object[][] logicalTablePhysicalTables() {
return new Object[][]{
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
index 95e9b4f102e..3ffc2921385 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
@@ -97,6 +97,7 @@ import org.apache.pinot.query.planner.spi.Phase;
import org.apache.pinot.query.routing.WorkerManager;
import org.apache.pinot.query.type.TypeFactory;
import org.apache.pinot.query.validate.BytesCastVisitor;
+import org.apache.pinot.query.validate.GroupByAliasShadowedByColumnException;
import org.apache.pinot.query.validate.RowExpressionValidationVisitor;
import org.apache.pinot.spi.exception.QueryErrorCode;
import org.apache.pinot.spi.exception.QueryException;
@@ -442,6 +443,19 @@ public class QueryEnvironment {
/// may be slightly different. For example, a function call may have its
arguments casted to the correct type (only
/// in case it was legal to apply an automatic cast for these types!).
private SqlNode validate(SqlNode sqlNode, PlannerContext plannerContext) {
+ try {
+ return validateAndClassifyErrors(sqlNode, plannerContext);
+ } catch (QueryException e) {
+ if (e.getErrorCode() == QueryErrorCode.QUERY_VALIDATION
+ &&
plannerContext.getValidator().isGroupByNameResolvedToShadowedColumn()) {
+ // Lets callers retry with preferSelectAliasInGroupBy
+ throw new GroupByAliasShadowedByColumnException(e);
+ }
+ throw e;
+ }
+ }
+
+ private SqlNode validateAndClassifyErrors(SqlNode sqlNode, PlannerContext
plannerContext) {
try {
SqlNode validated = plannerContext.getValidator().validate(sqlNode);
if (!validated.getKind().belongsTo(SqlKind.QUERY)) {
@@ -982,6 +996,21 @@ public class QueryEnvironment {
default int defaultSealedInListThreshold() {
return CommonConstants.Broker.DEFAULT_SEALED_IN_LIST_THRESHOLD;
}
+
+ /// See
[CommonConstants.Broker#CONFIG_OF_PREFER_SELECT_ALIAS_IN_GROUP_BY]. Can be
overridden per query with
+ ///
[CommonConstants.Broker.Request.QueryOptionKey#PREFER_SELECT_ALIAS_IN_GROUP_BY].
+ @Value.Default
+ default boolean defaultPreferSelectAliasInGroupBy() {
+ return CommonConstants.Broker.DEFAULT_PREFER_SELECT_ALIAS_IN_GROUP_BY;
+ }
+
+ /// Whether the validator marks
`BrokerMeter.QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN`. Only the broker
that
+ /// runs multi-stage queries turns it on. Other users of the validator,
like the single-stage paths that compile a
+ /// query only to check it or to get its schema, and the controller, must
not change the meter.
+ @Value.Default
+ default boolean meterGroupByAliasShadowedByColumn() {
+ return false;
+ }
}
/// A query that have been parsed, validates, transformed into a [RelNode]
and optimized with Calcite.
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
index 33f95acc16f..811ce0040d3 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
@@ -32,7 +32,6 @@ import org.apache.calcite.prepare.Prepare;
import org.apache.calcite.rel.RelDistributionTraitDef;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.sql.SqlExplainFormat;
-import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.tools.FrameworkConfig;
import org.apache.pinot.calcite.rex.SearchSealer;
import org.apache.pinot.common.utils.config.QueryOptionsUtils;
@@ -52,7 +51,7 @@ import org.apache.pinot.query.validate.Validator;
public class PlannerContext implements AutoCloseable, Context {
private final PlannerImpl _planner;
- private final SqlValidator _validator;
+ private final Validator _validator;
private final RelOptPlanner _relOptPlanner;
private final LogicalPlanner _relTraitPlanner;
@@ -69,7 +68,9 @@ public class PlannerContext implements AutoCloseable, Context
{
HepProgram optProgram, HepProgram traitProgram, Map<String, String>
options, QueryEnvironment.Config envConfig,
SqlExplainFormat sqlExplainFormat, @Nullable PhysicalPlannerContext
physicalPlannerContext) {
_planner = new PlannerImpl(config);
- _validator = new Validator(config.getOperatorTable(), catalogReader,
typeFactory);
+ _validator = new Validator(config.getOperatorTable(), catalogReader,
typeFactory,
+ QueryOptionsUtils.isPreferSelectAliasInGroupBy(options,
envConfig.defaultPreferSelectAliasInGroupBy()),
+ envConfig.meterGroupByAliasShadowedByColumn());
_options = options;
_envConfig = envConfig;
_relOptPlanner = new LogicalPlanner(optProgram, this,
config.getTraitDefs());
@@ -113,7 +114,7 @@ public class PlannerContext implements AutoCloseable,
Context {
return _planner;
}
- public SqlValidator getValidator() {
+ public Validator getValidator() {
return _validator;
}
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnException.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnException.java
new file mode 100644
index 00000000000..96813e3dffe
--- /dev/null
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnException.java
@@ -0,0 +1,37 @@
+/**
+ * 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.validate;
+
+import org.apache.pinot.spi.exception.QueryException;
+
+
+/// A [QueryException] with
[org.apache.pinot.spi.exception.QueryErrorCode#QUERY_VALIDATION] for a query
that failed
+/// validation and has a `GROUP BY` name that matches a `SELECT` alias and a
column. The validator resolved the name to
+/// the column, because `preferSelectAliasInGroupBy` was not set. With the
option set, the same query can validate.
+///
+/// It has the same error code, message and cause as the exception it
replaces, so code that handles a
+/// [QueryException] treats both the same way. The controller uses it to retry
the query with the option set. See
+/// `PinotQueryResource#getTableNames`.
+public class GroupByAliasShadowedByColumnException extends QueryException {
+
+ public GroupByAliasShadowedByColumnException(QueryException
validationException) {
+ super(validationException.getErrorCode(),
validationException.getMessage(), validationException.getCause());
+ setStackTrace(validationException.getStackTrace());
+ }
+}
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/Validator.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/Validator.java
index 6e5b5f65184..8b2529352d5 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/Validator.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/validate/Validator.java
@@ -20,6 +20,7 @@ package org.apache.pinot.query.validate;
import java.util.ArrayList;
import java.util.HashSet;
+import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -27,20 +28,29 @@ 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.rel.type.RelRecordType;
+import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.SqlSelect;
+import org.apache.calcite.sql.SqlUtil;
import org.apache.calcite.sql.SqlWith;
import org.apache.calcite.sql.SqlWithItem;
import org.apache.calcite.sql.validate.SelectScope;
import org.apache.calcite.sql.validate.SqlConformanceEnum;
import org.apache.calcite.sql.validate.SqlDelegatingConformance;
+import org.apache.calcite.sql.validate.SqlNameMatcher;
import org.apache.calcite.sql.validate.SqlValidatorCatalogReader;
import org.apache.calcite.sql.validate.SqlValidatorImpl;
import org.apache.calcite.sql.validate.SqlValidatorScope;
+import org.apache.calcite.sql.validate.SqlValidatorUtil;
+import org.apache.calcite.util.Util;
+import org.apache.pinot.common.metrics.BrokerMeter;
+import org.apache.pinot.common.metrics.BrokerMetrics;
+import org.checkerframework.checker.nullness.qual.PolyNull;
/// The `Validator` overwrites Calcite's Validator with Pinot specific logics.
@@ -62,11 +72,154 @@ public class Validator extends SqlValidatorImpl {
}
};
- public Validator(SqlOperatorTable opTab, SqlValidatorCatalogReader
catalogReader, RelDataTypeFactory typeFactory) {
+ private final boolean _preferSelectAliasInGroupBy;
+ private final boolean _meterGroupByAliasShadowedByColumn;
+ /// `GROUP BY` names that match a `SELECT` alias, per `SELECT`. See
[#rewriteGroupByAliases].
+ private final Map<SqlSelect, List<String>> _groupByAliasNames = new
IdentityHashMap<>();
+ /// Whether a `GROUP BY` name of this query matches a `SELECT` alias and a
column. See [#validateGroupClause].
+ private boolean _groupByAliasShadowedByColumnFound;
+
+ /// @param preferSelectAliasInGroupBy whether a simple name in `GROUP BY`
resolves to a `SELECT` alias before a
+ /// column of the same name. See
[#rewriteGroupByAliases].
+ /// @param meterGroupByAliasShadowedByColumn whether to mark
+ ///
[BrokerMeter#QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN]. See
+ /// [#validateGroupClause].
+ public Validator(SqlOperatorTable opTab, SqlValidatorCatalogReader
catalogReader, RelDataTypeFactory typeFactory,
+ boolean preferSelectAliasInGroupBy, boolean
meterGroupByAliasShadowedByColumn) {
super(opTab, catalogReader, typeFactory,
Config.DEFAULT.withConformance(PINOT_CONFORMANCE)
.withIdentifierExpansion(true)
.withTypeCoercionFactory(PinotTypeCoercion::new));
+ _preferSelectAliasInGroupBy = preferSelectAliasInGroupBy;
+ _meterGroupByAliasShadowedByColumn = meterGroupByAliasShadowedByColumn;
+ }
+
+ @Override
+ protected @PolyNull SqlNode performUnconditionalRewrites(@PolyNull SqlNode
node, boolean underFrom) {
+ SqlNode rewritten = super.performUnconditionalRewrites(node, underFrom);
+ if (rewritten instanceof SqlSelect) {
+ rewriteGroupByAliases((SqlSelect) rewritten);
+ }
+ return rewritten;
+ }
+
+ /// Finds each simple name in the `GROUP BY` list that matches exactly one
`SELECT` alias, unless the `SELECT` item is
+ /// the column of the same name. When [#_preferSelectAliasInGroupBy] is set,
replaces the name with the ordinal of
+ /// that `SELECT` item.
+ ///
+ /// Calcite 1.42 (CALCITE-7052) resolves a `GROUP BY` name to a column of
the `FROM` clause first, and to a `SELECT`
+ /// alias only when no column (or more than one) has that name. Calcite 1.40
resolved the alias first. Given
+ /// `SELECT CASE WHEN c = 'a' THEN 'x' ELSE c END AS c, COUNT(*) FROM t
GROUP BY c`, Calcite 1.40 groups by the
+ /// `CASE` expression and Calcite 1.42 groups by the column `c`. An ordinal
always refers to the `SELECT` item, so
+ /// the rewrite restores the Calcite 1.40 result. It also makes `HAVING`
resolve the name to the alias, as before.
+ ///
+ /// The names found are kept in [#_groupByAliasNames].
[#validateGroupClause] later checks which of them are also
+ /// columns. That check needs the scopes, which do not exist yet at this
point.
+ ///
+ /// The rewrite also applies to the names inside `ROLLUP`, `CUBE`, `GROUPING
SETS` and their `ROW` operands, because
+ /// Calcite 1.40 resolved those names to the alias too, and Calcite 1.42
expands ordinals there as well.
+ private void rewriteGroupByAliases(SqlSelect select) {
+ SqlNodeList groupList = select.getGroup();
+ if (groupList == null) {
+ return;
+ }
+ List<String> aliasNames = new ArrayList<>();
+ rewriteGroupByAliases(groupList, select.getSelectList().getList(),
getCatalogReader().nameMatcher(), aliasNames);
+ if (!aliasNames.isEmpty()) {
+ _groupByAliasNames.put(select, aliasNames);
+ }
+ }
+
+ /// Rewrites the `GROUP BY` items in `nodes` in place, and recurses into
grouping-set operators.
+ private void rewriteGroupByAliases(List<SqlNode> nodes, List<SqlNode>
selectList, SqlNameMatcher nameMatcher,
+ List<String> aliasNames) {
+ for (int i = 0; i < nodes.size(); i++) {
+ SqlNode node = nodes.get(i);
+ if (node instanceof SqlNodeList) {
+ rewriteGroupByAliases((SqlNodeList) node, selectList, nameMatcher,
aliasNames);
+ } else if (node instanceof SqlCall &&
isGroupingSetOperator(node.getKind())) {
+ SqlCall call = (SqlCall) node;
+ List<SqlNode> operands = new ArrayList<>(call.getOperandList());
+ rewriteGroupByAliases(operands, selectList, nameMatcher, aliasNames);
+ for (int j = 0; j < operands.size(); j++) {
+ if (operands.get(j) != call.operand(j)) {
+ call.setOperand(j, operands.get(j));
+ }
+ }
+ } else if (node instanceof SqlIdentifier && ((SqlIdentifier)
node).isSimple()) {
+ SqlNode replacement = rewriteGroupByName((SqlIdentifier) node,
selectList, nameMatcher, aliasNames);
+ if (replacement != node) {
+ nodes.set(i, replacement);
+ }
+ }
+ }
+ }
+
+ private static boolean isGroupingSetOperator(SqlKind kind) {
+ return kind == SqlKind.ROLLUP || kind == SqlKind.CUBE || kind ==
SqlKind.GROUPING_SETS || kind == SqlKind.ROW;
+ }
+
+ /// Returns the ordinal that replaces `identifier`, or `identifier` itself
when it is not replaced.
+ private SqlNode rewriteGroupByName(SqlIdentifier identifier, List<SqlNode>
selectList, SqlNameMatcher nameMatcher,
+ List<String> aliasNames) {
+ String name = identifier.getSimple();
+ int matchIndex = -1;
+ int matchCount = 0;
+ for (int j = 0; j < selectList.size(); j++) {
+ String alias = SqlValidatorUtil.alias(selectList.get(j));
+ if (alias != null && nameMatcher.matches(alias, name)) {
+ matchIndex = j;
+ matchCount++;
+ }
+ }
+ // With more than one match, Calcite 1.40 failed with an ambiguity error.
Keep the Calcite 1.42 resolution.
+ if (matchCount != 1) {
+ return identifier;
+ }
+ SqlNode expr = SqlUtil.stripAs(selectList.get(matchIndex));
+ if (expr instanceof SqlIdentifier &&
nameMatcher.matches(Util.last(((SqlIdentifier) expr).names), name)) {
+ return identifier;
+ }
+ aliasNames.add(name);
+ if (!_preferSelectAliasInGroupBy) {
+ return identifier;
+ }
+ return SqlLiteral.createExactNumeric(String.valueOf(matchIndex + 1),
identifier.getParserPosition());
+ }
+
+ /// Finds whether a name found by [#rewriteGroupByAliases] is also exactly
one column of the `FROM` clause. Calcite
+ /// 1.40 and Calcite 1.42 resolve such a name differently. On the first such
name, marks
+ /// [BrokerMeter#QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN] if
[#_meterGroupByAliasShadowedByColumn] is set.
+ ///
+ /// This runs before the validation of the `SELECT` list, so the name is
also found when the query then fails with
+ /// `Expression '...' is not being grouped`. See
[#isGroupByNameResolvedToShadowedColumn].
+ ///
+ /// Only multi-stage queries mark the meter. Single-stage queries always
resolve the name to the alias, so the
+ /// Calcite change does not affect them.
+ @Override
+ protected void validateGroupClause(SqlSelect select) {
+ List<String> aliasNames = _groupByAliasNames.get(select);
+ if (aliasNames != null && !_groupByAliasShadowedByColumnFound) {
+ SelectScope selectScope = getRawSelectScope(select);
+ SqlNameMatcher nameMatcher = getCatalogReader().nameMatcher();
+ for (String name : aliasNames) {
+ if (selectScope != null && selectScope.findQualifyingTableNames(name,
select, nameMatcher).size() == 1) {
+ _groupByAliasShadowedByColumnFound = true;
+ if (_meterGroupByAliasShadowedByColumn) {
+
BrokerMetrics.get().addMeteredGlobalValue(BrokerMeter.QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN,
1);
+ }
+ break;
+ }
+ }
+ }
+ super.validateGroupClause(select);
+ }
+
+ /// Returns whether the validation resolved a `GROUP BY` name to a column
although a `SELECT` alias has the same
+ /// name. That is, a name matches an alias and a column, and
`preferSelectAliasInGroupBy` is not set. With the option
+ /// set, the same query can validate.
+ public boolean isGroupByNameResolvedToShadowedColumn() {
+ return _groupByAliasShadowedByColumnFound && !_preferSelectAliasInGroupBy;
}
/// Expand the star in the select list.
diff --git
a/pinot-query-planner/src/test/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnExceptionTest.java
b/pinot-query-planner/src/test/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnExceptionTest.java
new file mode 100644
index 00000000000..eeb973374e5
--- /dev/null
+++
b/pinot-query-planner/src/test/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnExceptionTest.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.query.validate;
+
+import javax.annotation.Nullable;
+import org.apache.pinot.query.QueryEnvironment;
+import org.apache.pinot.query.QueryEnvironmentTestBase;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.fail;
+
+
+/// Checks when the validation fails with
[GroupByAliasShadowedByColumnException], the exception that makes the
+/// controller retry a query with `preferSelectAliasInGroupBy`.
+public class GroupByAliasShadowedByColumnExceptionTest extends
QueryEnvironmentTestBase {
+
+ @DataProvider
+ public Object[][] queries() {
+ return new Object[][]{
+ {"alias of another column, resolved to the column", "SELECT col2 AS
col1, COUNT(*) FROM a GROUP BY col1",
+ GroupByAliasShadowedByColumnException.class},
+ {"same, with the option set the query is valid",
+ "SET preferSelectAliasInGroupBy=true; SELECT col2 AS col1,
COUNT(*) FROM a GROUP BY col1", null},
+ {"option set, the query fails for another reason",
+ "SET preferSelectAliasInGroupBy=true; SELECT col2 AS col1, col3,
COUNT(*) FROM a GROUP BY col1",
+ QueryException.class},
+ {"no alias matches the group by name", "SELECT col2, COUNT(*) FROM a
GROUP BY col1", QueryException.class},
+ {"the query fails before the group by is validated",
+ "SELECT col2 AS col1, COUNT(*) FROM a WHERE unknownColumn = 1
GROUP BY col1", QueryException.class},
+ {"shadowed alias in a valid query",
+ "SELECT CASE WHEN col1 = 'foo' THEN 'bar' ELSE col1 END AS col1,
COUNT(*) FROM a GROUP BY col1", null},
+ };
+ }
+
+ @Test(dataProvider = "queries")
+ public void testValidationException(String description, String sql,
+ @Nullable Class<? extends QueryException> expectedException) {
+ try (QueryEnvironment.CompiledQuery ignored =
_queryEnvironment.compile(sql)) {
+ assertNull(expectedException, description + ": the query must fail");
+ } catch (QueryException e) {
+ if (expectedException == null) {
+ fail(description + ": the query must compile", e);
+ }
+ assertSame(e.getClass(), expectedException, description);
+ if (expectedException == GroupByAliasShadowedByColumnException.class) {
+ assertEquals(e.getErrorCode(), QueryErrorCode.QUERY_VALIDATION,
description);
+ }
+ }
+ }
+}
diff --git
a/pinot-query-planner/src/test/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnMeterTest.java
b/pinot-query-planner/src/test/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnMeterTest.java
new file mode 100644
index 00000000000..9f235ae9146
--- /dev/null
+++
b/pinot-query-planner/src/test/java/org/apache/pinot/query/validate/GroupByAliasShadowedByColumnMeterTest.java
@@ -0,0 +1,142 @@
+/**
+ * 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.validate;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.pinot.common.metrics.BrokerMeter;
+import org.apache.pinot.common.metrics.BrokerMetrics;
+import org.apache.pinot.core.routing.MockRoutingManagerFactory;
+import org.apache.pinot.query.QueryEnvironment;
+import org.apache.pinot.query.QueryEnvironmentTestBase;
+import org.apache.pinot.query.routing.WorkerManager;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.metrics.NoopPinotMetricsRegistry;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+/// Checks when [BrokerMeter#QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN]
is marked.
+public class GroupByAliasShadowedByColumnMeterTest extends
QueryEnvironmentTestBase {
+ private static final String FLAG = "SET preferSelectAliasInGroupBy=true; ";
+ private static final String CASE_ALIAS =
+ "SELECT CASE WHEN col1 = 'foo' THEN 'bar' ELSE col1 END AS col1,
COUNT(*) FROM a GROUP BY col1";
+
+ private static final CountingBrokerMetrics BROKER_METRICS = new
CountingBrokerMetrics();
+
+ /// Like the multi-stage broker, marks the meter. [#_queryEnvironment] keeps
the default and does not.
+ private QueryEnvironment _meteringQueryEnvironment;
+
+ @BeforeClass
+ public void registerBrokerMetrics() {
+ assertTrue(BrokerMetrics.register(BROKER_METRICS) || BrokerMetrics.get()
== BROKER_METRICS,
+ "Another BrokerMetrics instance is already registered in this JVM");
+ MockRoutingManagerFactory factory = new MockRoutingManagerFactory(1, 2);
+ for (Map.Entry<String, Schema> entry : TABLE_SCHEMAS.entrySet()) {
+ factory.registerTable(entry.getValue(), entry.getKey());
+ }
+ for (Map.Entry<String, List<String>> entry : SERVER1_SEGMENTS.entrySet()) {
+ for (String segment : entry.getValue()) {
+ factory.registerSegment(1, entry.getKey(), segment);
+ }
+ }
+ _meteringQueryEnvironment = new
QueryEnvironment(QueryEnvironment.configBuilder()
+ .requestId(-1L)
+ .database(CommonConstants.DEFAULT_DATABASE)
+ .tableCache(factory.buildTableCache())
+ .workerManager(new WorkerManager("Broker_localhost", "localhost", 3,
factory.buildRoutingManager(null)))
+ .meterGroupByAliasShadowedByColumn(true)
+ .build());
+ }
+
+ @DataProvider
+ public Object[][] queries() {
+ return new Object[][]{
+ {"alias of a different expression shadowed by a column", CASE_ALIAS,
1},
+ {"same, with preferSelectAliasInGroupBy", FLAG + CASE_ALIAS, 1},
+ {"same, with ORDER BY", CASE_ALIAS + " ORDER BY 1", 1},
+ {"alias of another column, query fails", "SELECT col2 AS col1,
COUNT(*) FROM a GROUP BY col1", 1},
+ {"two shadowed aliases count once",
+ "SELECT col2 AS col1, col1 AS col2, COUNT(*) FROM a GROUP BY col1,
col2", 1},
+ {"shadowed alias in a subquery",
+ "SELECT * FROM (SELECT UPPER(col1) AS col1, COUNT(*) AS cnt FROM a
GROUP BY col1) WHERE cnt > 1", 1},
+ {"shadowed alias in rollup", "SELECT UPPER(col1) AS col1, COUNT(*)
FROM a GROUP BY ROLLUP(col1)", 1},
+ {"shadowed alias in a row of grouping sets",
+ "SELECT UPPER(col1) AS col1, col2, COUNT(*) FROM a GROUP BY
GROUPING SETS ((col1, col2), ())", 1},
+ {"column aliased to its own name", "SELECT col1 AS col1, COUNT(*) FROM
a GROUP BY col1", 0},
+ {"qualified column aliased to its own name", "SELECT a.col1 AS col1,
COUNT(*) FROM a GROUP BY col1", 0},
+ {"alias that is not a column", "SELECT UPPER(col1) AS upper_col1,
COUNT(*) FROM a GROUP BY upper_col1", 0},
+ {"column without an alias", "SELECT col1, COUNT(*) FROM a GROUP BY
col1", 0},
+ {"no group by", "SELECT UPPER(col1) AS col1 FROM a", 0},
+ };
+ }
+
+ @Test(dataProvider = "queries")
+ public void testMeter(String description, String sql, int expectedIncrease) {
+ assertEquals(explainAndCountMeter(_meteringQueryEnvironment, sql),
expectedIncrease, description);
+ }
+
+ /// Single-stage queries always resolve a `GROUP BY` name to the alias. The
single-stage paths that compile with the
+ /// multi-stage validator use the default config, so they must not mark the
meter.
+ @Test(dataProvider = "queries")
+ public void testDefaultConfigDoesNotMarkMeter(String description, String
sql, int expectedIncrease) {
+ assertEquals(explainAndCountMeter(_queryEnvironment, sql), 0, description);
+ }
+
+ private static long explainAndCountMeter(QueryEnvironment queryEnvironment,
String sql) {
+ String explain = sql.startsWith(FLAG)
+ ? FLAG + "EXPLAIN PLAN FOR " + sql.substring(FLAG.length())
+ : "EXPLAIN PLAN FOR " + sql;
+ long before = meterCount();
+ try {
+ queryEnvironment.explainQuery(explain, 1L);
+ } catch (RuntimeException e) {
+ // Some queries fail validation. The meter is marked before the failure.
+ }
+ return meterCount() - before;
+ }
+
+ private static long meterCount() {
+ return BROKER_METRICS._groupByAliasShadowedByColumnCount.get();
+ }
+
+ /// Counts the marks of
[BrokerMeter#QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN]. The planner test
classpath has
+ /// no metrics implementation, so a real registry cannot be used.
+ private static class CountingBrokerMetrics extends BrokerMetrics {
+ private final AtomicLong _groupByAliasShadowedByColumnCount = new
AtomicLong();
+
+ CountingBrokerMetrics() {
+ super(new NoopPinotMetricsRegistry());
+ }
+
+ @Override
+ public void addMeteredGlobalValue(BrokerMeter meter, long unitCount) {
+ if (meter == BrokerMeter.QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN)
{
+ _groupByAliasShadowedByColumnCount.addAndGet(unitCount);
+ }
+ super.addMeteredGlobalValue(meter, unitCount);
+ }
+ }
+}
diff --git a/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
b/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
index f97f7b949ad..c2f6b44c1dc 100644
--- a/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
+++ b/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
@@ -392,6 +392,131 @@
"\n PinotLogicalTableScan(table=[[default, a]])",
"\n"
]
+ },
+ {
+ "description": "Group by a name that is both a column and a select
alias resolves to the column by default",
+ "sql": "EXPLAIN PLAN FOR SELECT CASE WHEN col1 = 'foo' THEN 'bar' ELSE
col1 END AS col1, COUNT(*) FROM a GROUP BY col1",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(col1=[CASE(=($0, _UTF-8'foo'), _UTF-8'bar':VARCHAR
CHARACTER SET \"UTF-8\", $0)], EXPR$1=[$1])",
+ "\n PinotLogicalAggregate(group=[{0}], agg#0=[COUNT($1)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n PinotLogicalAggregate(group=[{0}], agg#0=[COUNT()],
aggType=[LEAF])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by a name that is both a column and a select
alias resolves to the alias with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
CASE WHEN col1 = 'foo' THEN 'bar' ELSE col1 END AS col1, COUNT(*) FROM a GROUP
BY col1",
+ "output": [
+ "Execution Plan",
+ "\nPinotLogicalAggregate(group=[{0}], agg#0=[COUNT($1)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n PinotLogicalAggregate(group=[{0}], agg#0=[COUNT()],
aggType=[LEAF])",
+ "\n LogicalProject(col1=[CASE(=($0, _UTF-8'foo'),
_UTF-8'bar':VARCHAR CHARACTER SET \"UTF-8\", $0)])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Having on a grouped select alias resolves to the alias
with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
CASE WHEN col1 = 'foo' THEN 'bar' ELSE col1 END AS col1, COUNT(*) FROM a GROUP
BY col1 HAVING col1 <> 'bar'",
+ "output": [
+ "Execution Plan",
+ "\nPinotLogicalAggregate(group=[{0}], agg#0=[COUNT($1)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n PinotLogicalAggregate(group=[{0}], agg#0=[COUNT()],
aggType=[LEAF])",
+ "\n LogicalProject(col1=[CASE(=($0, _UTF-8'foo'),
_UTF-8'bar':VARCHAR CHARACTER SET \"UTF-8\", $0)])",
+ "\n LogicalFilter(condition=[SEARCH($0,
Sarg[(-∞.._UTF-8'bar':VARCHAR CHARACTER SET \"UTF-8\"), (_UTF-8'bar':VARCHAR
CHARACTER SET \"UTF-8\".._UTF-8'foo':VARCHAR CHARACTER SET \"UTF-8\"),
(_UTF-8'foo':VARCHAR CHARACTER SET \"UTF-8\"..+∞)]:VARCHAR CHARACTER SET
\"UTF-8\")])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by a column whose name is the alias of another
column fails by default",
+ "sql": "EXPLAIN PLAN FOR SELECT col2 AS col1, COUNT(*) FROM a GROUP BY
col1",
+ "expectedException": ".*Expression 'col2' is not being grouped.*"
+ },
+ {
+ "description": "Group by the alias of another column groups by that
column with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
col2 AS col1, COUNT(*) FROM a GROUP BY col1",
+ "output": [
+ "Execution Plan",
+ "\nPinotLogicalAggregate(group=[{0}], agg#0=[COUNT($1)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n PinotLogicalAggregate(group=[{1}], agg#0=[COUNT()],
aggType=[LEAF])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by rollup of a name that is both a column and a
select alias resolves to the column by default",
+ "sql": "EXPLAIN PLAN FOR SELECT UPPER(col1) AS col1, COUNT(*) FROM a
GROUP BY ROLLUP(col1)",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(col1=[UPPER($0)], EXPR$1=[$1])",
+ "\n LogicalProject(col1=[$0], EXPR$1=[$2])",
+ "\n PinotLogicalAggregate(group=[{0, 1}], agg#0=[COUNT($2)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0, 1]])",
+ "\n PinotLogicalAggregate(group=[{0}], groups=[[{0}, {}]],
agg#0=[COUNT()], aggType=[LEAF])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by rollup of a name that is both a column and a
select alias resolves to the alias with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
UPPER(col1) AS col1, COUNT(*) FROM a GROUP BY ROLLUP(col1)",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(col1=[$0], EXPR$1=[$2])",
+ "\n PinotLogicalAggregate(group=[{0, 1}], agg#0=[COUNT($2)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0, 1]])",
+ "\n PinotLogicalAggregate(group=[{0}], groups=[[{0}, {}]],
agg#0=[COUNT()], aggType=[LEAF])",
+ "\n LogicalProject(col1=[UPPER($0)])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by cube of a select alias resolves to the alias
with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
UPPER(col1) AS col1, col2, COUNT(*) FROM a GROUP BY CUBE(col1, col2)",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(col1=[$0], col2=[$1], EXPR$2=[$3])",
+ "\n PinotLogicalAggregate(group=[{0, 1, 2}], agg#0=[COUNT($3)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0, 1, 2]])",
+ "\n PinotLogicalAggregate(group=[{0, 1}], groups=[[{0, 1}, {0},
{1}, {}]], agg#0=[COUNT()], aggType=[LEAF])",
+ "\n LogicalProject(col1=[UPPER($0)], col2=[$1])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by grouping sets with a row of a select alias
resolves to the alias with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
UPPER(col1) AS col1, col2, COUNT(*) FROM a GROUP BY GROUPING SETS ((col1,
col2), col2, ())",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(col1=[$0], col2=[$1], EXPR$2=[$3])",
+ "\n PinotLogicalAggregate(group=[{0, 1, 2}], agg#0=[COUNT($3)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0, 1, 2]])",
+ "\n PinotLogicalAggregate(group=[{0, 1}], groups=[[{0, 1}, {1},
{}]], agg#0=[COUNT()], aggType=[LEAF])",
+ "\n LogicalProject(col1=[UPPER($0)], col2=[$1])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by a column aliased to its own name is unchanged
with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
col1 AS col1, COUNT(*) FROM a GROUP BY col1",
+ "output": [
+ "Execution Plan",
+ "\nPinotLogicalAggregate(group=[{0}], agg#0=[COUNT($1)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n PinotLogicalAggregate(group=[{0}], agg#0=[COUNT()],
aggType=[LEAF])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
}
]
}
diff --git a/pinot-query-runtime/src/test/resources/queries/Aggregates.json
b/pinot-query-runtime/src/test/resources/queries/Aggregates.json
index 6e4a0deee67..f9ceff29ef5 100644
--- a/pinot-query-runtime/src/test/resources/queries/Aggregates.json
+++ b/pinot-query-runtime/src/test/resources/queries/Aggregates.json
@@ -941,5 +941,77 @@
{ "sql": "SELECT upper(string_col), count(int_col) FROM {tbl} GROUP BY
upper(string_col) HAVING sum(int_col) > 0 ORDER BY upper(string_col)" },
{ "sql": "SELECT upper(string_col), count(int_col) FROM {tbl} GROUP BY
upper(string_col) HAVING sum(int_col) >= 0 AND count(int_col) >= 0 ORDER BY
count(int_col)" }
]
+ },
+ "group_by_select_alias_precedence": {
+ "tables": {
+ "tbl": {
+ "schema": [
+ {"name": "col1", "type": "STRING"},
+ {"name": "col2", "type": "STRING"},
+ {"name": "int_col", "type": "INT"}
+ ],
+ "inputs": [
+ ["foo", "x", 1],
+ ["foo", "y", 2],
+ ["bar", "x", 4],
+ ["baz", "y", 8]
+ ]
+ }
+ },
+ "queries": [
+ {
+ "description": "group by a name that is both a column and a select
alias groups by the column by default",
+ "sql": "SELECT CASE WHEN col1 = 'foo' THEN 'bar' ELSE col1 END AS
col1, SUM(int_col) FROM {tbl} GROUP BY col1",
+ "outputs": [
+ ["bar", 3],
+ ["bar", 4],
+ ["baz", 8]
+ ]
+ },
+ {
+ "description": "group by a name that is both a column and a select
alias groups by the alias with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; SELECT CASE WHEN col1 =
'foo' THEN 'bar' ELSE col1 END AS col1, SUM(int_col) FROM {tbl} GROUP BY col1",
+ "outputs": [
+ ["bar", 7],
+ ["baz", 8]
+ ]
+ },
+ {
+ "description": "having on a grouped select alias filters on the alias
with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; SELECT CASE WHEN col1 =
'foo' THEN 'bar' ELSE col1 END AS col1, SUM(int_col) FROM {tbl} GROUP BY col1
HAVING col1 <> 'baz'",
+ "outputs": [
+ ["bar", 7]
+ ]
+ },
+ {
+ "description": "group by rollup of a name that is both a column and a
select alias groups by the column by default",
+ "ignoreV2Optimizer": true,
+ "sql": "SELECT CASE WHEN col1 = 'foo' THEN 'bar' ELSE col1 END AS
col1, SUM(int_col) FROM {tbl} GROUP BY ROLLUP(col1)",
+ "outputs": [
+ ["bar", 3],
+ ["bar", 4],
+ ["baz", 8],
+ [null, 15]
+ ]
+ },
+ {
+ "description": "group by rollup of a name that is both a column and a
select alias groups by the alias with preferSelectAliasInGroupBy",
+ "ignoreV2Optimizer": true,
+ "sql": "SET preferSelectAliasInGroupBy=true; SELECT CASE WHEN col1 =
'foo' THEN 'bar' ELSE col1 END AS col1, SUM(int_col) FROM {tbl} GROUP BY
ROLLUP(col1)",
+ "outputs": [
+ ["bar", 7],
+ ["baz", 8],
+ [null, 15]
+ ]
+ },
+ {
+ "description": "group by the alias of another column groups by that
column with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; SELECT col2 AS col1,
SUM(int_col) FROM {tbl} GROUP BY col1",
+ "outputs": [
+ ["x", 5],
+ ["y", 10]
+ ]
+ }
+ ]
}
}
diff --git
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index 646ca537c40..cb2ac964d5e 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -839,6 +839,20 @@ public class CommonConstants {
/// Calcite itself stops treating an IN list as a scalar predicate.
public static final int DEFAULT_SEALED_IN_LIST_THRESHOLD = 20;
+ /// Whether the multi-stage engine resolves a simple name in `GROUP BY` to
a `SELECT` alias before a column of the
+ /// same name. Calcite 1.42 (CALCITE-7052) resolves the column first, as
MySQL and PostgreSQL do. Before that, Pinot
+ /// resolved the alias first. Enable this to keep the old behavior for
queries such as
+ /// `SELECT CASE WHEN c = 'a' THEN 'x' ELSE c END AS c, COUNT(*) FROM t
GROUP BY c`.
+ ///
+ /// This value can always be overridden by the
[Request.QueryOptionKey#PREFER_SELECT_ALIAS_IN_GROUP_BY] query
+ /// option. Planning outside the broker's multi-stage request handler does
not read this broker config and uses
+ /// the default. The query option works everywhere. The controller `/sql`
endpoint compiles a query only to find
+ /// its tables: when a `GROUP BY` name that matches an alias and a column
makes that compile fail, it retries with
+ /// the option set and lets the broker decide.
+ public static final String CONFIG_OF_PREFER_SELECT_ALIAS_IN_GROUP_BY =
+ "pinot.broker.multistage.prefer.select.alias.in.group.by";
+ public static final boolean DEFAULT_PREFER_SELECT_ALIAS_IN_GROUP_BY =
false;
+
public static class Request {
public static final String SQL = "sql";
public static final String SQL_V1 = "sqlV1";
@@ -1250,6 +1264,9 @@ public class CommonConstants {
/// Option to customize the value of
[Broker#CONFIG_OF_SEALED_IN_LIST_THRESHOLD]
public static final String SEALED_IN_LIST_THRESHOLD =
"sealedInListThreshold";
+ /// Option to customize the value of
[Broker#CONFIG_OF_PREFER_SELECT_ALIAS_IN_GROUP_BY]
+ public static final String PREFER_SELECT_ALIAS_IN_GROUP_BY =
"preferSelectAliasInGroupBy";
+
// Vector search query options
/// Number of inverted-list probes for IVF-based vector indexes.
Higher values improve recall
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]