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 ef3faff13de Fix preferSelectAliasInGroupBy for aliases that are not
columns and retry /sql after planning errors (#20298)
ef3faff13de is described below
commit ef3faff13de20d29576b2addcf84140678d95f59
Author: Yash Mayya <[email protected]>
AuthorDate: Thu Nov 26 02:21:11 2026 +0530
Fix preferSelectAliasInGroupBy for aliases that are not columns and retry
/sql after planning errors (#20298)
---
.../api/resources/PinotQueryResourceTest.java | 4 +
.../org/apache/pinot/query/QueryEnvironment.java | 21 ++--
.../GroupByAliasShadowedByColumnException.java | 6 +-
.../org/apache/pinot/query/validate/Validator.java | 116 +++++++++++----------
.../src/test/resources/queries/GroupByPlans.json | 67 ++++++++++++
5 files changed, 142 insertions(+), 72 deletions(-)
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 f7d3b0724cf..921a248f2d0 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
@@ -799,6 +799,9 @@ public class PinotQueryResourceTest {
// 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},
+ // Same, for a query that fails after the validation: with the column,
HAVING compares an INT with 'late'
+ {"SET useMultistageEngine = 'true'; SELECT CASE WHEN col3 > 15 THEN
'late' ELSE 'on_time' END AS col3, "
+ + "COUNT(*) FROM a GROUP BY col3 HAVING col3 = 'late'",
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},
@@ -813,6 +816,7 @@ public class PinotQueryResourceTest {
Schema schema = new Schema.SchemaBuilder().setSchemaName("a")
.addSingleValueDimension("col1", FieldSpec.DataType.STRING)
.addSingleValueDimension("col2", FieldSpec.DataType.STRING)
+ .addMetric("col3", FieldSpec.DataType.INT)
.build();
TableCache tableCache = new StaticTableCache(
List.of(new
TableConfigBuilder(TableType.OFFLINE).setTableName("a").build()),
List.of(schema), null, false);
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 7be40eb7c69..b8bec3e8985 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
@@ -329,6 +329,14 @@ public class QueryEnvironment {
RelRoot relRoot = compileQuery(queryNode, plannerContext);
return new CompiledQuery(_envConfig.getDatabase(), sqlQuery, relRoot,
plannerContext, sqlNodeAndOptions);
} catch (QueryException e) {
+ if (plannerContext != null) {
+ plannerContext.close();
+ if
(plannerContext.getValidator().isGroupByNameResolvedToShadowedColumn()) {
+ // Lets callers retry with preferSelectAliasInGroupBy. With the
column, the query can fail in the validation
+ // or later, for example when HAVING compares the name with a
literal of the type of the alias
+ throw new GroupByAliasShadowedByColumnException(e);
+ }
+ }
throw e;
} catch (Throwable t) {
if (plannerContext != null) {
@@ -444,19 +452,6 @@ 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)) {
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
index 96813e3dffe..43992251716 100644
---
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
@@ -21,9 +21,9 @@ 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.
+/// A [QueryException] for a query that failed to compile 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 compile.
///
/// 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
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 8b2529352d5..5e0a70433aa 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,16 +20,17 @@ 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;
+import javax.annotation.Nullable;
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.SqlJoin;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
@@ -50,7 +51,6 @@ 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.
@@ -74,9 +74,7 @@ public class Validator extends SqlValidatorImpl {
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].
+ /// Whether a `GROUP BY` name of this query matches a `SELECT` alias and a
column. See [#rewriteGroupByName].
private boolean _groupByAliasShadowedByColumnFound;
/// @param preferSelectAliasInGroupBy whether a simple name in `GROUP BY`
resolves to a `SELECT` alias before a
@@ -94,60 +92,51 @@ public class Validator extends SqlValidatorImpl {
_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.
+ /// Finds each simple name in the `GROUP BY` list that matches exactly one
`SELECT` alias and a column, 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
+ /// Calcite 1.42 (CALCITE-7052) resolves a `GROUP BY` name to a column
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 column that Calcite 1.42 resolves the name to is one of these:
+ /// - the column of a `USING` or `NATURAL` join
+ /// - the column of exactly one table of the `FROM` clause
+ /// - when no table of the `FROM` clause has the name, the column of exactly
one table of an outer query
+ ///
+ /// Any other name is not replaced. Both Calcite versions resolve it to the
alias. Calcite expands an alias, but not
+ /// an ordinal, when the `SELECT` item uses another `SELECT` alias or a
`USING` column, so an ordinal can make such
+ /// a query fail.
///
/// 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);
+ if (groupList != null) {
+ rewriteGroupByAliases(groupList, select,
getCatalogReader().nameMatcher());
}
}
/// 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) {
+ private void rewriteGroupByAliases(List<SqlNode> nodes, SqlSelect select,
SqlNameMatcher nameMatcher) {
for (int i = 0; i < nodes.size(); i++) {
SqlNode node = nodes.get(i);
if (node instanceof SqlNodeList) {
- rewriteGroupByAliases((SqlNodeList) node, selectList, nameMatcher,
aliasNames);
+ rewriteGroupByAliases((SqlNodeList) node, select, nameMatcher);
} else if (node instanceof SqlCall &&
isGroupingSetOperator(node.getKind())) {
SqlCall call = (SqlCall) node;
List<SqlNode> operands = new ArrayList<>(call.getOperandList());
- rewriteGroupByAliases(operands, selectList, nameMatcher, aliasNames);
+ rewriteGroupByAliases(operands, select, nameMatcher);
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);
+ SqlNode replacement = rewriteGroupByName((SqlIdentifier) node, select,
nameMatcher);
if (replacement != node) {
nodes.set(i, replacement);
}
@@ -159,10 +148,12 @@ public class Validator extends SqlValidatorImpl {
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) {
+ /// Returns the ordinal that replaces `identifier`, or `identifier` itself
when it is not replaced. On the first name
+ /// that matches an alias and a column, marks
[BrokerMeter#QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN] if
+ /// [#_meterGroupByAliasShadowedByColumn] is set.
+ private SqlNode rewriteGroupByName(SqlIdentifier identifier, SqlSelect
select, SqlNameMatcher nameMatcher) {
String name = identifier.getSimple();
+ List<SqlNode> selectList = select.getSelectList().getList();
int matchIndex = -1;
int matchCount = 0;
for (int j = 0; j < selectList.size(); j++) {
@@ -180,38 +171,51 @@ public class Validator extends SqlValidatorImpl {
if (expr instanceof SqlIdentifier &&
nameMatcher.matches(Util.last(((SqlIdentifier) expr).names), name)) {
return identifier;
}
- aliasNames.add(name);
+ SelectScope selectScope = getRawSelectScope(select);
+ if (selectScope == null || (!isCommonJoinColumn(select.getFrom(), name,
nameMatcher)
+ && selectScope.findQualifyingTableNames(name, select,
nameMatcher).size() != 1)) {
+ return identifier;
+ }
+ if (!_groupByAliasShadowedByColumnFound) {
+ _groupByAliasShadowedByColumnFound = true;
+ if (_meterGroupByAliasShadowedByColumn) {
+
BrokerMetrics.get().addMeteredGlobalValue(BrokerMeter.QUERIES_WITH_GROUP_BY_ALIAS_SHADOWED_BY_COLUMN,
1);
+ }
+ }
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.
+ /// Returns whether `name` is a column of a `USING` or `NATURAL` join in
`from`. Follows the joins that Calcite
+ /// looks at to expand such a column.
+ private boolean isCommonJoinColumn(@Nullable SqlNode from, String name,
SqlNameMatcher nameMatcher) {
+ while (from instanceof SqlJoin) {
+ SqlJoin join = (SqlJoin) from;
+ List<String> commonColumns = usingNames(join);
+ if (commonColumns == null) {
+ return false;
+ }
+ if (nameMatcher.indexOf(commonColumns, name) >= 0) {
+ return true;
+ }
+ from = join.getLeft();
+ }
+ return false;
+ }
+
+ /// Runs [#rewriteGroupByAliases] here because it needs the scopes to find
the columns.
///
- /// 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].
+ /// This runs before the validation of the `SELECT` list, so a name that
matches an alias and a column 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;
- }
- }
- }
+ rewriteGroupByAliases(select);
super.validateGroupClause(select);
}
diff --git a/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
b/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
index c2f6b44c1dc..580b08c6ca0 100644
--- a/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
+++ b/pinot-query-planner/src/test/resources/queries/GroupByPlans.json
@@ -506,6 +506,73 @@
"\n"
]
},
+ {
+ "description": "Group by an alias that is not a column and uses
another alias is unchanged with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
UPPER(col1) AS u, LOWER(u) AS l, COUNT(*) FROM a GROUP BY u, l",
+ "output": [
+ "Execution Plan",
+ "\nPinotLogicalAggregate(group=[{0, 1}], agg#0=[COUNT($2)],
aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0, 1]])",
+ "\n PinotLogicalAggregate(group=[{0, 1}], agg#0=[COUNT()],
aggType=[LEAF])",
+ "\n LogicalProject(u=[UPPER($0)], l=[LOWER(UPPER($0))])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by an alias that is not a column and uses a
USING column is unchanged with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
UPPER(col1) AS u, COUNT(*) FROM a JOIN b USING (col1) GROUP BY u",
+ "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 LogicalJoin(condition=[=($0, $2)], joinType=[inner])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n LogicalProject(col1=[$0], u=[UPPER($0)])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n LogicalProject(col1=[$0])",
+ "\n PinotLogicalTableScan(table=[[default, b]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by an alias that is also a USING column resolves
to the alias with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
UPPER(a.col2) AS col1, COUNT(*) FROM a JOIN b USING (col1) 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 LogicalJoin(condition=[=($0, $2)], joinType=[inner])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n LogicalProject(col1=[$0], col11=[UPPER($1)])",
+ "\n PinotLogicalTableScan(table=[[default, a]])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n LogicalProject(col1=[$0])",
+ "\n PinotLogicalTableScan(table=[[default, b]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Group by an alias that is also a column of the outer
query only resolves to the alias with preferSelectAliasInGroupBy",
+ "sql": "SET preferSelectAliasInGroupBy=true; EXPLAIN PLAN FOR SELECT
col1 FROM e WHERE col2 IN (SELECT UPPER(a.col2) AS mcol1 FROM a GROUP BY
mcol1)",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(col1=[$0])",
+ "\n LogicalJoin(condition=[=($1, $2)], joinType=[semi])",
+ "\n LogicalProject(col1=[$0], col2=[$1])",
+ "\n PinotLogicalTableScan(table=[[default, e]])",
+ "\n PinotLogicalExchange(distribution=[broadcast],
relExchangeType=[PIPELINE_BREAKER])",
+ "\n PinotLogicalAggregate(group=[{0}], aggType=[FINAL])",
+ "\n PinotLogicalExchange(distribution=[hash[0]])",
+ "\n PinotLogicalAggregate(group=[{0}], aggType=[LEAF])",
+ "\n LogicalProject(mcol1=[UPPER($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",
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]