diff --git a/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java b/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java index 6ac184d177ee..250ca10175d3 100644 --- a/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java +++ b/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java @@ -259,6 +259,12 @@ && allSatisfiable(measureList, tileKey2)) { } } } + // Return the roll-up tile with the fewest rows. + // Without this return the loop above has no effect and + // AggregateStarTableRule never rolls up a tile. + if (bestCandidate != null) { + return bestCandidate; + } } // What we need is not there. If we can't create, we're done. diff --git a/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java b/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java index 95a882863a76..5f991137d253 100644 --- a/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java +++ b/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java @@ -1967,7 +1967,7 @@ public static MutableAggregate permute(MutableAggregate aggregate, for (AggregateCall aggregateCall : query.aggCalls) { AggregateCall newAggCall = null; // 1. try to find rollup agg-call. - if (!aggregateCall.isDistinct()) { + if (!aggregateCall.isDistinct() && aggregateCall.distinctKeys == null) { int i = target.aggCalls.indexOf(aggregateCall); if (i >= 0) { // When an SqlAggFunction does not support roll up, it will return null, @@ -2030,6 +2030,15 @@ public static MutableAggregate permute(MutableAggregate aggregate, } newArgList.add(newArgIndex); } + final int newFilterArg; + if (queryAggCall.hasFilter()) { + newFilterArg = targetGroupByIndexes.indexOf(queryAggCall.filterArg); + if (newFilterArg < 0) { + return null; + } + } else { + newFilterArg = -1; + } final boolean isAllowBuild; if (newArgList.isEmpty()) { // Size of agg-call's args is empty, we stop to build a new agg-call, @@ -2051,7 +2060,7 @@ public static MutableAggregate permute(MutableAggregate aggregate, return AggregateCall.create(queryAggCall.getParserPosition(), aggregation, queryAggCall.isDistinct(), queryAggCall.isApproximate(), queryAggCall.ignoreNulls(), queryAggCall.rexList, - newArgList, -1, queryAggCall.distinctKeys, + newArgList, newFilterArg, queryAggCall.distinctKeys, queryAggCall.collation, queryAggCall.type, queryAggCall.name); } diff --git a/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java b/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java index b222cfc4f557..a2d433921aa2 100644 --- a/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java +++ b/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java @@ -541,6 +541,7 @@ public SqlParserPos getParserPosition() { && distinct == ((AggregateCall) o).distinct && approximate == ((AggregateCall) o).approximate && ignoreNulls == ((AggregateCall) o).ignoreNulls + && rexList.equals(((AggregateCall) o).rexList) && argList.equals(((AggregateCall) o).argList) && filterArg == ((AggregateCall) o).filterArg && Objects.equals(distinctKeys, ((AggregateCall) o).distinctKeys) diff --git a/core/src/main/java/org/apache/calcite/rel/externalize/RelJson.java b/core/src/main/java/org/apache/calcite/rel/externalize/RelJson.java index 688894c1f467..7d1b8f72030c 100644 --- a/core/src/main/java/org/apache/calcite/rel/externalize/RelJson.java +++ b/core/src/main/java/org/apache/calcite/rel/externalize/RelJson.java @@ -457,6 +457,21 @@ public Object toJson(AggregateCall node) { map.put("distinct", node.isDistinct()); map.put("operands", node.getArgList()); map.put("name", node.getName()); + if (node.isApproximate()) { + map.put("approximate", true); + } + if (node.ignoreNulls()) { + map.put("ignoreNulls", true); + } + if (node.filterArg >= 0) { + map.put("filter", node.filterArg); + } + if (node.distinctKeys != null) { + map.put("distinctKeys", toJson(node.distinctKeys)); + } + if (!node.collation.getFieldCollations().isEmpty()) { + map.put("collation", toJson(node.collation)); + } return map; } diff --git a/core/src/main/java/org/apache/calcite/rel/externalize/RelJsonReader.java b/core/src/main/java/org/apache/calcite/rel/externalize/RelJsonReader.java index 1cf0d2d64e9a..1c865bba3a46 100644 --- a/core/src/main/java/org/apache/calcite/rel/externalize/RelJsonReader.java +++ b/core/src/main/java/org/apache/calcite/rel/externalize/RelJsonReader.java @@ -344,15 +344,28 @@ private AggregateCall toAggCall(Map jsonAggCall) { requireNonNull((List) jsonAggCall.get("operands"), "jsonAggCall.operands"); final Integer filterOperand = (Integer) jsonAggCall.get("filter"); + final boolean approximate = + Boolean.TRUE.equals(jsonAggCall.get("approximate")); + final boolean ignoreNulls = + Boolean.TRUE.equals(jsonAggCall.get("ignoreNulls")); + @SuppressWarnings("unchecked") + final List jsonDistinctKeys = + (List) jsonAggCall.get("distinctKeys"); + @SuppressWarnings("unchecked") + final List> jsonCollation = + (List>) jsonAggCall.get("collation"); final Object jsonAggType = requireNonNull(jsonAggCall.get("type"), "jsonAggCall.type"); final RelDataType type = relJson.toType(cluster.getTypeFactory(), jsonAggType); final String name = (String) jsonAggCall.get("name"); - return AggregateCall.create(aggregation, distinct, false, false, + return AggregateCall.create(aggregation, distinct, approximate, ignoreNulls, ImmutableList.of(), operands, filterOperand == null ? -1 : filterOperand, - null, RelCollations.EMPTY, type, name); + jsonDistinctKeys == null ? null : ImmutableBitSet.of(jsonDistinctKeys), + jsonCollation == null ? RelCollations.EMPTY + : relJson.toCollation(jsonCollation), + type, name); } private RelNode lookupInput(String jsonInput) { diff --git a/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java b/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java index 152089329522..2bddac81f992 100644 --- a/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java +++ b/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java @@ -134,7 +134,6 @@ import java.util.Collections; import java.util.Deque; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -1421,15 +1420,16 @@ public SqlNode toSql(AggregateCall aggCall) { return toSql(aggCall.getAggregation(), aggCall.isDistinct(), Util.transform(aggCall.rexList, e -> toSql(null, e)), Util.transform(aggCall.getArgList(), this::field), - aggCall.filterArg, aggCall.collation, aggCall.isApproximate()); + aggCall.filterArg, aggCall.distinctKeys, aggCall.collation, + aggCall.isApproximate()); } /** Converts a call to an aggregate function, with a given list of operands, * to an expression. */ private SqlNode toSql(SqlOperator op, boolean distinct, List preOperandList, List operandList, - int filterArg, RelCollation collation, - boolean approximate) { + int filterArg, @Nullable ImmutableBitSet distinctKeys, + RelCollation collation, boolean approximate) { final SqlLiteral qualifier = distinct ? SqlSelectKeyword.DISTINCT.symbol(POS) : null; @@ -1440,7 +1440,7 @@ private SqlNode toSql(SqlOperator op, boolean distinct, if (op instanceof SqlSumEmptyIsZeroAggFunction) { final SqlNode node = toSql(SqlStdOperatorTable.SUM, distinct, preOperandList, - operandList, filterArg, collation, approximate); + operandList, filterArg, distinctKeys, collation, approximate); return SqlStdOperatorTable.COALESCE.createCall(POS, node, ZERO); } @@ -1465,7 +1465,7 @@ private SqlNode toSql(SqlOperator op, boolean distinct, newOperandList.addAll(Util.skip(operandList)); } return toSql(op, distinct, preOperandList, newOperandList, -1, - collation, approximate); + distinctKeys, collation, approximate); } if (op instanceof SqlCountAggFunction && operandList.isEmpty()) { @@ -1473,8 +1473,13 @@ private SqlNode toSql(SqlOperator op, boolean distinct, // to it. operandList = ImmutableList.of(SqlIdentifier.STAR); } - final SqlCall call = + final SqlCall call0 = op.createCall(qualifier, POS, operandList); + final SqlCall call = distinctKeys == null + ? call0 + : SqlStdOperatorTable.WITHIN_DISTINCT.createCall(POS, call0, + new SqlNodeList(Util.transform(distinctKeys.asList(), this::field), + POS)); // Handle filter by generating FILTER (WHERE ...) final SqlCall call2; @@ -1500,7 +1505,7 @@ private SqlCall withOrder(SqlCall call, RelCollation collation) { } final List orderByList = new ArrayList<>(); for (RelFieldCollation field : collation.getFieldCollations()) { - addOrderItem(orderByList, field); + addOrderItem(orderByList, field, false); } return SqlStdOperatorTable.WITHIN_GROUP.createCall(POS, call, new SqlNodeList(orderByList, POS)); @@ -2520,10 +2525,9 @@ private boolean hasNested( if (node instanceof SqlSelect) { SqlNodeList selectList = ((SqlSelect) node).getSelectList(); if (!selectList.equals(SqlNodeList.SINGLETON_STAR)) { - final Set aggregatesArgs = new HashSet<>(); - for (AggregateCall aggregateCall : aggregate.getAggCallList()) { - aggregatesArgs.addAll(aggregateCall.getArgList()); - } + final Set aggregatesArgs = + RelOptUtil.getAllFields2(ImmutableBitSet.of(), + aggregate.getAggCallList()); for (int aggregatesArg : aggregatesArgs) { if (selectList.get(aggregatesArg) instanceof SqlBasicCall) { final SqlBasicCall call = (SqlBasicCall) selectList.get(aggregatesArg); diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateCaseToFilterRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateCaseToFilterRule.java index 1bfd733ca068..ba3dde58b991 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateCaseToFilterRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateCaseToFilterRule.java @@ -138,7 +138,7 @@ && isThreeArgCase(project.getProjects().get(singleArg))) { private static @Nullable AggregateCall transform(AggregateCall call, Project project, List newProjects) { final int singleArg = soleArgument(call); - if (singleArg < 0) { + if (singleArg < 0 || call.distinctKeys != null) { return null; } @@ -238,7 +238,7 @@ && isIntLiteral(arg2, BigDecimal.ZERO))) { newProjects.add(filter); return AggregateCall.create(pos, call.getAggregation(), false, false, false, call.rexList, ImmutableList.of(newProjects.size() - 2), - newProjects.size() - 1, null, RelCollations.EMPTY, + newProjects.size() - 1, null, call.collation, call.getType(), call.getName()); } else { return null; diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java index 6fc0915bdb29..c372bdd3d886 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java @@ -310,6 +310,9 @@ private static RelCollation remapCollation(RelCollation collation, // In this case, we are assuming that there is a single distinct function. // So make sure that argLists is of size one. checkArgument(argLists.size() == 1); + if (aggregate.getAggCallList().stream().anyMatch(c -> c.distinctKeys != null)) { + return null; + } // Check if any DISTINCT aggregate has ORDER BY columns not in GROUP BY or args. // If so, we cannot safely apply this optimization because it would violate DISTINCT @@ -706,7 +709,7 @@ private static void rewriteUsingGroupingSets(RelOptRuleCall call, AggregateCall.create(aggCall.getParserPosition(), SqlStdOperatorTable.MIN, false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, args, newFilterArg, - aggCall.distinctKeys, remappedCollation, aggregate.hasEmptyGroup(), + null, remappedCollation, aggregate.hasEmptyGroup(), relBuilder.peek(), null, upperAggName); upperAggCalls.add(newCall); ordinals.add(topGroupCount + upperAggCalls.size() - 1); @@ -729,7 +732,7 @@ private static void rewriteUsingGroupingSets(RelOptRuleCall call, AggregateCall.create(aggCall.getParserPosition(), aggCall.getAggregation(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, newArgList, newFilterArg, - aggCall.distinctKeys, remappedCollation, + null, remappedCollation, aggregate.hasEmptyGroup(), relBuilder.peek(), null, upperAggName); upperAggCalls.add(newCall); ordinals.add(topGroupCount + upperAggCalls.size() - 1); @@ -1103,7 +1106,7 @@ private static void doRewrite(RelBuilder relBuilder, Aggregate aggregate, int n, final AggregateCall newAggCall = AggregateCall.create(aggCall.getParserPosition(), aggCall.getAggregation(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, - newArgs, -1, aggCall.distinctKeys, remapCollation(aggCall.collation, sourceOf), + newArgs, -1, null, remapCollation(aggCall.collation, sourceOf), aggCall.getType(), aggCall.getName()); assert refs.get(i) == null; if (leftFields == null) { @@ -1192,7 +1195,7 @@ private static void rewriteAggCalls( AggregateCall.create(aggCall.getParserPosition(), aggCall.getAggregation(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, newArgs, -1, - aggCall.distinctKeys, remapCollation(aggCall.collation, sourceOf), + null, remapCollation(aggCall.collation, sourceOf), aggCall.getType(), aggCall.getName()); newAggCalls.set(i, newAggCall); } diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandWithinDistinctRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandWithinDistinctRule.java index 46f4e5994e2b..4ae86499882a 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandWithinDistinctRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandWithinDistinctRule.java @@ -19,6 +19,7 @@ import org.apache.calcite.linq4j.Ord; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelRule; +import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.logical.LogicalAggregate; @@ -427,7 +428,14 @@ int getCount(int filterArg) { // aggregate. aggCall = b.aggregateCall(c.getParserPosition(), c.getAggregation(), - b.fields(registrar.fields(c.getArgList(), c.filterArg))); + b.fields(registrar.fields(c.getArgList(), c.filterArg))) + .sort( + b.fields( + RelCollations.of( + Util.transform(c.collation.getFieldCollations(), + fc -> fc.withFieldIndex( + registrar.field(fc.getFieldIndex(), + c.filterArg)))))); if (mustBeCounted(c)) { filters.add( diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java index 5024d2e04ba4..811314f063af 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java @@ -18,10 +18,10 @@ import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptRuleOperand; +import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.plan.RelRule; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Aggregate; -import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.logical.LogicalTableScan; import org.apache.calcite.rex.RexNode; @@ -85,19 +85,10 @@ public AggregateExtractProjectRule(RelOptRuleOperand operand, @Override public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = call.rel(1); - // Compute which input fields are used. - // 1. group fields are always used - final ImmutableBitSet.Builder inputFieldsUsed = - aggregate.getGroupSet().rebuild(); - // 2. agg functions - for (AggregateCall aggCall : aggregate.getAggCallList()) { - for (int i : aggCall.getArgList()) { - inputFieldsUsed.set(i); - } - if (aggCall.filterArg >= 0) { - inputFieldsUsed.set(aggCall.filterArg); - } - } + // Compute which input fields are used: the group keys, and the arguments, + // filters, WITHIN DISTINCT keys and sort keys of the aggregate calls + final ImmutableBitSet inputFieldsUsed = + ImmutableBitSet.of(RelOptUtil.getAllFields(aggregate)); final RelBuilder relBuilder = call.builder().push(input); final List projects = new ArrayList<>(); final Mapping mapping = @@ -105,7 +96,7 @@ public AggregateExtractProjectRule(RelOptRuleOperand operand, aggregate.getInput().getRowType().getFieldCount(), inputFieldsUsed.cardinality()); int j = 0; - for (int i : inputFieldsUsed.build()) { + for (int i : inputFieldsUsed) { projects.add(relBuilder.field(i)); mapping.set(i, j++); } diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterToCaseRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterToCaseRule.java index d76a3be0d890..0d4eb9d3e83b 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterToCaseRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterToCaseRule.java @@ -18,7 +18,6 @@ import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelRule; -import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.core.Project; @@ -109,7 +108,7 @@ protected AggregateFilterToCaseRule(Config config) { private static AggregateCall transform(AggregateCall call, RexBuilder rexBuilder, RelDataTypeFactory typeFactory, List newProjects) { - if (!call.hasFilter()) { + if (!call.hasFilter() || !call.getAggregation().skipsNullInputs()) { return call; } final SqlKind kind = call.getAggregation().getKind(); @@ -137,7 +136,7 @@ private static AggregateCall transform(AggregateCall call, newProjects.add(caseWhen); return AggregateCall.create(call.getParserPosition(), call.getAggregation(), call.isDistinct(), call.isApproximate(), call.ignoreNulls(), call.rexList, - ImmutableList.of(newProjects.size() - 1), -1, call.distinctKeys, RelCollations.EMPTY, + ImmutableList.of(newProjects.size() - 1), -1, call.distinctKeys, call.collation, call.getType(), call.getName()); } diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java index 105e4096dc5e..f118882c444b 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java @@ -136,7 +136,7 @@ public AggregateFilterTransposeRule(RelOptRuleOperand operand, int i = newGroupSet.cardinality(); for (AggregateCall aggregateCall : aggregate.getAggCallList()) { final SqlAggFunction rollup = aggregateCall.getAggregation().getRollup(); - if (rollup == null) { + if (rollup == null || aggregateCall.distinctKeys != null) { // This aggregate cannot be rolled up. return; } diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java index 6e3975c4e1da..25561f30ad8f 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java @@ -36,6 +36,7 @@ import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexUtil; import org.apache.calcite.sql.SqlAggFunction; +import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlSplittableAggFunction; import org.apache.calcite.tools.RelBuilder; import org.apache.calcite.tools.RelBuilderFactory; @@ -138,13 +139,20 @@ static boolean isAggregateSupported(Aggregate aggregate, return false; } // If any aggregate functions do not support splitting, bail out - // If any aggregate call has a filter or is distinct, bail out + // If any aggregate call has a filter, is distinct, or has WITHIN DISTINCT, + // bail out + // BIT_XOR is not supported. It uses SelfSplitter, which ignores how many + // rows of the other input join to each row. That is correct for MIN, MAX, + // BIT_AND and BIT_OR, where a repeated value does not change the result, + // but x XOR x is 0. for (AggregateCall aggregateCall : aggregate.getAggCallList()) { if (aggregateCall.getAggregation().unwrap(SqlSplittableAggFunction.class) == null) { return false; } - if (aggregateCall.filterArg >= 0 || aggregateCall.isDistinct()) { + if (aggregateCall.filterArg >= 0 || aggregateCall.isDistinct() + || aggregateCall.distinctKeys != null + || aggregateCall.getAggregation().getKind() == SqlKind.BIT_XOR) { return false; } } diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateMergeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateMergeRule.java index 34b727e222ed..66547ea76fd3 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateMergeRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateMergeRule.java @@ -71,6 +71,7 @@ private static boolean isAggregateSupported(AggregateCall aggCall) { if (aggCall.isDistinct() || aggCall.hasFilter() || aggCall.isApproximate() + || aggCall.distinctKeys != null || aggCall.getArgList().size() > 1) { return false; } diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java index 0aae7872fa71..b77bc0ff4ad1 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java @@ -103,6 +103,11 @@ protected void apply(RelOptRuleCall call, @Nullable Project postProject, // populate a materialization return; } + if (aggregate.getAggCallList().stream().anyMatch(c -> + c.hasFilter() || c.distinctKeys != null + || !c.collation.getFieldCollations().isEmpty())) { + return; + } final RelOptCluster cluster = scan.getCluster(); final RelOptTable table = scan.getTable(); final RelOptLattice lattice = diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java index 614c510a4e18..bb989637a57d 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java @@ -118,6 +118,7 @@ public AggregateUnionTransposeRule(Class aggregateClass, for (AggregateCall aggCall : aggRel.getAggCallList()) { if (aggCall.isDistinct() + || aggCall.distinctKeys != null || !SUPPORTED_AGGREGATES.containsKey(aggCall.getAggregation() .getClass())) { return; diff --git a/core/src/main/java/org/apache/calcite/rel/rules/MeasureRules.java b/core/src/main/java/org/apache/calcite/rel/rules/MeasureRules.java index f69810a14d42..c8eb2bc6c3a7 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/MeasureRules.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/MeasureRules.java @@ -132,6 +132,10 @@ protected AggregateMeasureRule(AggregateMeasureRuleConfig config) { @Override public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); + if (aggregate.getAggCallList().stream().anyMatch(c -> + c.getAggregation().kind == SqlKind.AGG_M2V && c.hasFilter())) { + return; + } final RelBuilder b = call.builder(); b.push(aggregate.getInput()); final List> aggCallList = diff --git a/core/src/main/java/org/apache/calcite/rel/rules/materialize/MaterializedViewAggregateRule.java b/core/src/main/java/org/apache/calcite/rel/rules/materialize/MaterializedViewAggregateRule.java index 7ac3a79f5105..2165f7292725 100644 --- a/core/src/main/java/org/apache/calcite/rel/rules/materialize/MaterializedViewAggregateRule.java +++ b/core/src/main/java/org/apache/calcite/rel/rules/materialize/MaterializedViewAggregateRule.java @@ -479,7 +479,9 @@ public abstract class MaterializedViewAggregateRule= 0) { + if (queryAggCall.filterArg >= 0 + || queryAggCall.distinctKeys != null + || queryAggCall.hasCollation()) { // Not supported currently return null; } @@ -497,7 +499,8 @@ public abstract class MaterializedViewAggregateRule= 0) { + || viewAggCall.filterArg >= 0 + || viewAggCall.distinctKeys != null) { // Continue continue; } diff --git a/core/src/main/java/org/apache/calcite/sql/SqlFilterOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlFilterOperator.java index 5302777606f7..93cd0d456633 100644 --- a/core/src/main/java/org/apache/calcite/sql/SqlFilterOperator.java +++ b/core/src/main/java/org/apache/calcite/sql/SqlFilterOperator.java @@ -107,6 +107,12 @@ public SqlFilterOperator() { @Override public boolean hasEmptyGroup() { return true; } + + @Override public RelDataType getCollationType() { + final SqlNodeList orderList = + requireNonNull(flat.orderList, "orderList"); + return SqlTypeUtil.deriveType(this, orderList.get(0)); + } }; RelDataType ret = aggCall.getOperator().inferReturnType(opBinding); diff --git a/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java b/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java index ae43fe1e9112..56fb64e2b54a 100644 --- a/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java +++ b/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java @@ -32,6 +32,7 @@ import org.apache.calcite.plan.hep.HepRelVertex; import org.apache.calcite.rel.BiRel; import org.apache.calcite.rel.RelCollation; +import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.RelFieldCollation; import org.apache.calcite.rel.RelHomogeneousShuttle; import org.apache.calcite.rel.RelNode; @@ -877,8 +878,12 @@ static boolean isSameForNoRowsAndNullRow(Aggregate aggregate) { } } newAggCalls.add( - oldAggCall.adaptTo(newProject, aggArgs, filterArg, - rel.hasEmptyGroup(), newHasEmptyGroup)); + oldAggCall + .withDistinctKeys(oldAggCall.distinctKeys == null ? null + : oldAggCall.distinctKeys.permute(combinedMap)) + .withCollation(RelCollations.permute(oldAggCall.collation, combinedMap)) + .adaptTo(newProject, aggArgs, filterArg, + rel.hasEmptyGroup(), newHasEmptyGroup)); // The old to new output position mapping will be the same as that // of newProject, plus any aggregates that the oldAgg produces. @@ -3666,8 +3671,12 @@ public static final class RemoveCorrelationForScalarAggregateRule aggCall.filterArg < 0 ? aggCall.filterArg : aggCall.filterArg + groupCount; newAggCalls.add( - aggCall.adaptTo(joinOutputProject, argList, filterArg, - aggregate.hasEmptyGroup(), groupCount == 0)); + aggCall + .withDistinctKeys(aggCall.distinctKeys == null ? null + : aggCall.distinctKeys.shift(groupCount)) + .withCollation(RelCollations.shift(aggCall.collation, groupCount)) + .adaptTo(joinOutputProject, argList, filterArg, + aggregate.hasEmptyGroup(), groupCount == 0)); } ImmutableBitSet groupSet = diff --git a/core/src/main/java/org/apache/calcite/sql2rel/TopDownGeneralDecorrelator.java b/core/src/main/java/org/apache/calcite/sql2rel/TopDownGeneralDecorrelator.java index 7a69c86a4612..006c1fbac23f 100644 --- a/core/src/main/java/org/apache/calcite/sql2rel/TopDownGeneralDecorrelator.java +++ b/core/src/main/java/org/apache/calcite/sql2rel/TopDownGeneralDecorrelator.java @@ -601,7 +601,9 @@ public RelNode unnestInternal(Aggregate aggregate, boolean allowEmptyOutputFromR Map oldToNewOutputs = new HashMap<>(); for (int groupKey : aggregate.getGroupSet()) { int oriIndex = aggregate.getGroupSet().indexOf(groupKey); - int newIndex = newGroupSet.indexOf(groupKey); + int newIndex = + newGroupSet.indexOf( + requireNonNull(inputUnnestedQuery.oldToNewOutputs.get(groupKey))); oldToNewOutputs.put(oriIndex, newIndex); } for (int i = 0; i < aggregate.getAggCallList().size(); i++) { diff --git a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java index 42f757120e6c..1a9838862394 100644 --- a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java +++ b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java @@ -4299,6 +4299,10 @@ public RelBuilder pivot(GroupKey groupKey, aggCalls.forEach(aggCall -> { final String alias2 = alias + "_" + ((AggCallPlus) aggCall).alias(); final List filters = new ArrayList<>(); + final RexNode filter = ((AggCallPlus) aggCall).filterCondition(); + if (filter != null) { + filters.add(filter); + } Pair.forEach(axisList, expressionList, (axis, expression) -> filters.add(equals(axis, expression))); multipliedAggCalls.add(aggCall.filter(and(filters)).as(alias2)); @@ -4576,6 +4580,9 @@ private interface AggCallPlus extends AggCall { /** Returns the alias. */ @Nullable String alias(); + /** Returns the FILTER condition, or null. */ + @Nullable RexNode filterCondition(); + /** Returns an {@link AggregateCall} that is approximately equivalent * to this {@code AggCall} and is good for certain things, such as deriving * field names. */ @@ -4757,6 +4764,10 @@ private class AggCallImpl implements AggCallPlus { return alias; } + @Override public @Nullable RexNode filterCondition() { + return filter; + } + @Override public AggregateCall aggregateCall() { // Use dummy values for collation and type. This method only promises to // return a call that is "approximately equivalent ... and is good for @@ -4793,12 +4804,15 @@ private class AggCallImpl implements AggCallPlus { ? null : ImmutableBitSet.of( registrar.registerExpressions(this.distinctKeys)); + // collation() gives the direction; the field is the one that register() + // projected for the sort key final RelCollation collation = RelCollations.of(this.orderKeys .stream() .map(orderKey -> collation(orderKey, RelFieldCollation.Direction.ASCENDING, - null, Collections.emptyList())) + null, new ArrayList<>()) + .withFieldIndex(registrar.registerExpression(orderKey))) .collect(Collectors.toList())); if (aggFunction instanceof SqlCountAggFunction && !distinct) { args = args.stream() @@ -4833,6 +4847,17 @@ private class AggCallImpl implements AggCallPlus { } @Override public OverCall over() { + checkArgument(filter == null, + "FILTER is not supported in a windowed aggregate call: %s", this); + checkArgument(distinctKeys == null, + "WITHIN DISTINCT is not supported in a windowed aggregate call: %s", + this); + checkArgument(orderKeys.isEmpty(), + "WITHIN GROUP is not supported in a windowed aggregate call: %s", + this); + checkArgument(preOperands.isEmpty(), + "pre-operands are not supported in a windowed aggregate call: %s", + this); return new OverCallImpl(pos, aggFunction, distinct, operands, ignoreNulls, alias); } @@ -4928,6 +4953,10 @@ private class AggCallImpl2 implements AggCallPlus { return aggregateCall.name; } + @Override public @Nullable RexNode filterCondition() { + throw new UnsupportedOperationException(); + } + @Override public AggregateCall aggregateCall() { return aggregateCall; } diff --git a/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java b/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java index 21cc2de0f416..de78ceb20da4 100644 --- a/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java +++ b/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java @@ -28,6 +28,7 @@ import org.apache.calcite.rel.RelInput; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.RelShuttleImpl; +import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.rel.core.TableModify; @@ -1267,6 +1268,87 @@ void testAggregateWithAlias(SqlExplainFormat format) { assertThat(s, isLinux(expected)); } + /** RelJsonWriter does not write the FILTER, WITHIN DISTINCT and WITHIN + * GROUP of an aggregate call, so the plan that RelJsonReader reads back + * computes other values. */ + @Test void testAggregateCallFieldsRoundTrip() { + final FrameworkConfig config = RelBuilderTest.config().build(); + final RelBuilder builder = RelBuilder.create(config); + // Equivalent SQL: + // SELECT deptno, + // COUNT(*) FILTER (WHERE comm IS NOT NULL) AS c, + // SUM(sal) WITHIN DISTINCT (job) AS s, + // COLLECT(ename) WITHIN GROUP (ORDER BY sal) AS l + // FROM emp + // GROUP BY deptno + final RelNode rel = builder + .scan("EMP") + .aggregate(builder.groupKey("DEPTNO"), + builder.count() + .filter(builder.isNotNull(builder.field("COMM"))).as("C"), + builder.sum(builder.field("SAL")) + .unique(builder.field("JOB")).as("S"), + builder.aggregateCall(SqlStdOperatorTable.COLLECT, + builder.field("ENAME")).sort(builder.field("SAL")).as("L")) + .build(); + final String expected = "" + + "LogicalAggregate(group=[{3}], C=[COUNT() FILTER $4], " + + "S=[SUM($2) WITHIN DISTINCT ($1)], " + + "L=[COLLECT($0) WITHIN GROUP ([2])])\n" + + " LogicalProject(ENAME=[$1], JOB=[$2], SAL=[$5], DEPTNO=[$7], " + + "$f8=[IS NOT NULL($6)])\n" + + " LogicalTableScan(table=[[scott, EMP]])\n"; + assertThat(RelOptUtil.toString(rel), isLinux(expected)); + final RelJsonWriter jsonWriter = new RelJsonWriter(); + rel.explain(jsonWriter); + final String s = + deserializeAndDumpToTextFormat(getSchema(rel), jsonWriter.asString()); + assertThat(s, isLinux(expected)); + } + + /** Describes the calls of an Aggregate, including IGNORE NULLS, which + * {@link AggregateCall#toString()} does not print. */ + private static String describeAggCalls(RelNode rel) { + final StringBuilder b = new StringBuilder(); + for (AggregateCall call : ((Aggregate) rel).getAggCallList()) { + b.append(call).append(call.ignoreNulls() ? " IGNORE NULLS" : "") + .append("\n"); + } + return b.toString(); + } + + /** RelJsonWriter does not write APPROXIMATE and IGNORE NULLS of an + * aggregate call. */ + @Test void testAggregateCallFlagsRoundTrip() { + final FrameworkConfig config = RelBuilderTest.config().build(); + final RelBuilder builder = RelBuilder.create(config); + final RelNode rel = builder + .scan("EMP") + .aggregate(builder.groupKey("DEPTNO"), + builder.count(true, "C", builder.field("JOB")).approximate(true), + builder.aggregateCall(SqlLibraryOperators.ARRAY_AGG, + builder.field("COMM")).ignoreNulls(true).as("A")) + .build(); + final String expected = "COUNT(APPROXIMATE DISTINCT $2)\n" + + "ARRAY_AGG($6) IGNORE NULLS\n"; + assertThat(describeAggCalls(rel), is(expected)); + final RelJsonWriter jsonWriter = new RelJsonWriter(); + rel.explain(jsonWriter); + final String relJson = jsonWriter.asString(); + final String s = + Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> { + final RelJsonReader reader = + new RelJsonReader(cluster, getSchema(rel), rootSchema, + RelJson::withLibraryOperatorTable); + try { + return describeAggCalls(reader.read(relJson)); + } catch (IOException e) { + throw TestUtil.rethrow(e); + } + }); + assertThat(s, is(expected)); + } + /** Test case for * [CALCITE-4804] * Support Snapshot operator serialization and deserialization. */ diff --git a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java index 6e6d6807fb43..0e51b5bcc69e 100644 --- a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java +++ b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java @@ -2393,6 +2393,64 @@ private static RelNode sqlToRel(String sql, SchemaPlus defaultSchema, relFn(relFn).withOracle().ok(expectedOracle); } + /** Tests that RelToSqlConverter keeps a sub-query when the FILTER or the + * WITHIN GROUP sort key of an aggregate call is a column that contains a + * windowed aggregate. If the converter writes the expression of that column + * in place of the column, the generated query has a window function in the + * FILTER or in the sort key, which is not valid. */ + @Test void testAggregateFilterAndSortOnWindowFunction() { + // Equivalent SQL: + // SELECT COUNT(*) FILTER (WHERE f) AS c + // FROM (SELECT ROW_NUMBER() OVER (ORDER BY sal) > 1 AS f + // FROM emp) AS t + final Function filterFn = b -> b + .scan("EMP") + .project( + b.alias( + b.greaterThan( + b.aggregateCall(SqlStdOperatorTable.ROW_NUMBER) + .over() + .orderBy(b.field("SAL")) + .toRex(), + b.literal(1)), + "F")) + .aggregate(b.groupKey(), b.count().filter(b.field("F")).as("C")) + .build(); + // PostgreSQL does not allow a window function in FILTER. + // The expected query was run on PostgreSQL 14, with "scott"."EMP" + // changed to a table emp, and gives 13. + final String expectedPostgresql = "SELECT COUNT(*) FILTER (WHERE \"F\") AS \"C\"\n" + + "FROM (SELECT (ROW_NUMBER() OVER (ORDER BY \"SAL\")) > 1 AS \"F\"\n" + + "FROM \"scott\".\"EMP\") AS \"t\""; + relFn(filterFn).withPostgresql().ok(expectedPostgresql); + + // Equivalent SQL: + // SELECT LISTAGG(ename) WITHIN GROUP (ORDER BY r DESC) AS l + // FROM (SELECT ename, ROW_NUMBER() OVER (ORDER BY sal) AS r + // FROM emp) AS t + final Function sortFn = b -> b + .scan("EMP") + .project(b.field("ENAME"), + b.alias( + b.aggregateCall(SqlStdOperatorTable.ROW_NUMBER) + .over() + .orderBy(b.field("SAL")) + .toRex(), + "R")) + .aggregate(b.groupKey(), + b.aggregateCall(SqlStdOperatorTable.LISTAGG, b.field("ENAME")) + .sort(b.desc(b.field("R"))) + .as("L")) + .build(); + // MySQL does not allow a window function in an aggregate function. + final String expectedMysql = "SELECT GROUP_CONCAT(`ENAME` " + + "ORDER BY `R` IS NULL DESC, `R` DESC) AS `L`\n" + + "FROM (SELECT `ENAME`, " + + "ROW_NUMBER() OVER (ORDER BY `SAL` IS NULL, `SAL`) AS `R`\n" + + "FROM `scott`.`EMP`) AS `t`"; + relFn(sortFn).withMysql().ok(expectedMysql); + } + /** Test case for * [CALCITE-7655] * RelToSqlConverter incorrectly removes a subquery when grouping by a window function @@ -9027,6 +9085,44 @@ private void checkLiteral2(String expression, String expected) { sql(query).ok(expected); } + /** RelToSqlConverter writes a WITHIN GROUP sort key that is an expression + * as an ordinal, so the generated query sorts by a constant. */ + @Test void testWithinGroupExpression() { + final String query = "select \"product_class_id\", collect(\"net_weight\") " + + "within group (order by \"net_weight\" + 1) " + + "from \"product\" group by \"product_class_id\""; + final String expected = "SELECT \"product_class_id\", COLLECT(\"net_weight\") " + + "WITHIN GROUP (ORDER BY \"net_weight\" + 1)\n" + + "FROM \"foodmart\".\"product\"\n" + + "GROUP BY \"product_class_id\""; + sql(query).ok(expected); + } + + /** RelToSqlConverter drops WITHIN DISTINCT. */ + @Test void testWithinDistinct() { + final String query = "select \"product_class_id\", sum(\"net_weight\") " + + "within distinct (\"brand_name\") " + + "from \"product\" group by \"product_class_id\""; + final String expected = "SELECT \"product_class_id\", SUM(\"net_weight\") " + + "WITHIN DISTINCT (\"brand_name\")\n" + + "FROM \"foodmart\".\"product\"\n" + + "GROUP BY \"product_class_id\""; + sql(query).ok(expected); + } + + /** As {@link #testWithinDistinct()}, with a FILTER. FILTER must be outside + * WITHIN DISTINCT, so that the parser can read the query back. */ + @Test void testWithinDistinctFilter() { + final String query = "select \"product_class_id\", sum(\"net_weight\") " + + "within distinct (\"brand_name\") filter (where \"low_fat\") " + + "from \"product\" group by \"product_class_id\""; + final String expected = "SELECT \"product_class_id\", SUM(\"net_weight\") " + + "WITHIN DISTINCT (\"brand_name\") FILTER (WHERE \"low_fat\" IS TRUE)\n" + + "FROM \"foodmart\".\"product\"\n" + + "GROUP BY \"product_class_id\""; + sql(query).ok(expected); + } + @Test void testWithinGroup2() { final String query = "select \"product_class_id\", collect(\"net_weight\") " + "within group (order by \"low_fat\", \"net_weight\" desc nulls last) " diff --git a/core/src/test/java/org/apache/calcite/test/JdbcTest.java b/core/src/test/java/org/apache/calcite/test/JdbcTest.java index c68f4a6bf2d2..3060ef9cbb94 100644 --- a/core/src/test/java/org/apache/calcite/test/JdbcTest.java +++ b/core/src/test/java/org/apache/calcite/test/JdbcTest.java @@ -47,11 +47,14 @@ import org.apache.calcite.linq4j.QueryProvider; import org.apache.calcite.linq4j.Queryable; import org.apache.calcite.plan.RelOptPlanner; +import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.prepare.CalcitePrepareImpl; import org.apache.calcite.prepare.Prepare; import org.apache.calcite.rel.metadata.DefaultRelMetadataProvider; +import org.apache.calcite.rel.rules.AggregateExtractProjectRule; import org.apache.calcite.rel.rules.CoreRules; +import org.apache.calcite.rel.rules.MeasureRules; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rel.type.RelProtoDataType; @@ -3327,6 +3330,189 @@ void testInnerJoinValues(String format) { .returns("CP=0.75; CS=1.0; SXX=4.75; SYY=4.0\n"); } + /** Runs a query on the scott schema; a Hep program applies {@code rules} + * before the standard program, so that the rules see the plan that + * SqlToRelConverter produces. */ + private static CalciteAssert.AssertQuery queryAfterHepRules(String sql, + RelOptRule... rules) { + final Program program = + Programs.hep(ImmutableList.copyOf(rules), true, + DefaultRelMetadataProvider.INSTANCE); + return CalciteAssert.that() + .with(CalciteAssert.Config.SCOTT) + .query(sql) + .withHook(Hook.PROGRAM, + Hook.propertyJ(Programs.sequence(program, Programs.standard()))); + } + + /** AggregateFilterToCaseRule drops the WITHIN GROUP sort order. + * Result validated with PostgreSQL 14, using + * STRING_AGG(ename, ',' ORDER BY ename DESC) FILTER (WHERE sal > 1000). */ + @Test void testAggregateFilterToCaseKeepsSortOrder() { + final String sql = "select deptno,\n" + + " listagg(ename) within group (order by ename desc)\n" + + " filter (where sal > 1000) as l\n" + + "from emp group by deptno order by deptno"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_FILTER_TO_CASE) + .returns("DEPTNO=10; L=MILLER,KING,CLARK\n" + + "DEPTNO=20; L=SCOTT,JONES,FORD,ADAMS\n" + + "DEPTNO=30; L=WARD,TURNER,MARTIN,BLAKE,ALLEN\n"); + } + + /** AggregateExtractProjectRule removes the WITHIN GROUP sort key SAL from + * the new Project, because SAL is not an argument. + * Result validated with PostgreSQL 14, using + * STRING_AGG(ename, ',' ORDER BY sal, ename). */ + @Test void testAggregateExtractProjectKeepsSortKey() { + final String sql = "select deptno,\n" + + " listagg(ename) within group (order by sal, ename) as l\n" + + "from emp group by deptno order by deptno"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_PROJECT_MERGE, + AggregateExtractProjectRule.SCAN) + .returns("DEPTNO=10; L=MILLER,CLARK,KING\n" + + "DEPTNO=20; L=SMITH,ADAMS,JONES,FORD,SCOTT\n" + + "DEPTNO=30; L=JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE\n"); + } + + /** AggregateExtractProjectRule removes the WITHIN DISTINCT key ENAME from + * the new Project, and fails to map it. + * ENAME is unique, so the result is SUM(sal). + * Result validated with PostgreSQL 14, using SUM(sal). */ + @Test void testAggregateExtractProjectKeepsWithinDistinctKey() { + final String sql = "select deptno, sum(sal) within distinct (ename) as s\n" + + "from emp group by deptno order by deptno"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_PROJECT_MERGE, + AggregateExtractProjectRule.SCAN) + .returns("DEPTNO=10; S=8750.00\n" + + "DEPTNO=20; S=10875.00\n" + + "DEPTNO=30; S=9400.00\n"); + } + + /** AggregateFilterTransposeRule rolls up COUNT WITHIN DISTINCT as if it + * were a plain COUNT. + * Result validated with PostgreSQL 14, using COUNT(DISTINCT job). */ + @Test void testAggregateFilterTransposeWithinDistinct() { + final String sql = "select deptno, count(*) within distinct (job) as c\n" + + "from emp where mgr > 7000 group by deptno order by deptno"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_PROJECT_MERGE, + CoreRules.AGGREGATE_FILTER_TRANSPOSE) + .returns("DEPTNO=10; C=2\n" + + "DEPTNO=20; C=3\n" + + "DEPTNO=30; C=3\n"); + } + + /** AggregateUnionTransposeRule splits SUM WITHIN DISTINCT across the + * inputs of a UNION ALL, and keeps the WITHIN DISTINCT keys of the old + * input in the top Aggregate. + * Departments 10 and 20 each contribute every employee once. + * Result validated with PostgreSQL 14, using SUM(sal) over the distinct + * (ename, sal) pairs. */ + @Test void testAggregateUnionTransposeWithinDistinct() { + final String sql = "select sum(sal) within distinct (ename) as s\n" + + "from (select ename, sal from emp where deptno = 10\n" + + " union all\n" + + " select ename, sal from emp where deptno <= 20)"; + queryAfterHepRules(sql, CoreRules.PROJECT_SET_OP_TRANSPOSE, + CoreRules.PROJECT_MERGE, CoreRules.AGGREGATE_UNION_TRANSPOSE) + .returns("S=19625.00\n"); + } + + /** AggregateJoinTransposeRule splits SUM WITHIN DISTINCT across the inputs + * of a join, and keeps the WITHIN DISTINCT keys of the old input. + * Result validated with PostgreSQL 14, using SUM(DISTINCT d.deptno). */ + @Test void testAggregateJoinTransposeWithinDistinct() { + final String sql = "select d.dname,\n" + + " sum(d.deptno) within distinct (d.deptno) as s\n" + + "from dept d join emp e on d.deptno = e.deptno\n" + + "group by d.dname order by d.dname"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_PROJECT_MERGE, + CoreRules.AGGREGATE_JOIN_TRANSPOSE_EXTENDED) + .returns("DNAME=ACCOUNTING; S=10\n" + + "DNAME=RESEARCH; S=20\n" + + "DNAME=SALES; S=30\n"); + } + + /** AggregateJoinTransposeRule pushes BIT_XOR below a join, but it does not + * count the rows of the other input that join to each row. + * The XOR of a value with itself is 0, thus this count changes the result. + * Department 30 has 6 employees. Each EMPNO occurs 6 times, thus the + * correct BIT_XOR is 0. Departments 10 and 20 have an odd number of + * employees, thus their results do not change. + * Result validated with PostgreSQL 14. */ + @Test void testAggregateJoinTransposeBitXor() { + final String sql = "select e.deptno, bit_xor(e.empno) as x\n" + + "from emp e join emp f on e.deptno = f.deptno\n" + + "group by e.deptno order by e.deptno"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_PROJECT_MERGE, + CoreRules.AGGREGATE_JOIN_TRANSPOSE_EXTENDED) + .returns("DEPTNO=10; X=7687\n" + + "DEPTNO=20; X=7985\n" + + "DEPTNO=30; X=0\n"); + } + + /** AggregateExpandDistinctAggregatesRule, in the configuration that uses a + * join, splits SUM WITHIN DISTINCT into a bottom and a top Aggregate, and + * keeps the WITHIN DISTINCT keys of the old input in the top Aggregate. + * Result validated with PostgreSQL 14, using COUNT(DISTINCT mgr) and the + * sum of CHAR_LENGTH(job) over the distinct jobs of each department. */ + @Test void testAggregateExpandDistinctToJoinWithinDistinct() { + final String sql = "select deptno, count(distinct mgr) as c,\n" + + " sum(char_length(job)) within distinct (job) as s\n" + + "from emp group by deptno order by deptno"; + queryAfterHepRules(sql, + CoreRules.AGGREGATE_EXPAND_DISTINCT_AGGREGATES_TO_JOIN) + .returns("DEPTNO=10; C=2; S=21\n" + + "DEPTNO=20; C=4; S=19\n" + + "DEPTNO=30; C=2; S=20\n"); + } + + /** AggregateExpandDistinctAggregatesRule keeps the WITHIN DISTINCT keys of + * the old input when it rewrites a DISTINCT call next to COUNT(*), in both + * configurations: with grouping sets and with a join. + * ENAME is unique, so the result is SUM(DISTINCT sal). + * Result validated with PostgreSQL 14, using SUM(DISTINCT sal). */ + @Test void testAggregateExpandDistinctDistinctWithinDistinct() { + final String sql = "select deptno, count(*) as c,\n" + + " sum(distinct sal) within distinct (ename) as s\n" + + "from emp group by deptno order by deptno"; + final String expected = "DEPTNO=10; C=3; S=8750.00\n" + + "DEPTNO=20; C=5; S=7875.00\n" + + "DEPTNO=30; C=6; S=8150.00\n"; + queryAfterHepRules(sql, CoreRules.AGGREGATE_EXPAND_DISTINCT_AGGREGATES) + .returns(expected); + queryAfterHepRules(sql, + CoreRules.AGGREGATE_EXPAND_DISTINCT_AGGREGATES_TO_JOIN) + .returns(expected); + } + + /** MeasureRules.AGGREGATE drops the FILTER of AGGREGATE(c), so each job + * gets the count of all its employees. The default programs use + * MeasureRules.AGGREGATE2, which keeps the FILTER. + * Result validated with PostgreSQL 14, using + * COUNT(*) FILTER (WHERE deptno = 20). */ + @Test void testMeasureAggregateRuleKeepsFilter() { + final String sql = "select job,\n" + + " aggregate(c) filter (where deptno = 20) as c2\n" + + "from (select *, count(*) as measure c from emp)\n" + + "group by job order by job"; + final Program program = + Programs.hep( + ImmutableList.of(MeasureRules.AGGREGATE, CoreRules.PROJECT_MERGE, + MeasureRules.PROJECT), + true, DefaultRelMetadataProvider.INSTANCE); + CalciteAssert.that() + .with(CalciteAssert.Config.SCOTT) + .with(CalciteConnectionProperty.FUN, "calcite") + .query(sql) + .withHook(Hook.PROGRAM, + Hook.propertyJ(Programs.sequence(program, Programs.standard()))) + .returns("JOB=ANALYST; C2=2\n" + + "JOB=CLERK; C2=2\n" + + "JOB=MANAGER; C2=1\n" + + "JOB=PRESIDENT; C2=0\n" + + "JOB=SALESMAN; C2=0\n"); + } + @Test void testAggregateFilter() { final String s = "select \"the_month\",\n" + " count(*) as \"c\",\n" diff --git a/core/src/test/java/org/apache/calcite/test/LatticeTest.java b/core/src/test/java/org/apache/calcite/test/LatticeTest.java index 7c3aa99d9341..09fd4da5f85e 100644 --- a/core/src/test/java/org/apache/calcite/test/LatticeTest.java +++ b/core/src/test/java/org/apache/calcite/test/LatticeTest.java @@ -15,10 +15,12 @@ * limitations under the License. */ package org.apache.calcite.test; +import org.apache.calcite.adapter.java.ReflectiveSchema; import org.apache.calcite.jdbc.CalciteSchema; import org.apache.calcite.materialize.Lattice; import org.apache.calcite.materialize.Lattices; import org.apache.calcite.materialize.MaterializationService; +import org.apache.calcite.materialize.TileKey; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptUtil; @@ -29,10 +31,12 @@ import org.apache.calcite.sql.SqlDialect.DatabaseProduct; import org.apache.calcite.test.schemata.foodmart.FoodmartSchema; import org.apache.calcite.util.ImmutableBitSet; +import org.apache.calcite.util.Pair; import org.apache.calcite.util.TestUtil; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; @@ -501,6 +505,98 @@ private static CalciteAssert.AssertThat modelWithLattices( .sameResultWithMaterializationsDisabled(); } + /** Returns a model with a lattice on the table "emps" of + * {@link MaterializationTest.HrFKUKSchema}, which has one tile with the + * measure COUNT(*). The lattice does not create other tiles. + * + * @param dimensions Dimensions of the tile, for example + * {@code "'deptno'"} */ + private static CalciteAssert.AssertThat hrModelWithOneTile( + String dimensions) { + return CalciteAssert.model("{\n" + + " version: '1.0',\n" + + " defaultSchema: 'adhoc',\n" + + " schemas: [ {\n" + + " name: 'hr',\n" + + " type: 'custom',\n" + + " factory: '" + ReflectiveSchema.Factory.class.getName() + "',\n" + + " operand: {class: '" + + MaterializationTest.HrFKUKSchema.class.getName() + "'}\n" + + " }, {\n" + + " name: 'adhoc',\n" + + " lattices: [ {\n" + + " name: 'star',\n" + + " sql: 'select 1 from \"hr\".\"emps\"',\n" + + " auto: false,\n" + + " tiles: [ {\n" + + " dimensions: [ " + dimensions + " ],\n" + + " measures: [ { agg: 'count' } ]\n" + + " } ]\n" + + " } ]\n" + + " } ]\n" + + "}"); + } + + /** Test case for + * [CALCITE-7974] + * Many query rewrites lose the WITHIN GROUP sort order and/or FILTER and/or + * WITHIN DISTINCT of an Aggregate. + * + *

The tile has the measure COUNT(*). AggregateStarTableRule uses this + * measure for COUNT(*) WITHIN DISTINCT (salary), because + * Lattice.toMeasure ignores WITHIN DISTINCT. Department 10 has 3 + * employees and 2 distinct salaries (gave 3). + * + *

The first query makes sure that the planner uses the tile. + * Result validated with PostgreSQL 14, using COUNT(DISTINCT salary). */ + @Test void testTileWithinDistinct() { + final CalciteAssert.AssertThat with = hrModelWithOneTile("'deptno'"); + with.query("select \"deptno\", count(*) as c\n" + + "from \"hr\".\"emps\" group by \"deptno\"") + .enableMaterializations(true) + .explainContains("EnumerableTableScan(table=[[adhoc, m{1}]])") + .returnsUnordered("deptno=10; C=3", "deptno=20; C=1"); + with.query("select \"deptno\", count(*) within distinct (\"salary\") as c\n" + + "from \"hr\".\"emps\" group by \"deptno\"") + .enableMaterializations(true) + .returnsUnordered("deptno=10; C=2", "deptno=20; C=1"); + } + + /** The tile groups by DEPTNO and SALARY. A request for a tile that groups + * by DEPTNO must get this tile, because AggregateStarTableRule can roll it + * up. Since CALCITE-6763, MaterializationService.defineTile chose the best + * tile for the roll-up but did not return it, so AggregateStarTableRule + * never rolled up a tile. + * + *

The query checks that the roll-up does not answer + * COUNT(*) WITHIN DISTINCT (salary) from the COUNT(*) of the tile. + * Result validated with PostgreSQL 14, using COUNT(DISTINCT salary). */ + @Test void testTileRollUp() throws Exception { + final CalciteAssert.AssertThat with = + hrModelWithOneTile("'deptno', 'salary'"); + with.doWithConnection(c -> { + final SchemaPlus adhoc = + requireNonNull(c.getRootSchema().subSchemas().get("adhoc")); + final CalciteSchema adhocSchema = + requireNonNull(adhoc.unwrap(CalciteSchema.class)); + final Lattice lattice = + requireNonNull(adhocSchema.getLatticeMap().firstEntry()) + .getValue().getLattice(); + final Lattice.Tile tile = Iterables.getOnlyElement(lattice.computeTiles()); + // Field 1 is DEPTNO, field 3 is SALARY + assertThat(tile.bitSet(), is(ImmutableBitSet.of(1, 3))); + final Pair pair = + MaterializationService.instance().defineTile(lattice, + ImmutableBitSet.of(1), tile.measures, adhocSchema, false, false); + assertThat(pair == null ? null : pair.right.dimensions, + is(tile.bitSet())); + }); + with.query("select \"deptno\", count(*) within distinct (\"salary\") as c\n" + + "from \"hr\".\"emps\" group by \"deptno\"") + .enableMaterializations(true) + .returnsUnordered("deptno=10; C=2", "deptno=20; C=1"); + } + /** Tests a model that uses an algorithm to generate an initial set of * tiles. * diff --git a/core/src/test/java/org/apache/calcite/test/MaterializationTest.java b/core/src/test/java/org/apache/calcite/test/MaterializationTest.java index ad951f286d3f..843f3f5ec4da 100644 --- a/core/src/test/java/org/apache/calcite/test/MaterializationTest.java +++ b/core/src/test/java/org/apache/calcite/test/MaterializationTest.java @@ -128,6 +128,117 @@ public class MaterializationTest { .sameResultWithMaterializationsDisabled(); } + /** Model with a clone of the scott schema. */ + private static final String SCOTT_CLONE_MODEL = "{\n" + + " version: '1.0',\n" + + " defaultSchema: 'SCOTT_CLONE',\n" + + " schemas: [ {\n" + + " name: 'SCOTT_CLONE',\n" + + " type: 'custom',\n" + + " factory: 'org.apache.calcite.adapter.clone.CloneSchema$Factory',\n" + + " operand: {\n" + + " jdbcDriver: '" + JdbcTest.SCOTT.driver + "',\n" + + " jdbcUser: '" + JdbcTest.SCOTT.username + "',\n" + + " jdbcPassword: '" + JdbcTest.SCOTT.password + "',\n" + + " jdbcUrl: '" + JdbcTest.SCOTT.url + "',\n" + + " jdbcSchema: 'SCOTT'\n" + + " } } ]\n" + + "}"; + + /** Runs {@code query} with the materialized view {@code mv} on the scott + * schema, and checks the result. */ + private static void checkScottMaterialization(String mv, String query, + String expected) { + CalciteAssert.that() + .withMaterializations(SCOTT_CLONE_MODEL, "m0", mv) + .query(query) + .enableMaterializations(true) + .returns(expected); + } + + /** MaterializedViewAggregateRule answers SUM WITHIN DISTINCT from a plain + * SUM in the view (gave 310). + * Result validated with PostgreSQL 14, using SUM(DISTINCT deptno). */ + @Test void testMaterializationWithinDistinct() { + checkScottMaterialization( + "select deptno, empno, sum(cast(deptno as integer)) as s\n" + + "from emp group by deptno, empno", + "select sum(cast(deptno as integer)) within distinct (deptno) as s\n" + + "from emp", + "S=60\n"); + } + + /** MaterializedViewAggregateRule answers LISTAGG WITHIN GROUP from an + * unordered LISTAGG in the view. + * Result validated with PostgreSQL 14, using + * STRING_AGG(ename, ',' ORDER BY sal DESC, ename). */ + @Test void testMaterializationWithinGroup() { + checkScottMaterialization( + "select deptno, listagg(ename) as l from emp group by deptno", + "select deptno,\n" + + " listagg(ename) within group (order by sal desc, ename) as l\n" + + "from emp group by deptno order by deptno", + "DEPTNO=10; L=KING,CLARK,MILLER\n" + + "DEPTNO=20; L=FORD,SCOTT,JONES,ADAMS,SMITH\n" + + "DEPTNO=30; L=BLAKE,ALLEN,TURNER,MARTIN,WARD,JAMES\n"); + } + + /** Materialized view substitution rolls up COUNT WITHIN DISTINCT from the + * view as if it were a plain COUNT (gave 14). + * Result validated with PostgreSQL 14, using COUNT(DISTINCT deptno). */ + @Test void testMaterializationRollUpWithinDistinct() { + checkScottMaterialization( + "select empno, count(*) within distinct (deptno) as c\n" + + "from emp group by empno", + "select count(*) within distinct (deptno) as c from emp", + "C=3\n"); + } + + /** MaterializedViewAggregateRule answers a plain COUNT from a COUNT WITHIN + * DISTINCT in the view. + * Result validated with PostgreSQL 14, using COUNT(*). */ + @Test void testMaterializationViewWithinDistinct() { + checkScottMaterialization( + "select deptno, count(*) within distinct (job) as c\n" + + "from emp group by deptno", + "select deptno, count(*) as c from emp group by deptno order by deptno", + "DEPTNO=10; C=3\n" + + "DEPTNO=20; C=5\n" + + "DEPTNO=30; C=6\n"); + } + + /** The view groups by DEPTNO; the query has no GROUP BY. + * SubstitutionVisitor rolls up COUNT WITHIN DISTINCT with SUM0 over the + * column C of the view, and keeps the WITHIN DISTINCT key of the query. + * In the view, the field index of that key is the column C. Each + * department has 3 jobs, so the result was 3. + * Result validated with PostgreSQL 14, using COUNT(DISTINCT job). */ + @Test void testMaterializationRollUpWithinDistinctKey() { + checkScottMaterialization( + "select deptno, count(*) within distinct (job) as c\n" + + "from emp group by deptno", + "select count(*) within distinct (job) as c from emp", + "C=5\n"); + } + + /** The view groups by DEPTNO, SAL and B. SubstitutionVisitor computes + * MIN(sal) and COUNT(DISTINCT sal) from the column SAL of the view, and + * drops the FILTER (gave 800 and 4 for department 20). + * Result validated with PostgreSQL 14. */ + @Test void testMaterializationRollUpFilter() { + final String from = + "from (select deptno, sal, empno > 7700 as b from emp)\n"; + checkScottMaterialization( + "select deptno, sal, b\n" + + from + "group by deptno, sal, b", + "select deptno, min(sal) filter (where b) as m,\n" + + " count(distinct sal) filter (where b) as c\n" + + from + "group by deptno order by deptno", + "DEPTNO=10; M=1300.00; C=3\n" + + "DEPTNO=20; M=1100.00; C=2\n" + + "DEPTNO=30; M=950.00; C=2\n"); + } + /** Test case for * [CALCITE-7636] * Materialized view union rewriting drops rows when the view filter is not @@ -410,6 +521,7 @@ List> run(RelNode input) { /** * Hr schema with FK-UK relationship. */ + @ReflectiveSchema.Input public static class HrFKUKSchema { @Override public String toString() { return "HrFKUKSchema"; diff --git a/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java b/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java index 2ca9f81f3d87..0c4fc1148e3b 100644 --- a/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java +++ b/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java @@ -34,6 +34,7 @@ import org.apache.calcite.rel.RelDistributions; import org.apache.calcite.rel.RelFieldCollation; import org.apache.calcite.rel.RelNode; +import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.core.Combine; import org.apache.calcite.rel.core.Correlate; @@ -128,6 +129,7 @@ import java.util.Collections; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; @@ -1398,6 +1400,34 @@ private RexNode caseCall(RelBuilder b, RexNode ref, RexNode... nodes) { assertThat(f.apply(createBuilder()), hasTree(expected)); } + /** Tests that {@link RelBuilder.AggCall#over()} rejects an aggregate call + * that has a FILTER, WITHIN DISTINCT keys, a WITHIN GROUP sort or + * pre-operands. The windowed call cannot keep them, and if it drops them + * the query gives wrong results: for example, + * {@code SUM(sal) FILTER (WHERE job = 'CLERK') OVER (PARTITION BY deptno)} + * gave the sum of all the salaries in the department. */ + @Test void testOverRejectsFilterAndSort() { + final RelBuilder b = RelBuilder.create(config().build()); + b.scan("EMP"); + final Map calls = + ImmutableMap.of("FILTER is not supported", + b.sum(b.field("SAL")) + .filter(b.equals(b.field("JOB"), b.literal("CLERK"))), + "WITHIN DISTINCT is not supported", + b.sum(b.field("SAL")).unique(b.field("JOB")), + "WITHIN GROUP is not supported", + b.aggregateCall(SqlStdOperatorTable.LISTAGG, b.field("ENAME")) + .sort(b.field("SAL")), + "pre-operands are not supported", + b.literalAgg(1)); + calls.forEach((message, call) -> { + final IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, call::over); + assertThat(e.getMessage(), + is(message + " in a windowed aggregate call: " + call)); + }); + } + @Test void testRename() { final RelBuilder builder = RelBuilder.create(config().build()); @@ -2087,6 +2117,51 @@ private RelNode buildRelWithDuplicateAggregates( assertThat(root, hasTree(expected)); } + /** Tests that two calls to {@code LITERAL_AGG} with different values are + * not equal. {@link AggregateCall#hashCode()} uses the values, so + * {@link AggregateCall#equals(Object)} must use them too. */ + @Test void testLiteralAggCallEquals() { + final RelBuilder b = RelBuilder.create(config().build()); + final RelNode root = b.scan("EMP") + .aggregate(b.groupKey("DEPTNO"), + b.literalAgg(1).as("A"), + b.literalAgg(2).as("B")) + .build(); + final List calls = ((Aggregate) root).getAggCallList(); + // The calls return different values, so they are not equal + assertThat(calls.get(0).equals(calls.get(1)), is(false)); + assertThat(calls.get(1).equals(calls.get(0)), is(false)); + } + + /** Tests that {@link RelBuilder#aggregate} does not merge calls to + * {@code LITERAL_AGG} that have different values. */ + @Test void testAggregateDuplicateLiteralAggCalls() throws Exception { + // Equivalent SQL, if LITERAL_AGG(v) returns the constant v: + // SELECT deptno, LITERAL_AGG(1) AS a, LITERAL_AGG(2) AS b, + // LITERAL_AGG(2) AS c + // FROM emp + // GROUP BY deptno + // ORDER BY deptno + final RelBuilder b = RelBuilder.create(config().build()); + final RelNode root = b.scan("EMP") + .aggregate(b.groupKey("DEPTNO"), + b.literalAgg(1).as("A"), + b.literalAgg(2).as("B"), + b.literalAgg(2).as("C")) + .sort(b.field("DEPTNO")) + .build(); + // C is a copy of B. If C is taken from A, the value of C is 1. + final String expected = "" + + "DEPTNO=10; A=1; B=2; C=2\n" + + "DEPTNO=20; A=1; B=2; C=2\n" + + "DEPTNO=30; A=1; B=2; C=2\n"; + try (PreparedStatement preparedStatement = RelRunners.run(root)) { + final String s = + CalciteAssert.toString(preparedStatement.executeQuery()); + assertThat(s, is(expected)); + } + } + /** * Test reproducing issue CALCITE-6261. */ @@ -2280,6 +2355,29 @@ private RelNode buildRelWithDuplicateAggregates( hasTree(expected2)); } + /** RelBuilder fails with UnsupportedOperationException on a WITHIN GROUP + * sort key that is an expression. */ + @Test void testAggregateCallSortByExpression() { + // Equivalent SQL: + // SELECT COLLECT(ename) WITHIN GROUP (ORDER BY sal + 1) + // FROM emp + final RelBuilder builder = RelBuilder.create(config().build()); + final RelNode root = builder.scan("EMP") + .aggregate(builder.groupKey(), + builder.aggregateCall(SqlStdOperatorTable.COLLECT, + builder.field("ENAME")) + .sort( + builder.call(SqlStdOperatorTable.PLUS, + builder.field("SAL"), builder.literal(1)))) + .build(); + // The sort key of COLLECT is the input field that computes SAL + 1 + final Aggregate aggregate = (Aggregate) root; + final Project project = (Project) aggregate.getInput(); + final int key = aggregate.getAggCallList().get(0).collation + .getFieldCollations().get(0).getFieldIndex(); + assertThat(project.getProjects().get(key), hasToString("+($5, 1)")); + } + /** Tests that {@link RelBuilder#aggregate} on top of a {@link Project} prunes * away expressions that are not used. * @@ -5205,6 +5303,46 @@ private static RelBuilder assertSize(RelBuilder b, assertThat(f.apply(createBuilder()), hasTree(expected)); } + /** Tests that {@link RelBuilder#pivot} keeps the FILTER of an aggregate + * call, and adds the condition on the axis to it. */ + @Test void testPivotKeepsFilter() throws Exception { + // Equivalent SQL (the SQL validator rejects FILTER in PIVOT): + // SELECT * + // FROM (SELECT deptno, job, sal FROM emp) + // PIVOT (SUM(sal) FILTER (WHERE job = 'CLERK') AS s + // FOR deptno IN (10 AS d10, 20 AS d20)) + // + // translates to + // SELECT + // SUM(sal) FILTER (WHERE job = 'CLERK' AND deptno = 10) AS d10_s, + // SUM(sal) FILTER (WHERE job = 'CLERK' AND deptno = 20) AS d20_s + // FROM emp + final RelBuilder b = RelBuilder.create(config().build()); + final RelNode root = b.scan("EMP") + .pivot(b.groupKey(), + Collections.singletonList( + b.sum(b.field("SAL")) + .filter(b.equals(b.field("JOB"), b.literal("CLERK"))) + .as("S")), + Collections.singletonList(b.field("DEPTNO")), + ImmutableMap.>builder() + .put("D10", Collections.singletonList(b.literal(10))) + .put("D20", Collections.singletonList(b.literal(20))) + .build() + .entrySet()) + .build(); + // Each value is the sum of the salaries of the clerks in the department. + // If the FILTER is lost, the values are the sums of all the salaries in + // the department (8750.00 and 10875.00). + // Result validated with PostgreSQL 14. + final String expected = "D10_S=1300.00; D20_S=1900.00\n"; + try (PreparedStatement preparedStatement = RelRunners.run(root)) { + final String s = + CalciteAssert.toString(preparedStatement.executeQuery()); + assertThat(s, is(expected)); + } + } + @Test void testUnpivot() { // Equivalent SQL: // SELECT * diff --git a/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java b/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java index 691469d5218f..bf66c808ec9a 100644 --- a/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java +++ b/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java @@ -7409,6 +7409,32 @@ public boolean test(Project project) { .checkUnchanged(); } + /** AggregateFilterToCaseRule must not change FILTER into CASE for an + * aggregate function that does not skip NULL inputs. The CASE gives NULL + * for the rows that FILTER removes, and the function would see these NULL + * values. */ + @Test void testAggregateFilterToCaseWithCustomNullAwareUdaf() { + final SqlAggFunction nullAwareAgg = + new SqlAggFunction("NULL_AWARE_SUM", null, SqlKind.SUM, ReturnTypes.ARG0_NULLABLE, null, + OperandTypes.NUMERIC, SqlFunctionCategory.NUMERIC, false, false, + Optionality.FORBIDDEN) { + @Override public boolean skipsNullInputs() { + return false; // NULL values are semantically relevant + } + }; + + final String sql = "select null_aware_sum(sal) filter (where deptno > 10)\n" + + "from emp"; + + sql(sql) + .withFactory(t -> + t.withOperatorTable(opTab -> + SqlOperatorTables.chain(opTab, + SqlOperatorTables.of(ImmutableList.of(nullAwareAgg))))) + .withRule(CoreRules.AGGREGATE_FILTER_TO_CASE) + .checkUnchanged(); + } + @Test void testPullAggregateThroughUnion() { final String sql = "select deptno, job from" + " (select deptno, job from emp as e1" diff --git a/core/src/test/resources/org/apache/calcite/test/RelOptRulesTest.xml b/core/src/test/resources/org/apache/calcite/test/RelOptRulesTest.xml index 7dbd0e2c7b21..cf1edf0d9dc1 100644 --- a/core/src/test/resources/org/apache/calcite/test/RelOptRulesTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/RelOptRulesTest.xml @@ -330,6 +330,19 @@ LogicalProject(SUM0_MATCH=[$3], SUM_DISTINCT_NOT_MATCH=[$0], COUNT_DISTINCT_MATC LogicalAggregate(group=[{}], SUM_DISTINCT_NOT_MATCH=[SUM(DISTINCT $0) FILTER $1], COUNT_DISTINCT_MATCH=[COUNT(DISTINCT $2)], COUNT_STAR_MATCH=[COUNT($3)], agg#3=[$SUM0($4)]) LogicalProject(EMPNO=[$0], $f3=[=($7, 20)], $f7=[CASE(=($2, 'CLERK'), $7, null:INTEGER)], $f8=[CASE(=($7, 40), 0, null:INTEGER)], $f9=[CASE(=($7, 10), $5, null:INTEGER)]) LogicalTableScan(table=[[CATALOG, SALES, EMP]]) +]]> + + + + + 10) +from emp]]> + + + ($7, 10)]) + LogicalTableScan(table=[[CATALOG, SALES, EMP]]) ]]> diff --git a/core/src/test/resources/sql/agg.iq b/core/src/test/resources/sql/agg.iq index 441150eca51e..a97771179fba 100644 --- a/core/src/test/resources/sql/agg.iq +++ b/core/src/test/resources/sql/agg.iq @@ -5085,3 +5085,57 @@ order by deptno nulls last, ename nulls first; # Nested forms and restrictions are in # SqlValidatorTest.testGroupingSetsStarNested. !use post + +# [CALCITE-7974] Many query rewrites lose the WITHIN GROUP sort order and/or +# FILTER and/or WITHIN DISTINCT of an Aggregate +# AggregateCaseToFilterRule changes AGG(CASE WHEN c THEN x END) to +# AGG(x) FILTER (WHERE c). It must keep the WITHIN GROUP sort order. +# Result validated with PostgreSQL 14, using +# STRING_AGG(CASE WHEN deptno = 20 THEN ename END, ',' ORDER BY ename DESC). +!use scott +SELECT LISTAGG(CASE WHEN deptno = 20 THEN ename END) + WITHIN GROUP (ORDER BY ename DESC) AS names +FROM emp; ++------------------------------+ +| NAMES | ++------------------------------+ +| SMITH,SCOTT,JONES,FORD,ADAMS | ++------------------------------+ +(1 row) + +!ok + +# The rule does not change a call with WITHIN DISTINCT. Before, it dropped +# WITHIN DISTINCT and the result was 80 (department 20 has two clerks). +# Result validated with PostgreSQL 14, using +# SUM(DISTINCT CASE WHEN job = 'CLERK' THEN deptno END). +SELECT SUM(CASE WHEN job = 'CLERK' THEN deptno END) + WITHIN DISTINCT (deptno) AS s +FROM emp; ++----+ +| S | ++----+ +| 60 | ++----+ +(1 row) + +!ok + +# The validator fails on FILTER after WITHIN GROUP in PERCENTILE_DISC +# (UnsupportedOperationException in SqlOperatorBinding.getCollationType) +# Result validated with PostgreSQL 14. +select percentile_disc(0.5) within group (order by sal) + filter (where deptno = 10) as p, + percentile_disc(0.5) within group (order by sal desc) + filter (where deptno = 10) as pd, + percentile_cont(0.5) within group (order by sal) + filter (where deptno = 10) as pc +from emp; ++---------+---------+---------+ +| P | PD | PC | ++---------+---------+---------+ +| 2450.00 | 2450.00 | 2450.00 | ++---------+---------+---------+ +(1 row) + +!ok diff --git a/core/src/test/resources/sql/sub-query.iq b/core/src/test/resources/sql/sub-query.iq index 13f48cfac5e8..74b522e01fb6 100644 --- a/core/src/test/resources/sql/sub-query.iq +++ b/core/src/test/resources/sql/sub-query.iq @@ -11625,3 +11625,124 @@ from dept; (4 rows) !ok + +# [CALCITE-7974] Many query rewrites lose the WITHIN GROUP sort order and/or +# FILTER and/or WITHIN DISTINCT of an Aggregate +# All results validated with PostgreSQL 14. +# PostgreSQL query: STRING_AGG(e.ename, ',' ORDER BY e.ename DESC). +SELECT d.deptno, + (SELECT LISTAGG(e.ename) WITHIN GROUP (ORDER BY e.ename DESC) + FROM emp e WHERE e.deptno = d.deptno) AS names +FROM dept d +ORDER BY d.deptno; ++--------+--------------------------------------+ +| DEPTNO | NAMES | ++--------+--------------------------------------+ +| 10 | MILLER,KING,CLARK | +| 20 | SMITH,SCOTT,JONES,FORD,ADAMS | +| 30 | WARD,TURNER,MARTIN,JAMES,BLAKE,ALLEN | +| 40 | | ++--------+--------------------------------------+ +(4 rows) + +!ok + +# Same, with an expression over the aggregate +SELECT d.deptno, + (SELECT LOWER(LISTAGG(e.ename) WITHIN GROUP (ORDER BY e.ename DESC)) + FROM emp e WHERE e.deptno = d.deptno) AS names +FROM dept d +ORDER BY d.deptno; ++--------+--------------------------------------+ +| DEPTNO | NAMES | ++--------+--------------------------------------+ +| 10 | miller,king,clark | +| 20 | smith,scott,jones,ford,adams | +| 30 | ward,turner,martin,james,blake,allen | +| 40 | | ++--------+--------------------------------------+ +(4 rows) + +!ok + +# The type of PERCENTILE_DISC is the type of its sort key. A wrong sort +# key gave "Decorrelation produced a relation with a different type". +SELECT d.deptno, + (SELECT PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY e.sal) + FROM emp e WHERE e.deptno = d.deptno) AS median_sal +FROM dept d +ORDER BY d.deptno; ++--------+------------+ +| DEPTNO | MEDIAN_SAL | ++--------+------------+ +| 10 | 2450.00 | +| 20 | 2975.00 | +| 30 | 1250.00 | +| 40 | | ++--------+------------+ +(4 rows) + +!ok + +# ENAME is unique, so SUM(e.sal) WITHIN DISTINCT (e.ename) is SUM(e.sal). +# With the wrong key it was SUM(DISTINCT e.sal): 7875.00 for DEPTNO 20. +# PostgreSQL query: SUM(x.sal) FROM (SELECT DISTINCT e.ename, e.sal ...) AS x. +SELECT d.deptno, + (SELECT SUM(e.sal) WITHIN DISTINCT (e.ename) + FROM emp e WHERE e.deptno = d.deptno) AS total_sal +FROM dept d +ORDER BY d.deptno; ++--------+-----------+ +| DEPTNO | TOTAL_SAL | ++--------+-----------+ +| 10 | 8750.00 | +| 20 | 10875.00 | +| 30 | 9400.00 | +| 40 | | ++--------+-----------+ +(4 rows) + +!ok + +# Same, with an expression over the aggregate +SELECT d.deptno, + (SELECT CAST(SUM(e.sal) WITHIN DISTINCT (e.ename) AS INTEGER) + FROM emp e WHERE e.deptno = d.deptno) AS total_sal +FROM dept d +ORDER BY d.deptno; ++--------+-----------+ +| DEPTNO | TOTAL_SAL | ++--------+-----------+ +| 10 | 8750 | +| 20 | 10875 | +| 30 | 9400 | +| 40 | | ++--------+-----------+ +(4 rows) + +!ok + +# TopDownGeneralDecorrelator gives a wrong result when the input of an +# Aggregate is a Join whose left input gets the correlation columns. +# The correlation columns move the columns of the right input, but the +# decorrelator finds the group key at its old position. Here DNO was read +# from the correlation column D.DEPTNO, which gave 20 for DEPTNO 10 and 20. +# Result validated with PostgreSQL 14. +SELECT d.deptno, + (SELECT SUM(t.dno) + FROM (SELECT DISTINCT e.deptno, d2.deptno AS dno + FROM (SELECT deptno FROM emp WHERE deptno > d.deptno) AS e + JOIN dept AS d2 ON e.deptno = d2.deptno) AS t) AS s +FROM dept AS d +ORDER BY d.deptno; ++--------+----+ +| DEPTNO | S | ++--------+----+ +| 10 | 50 | +| 20 | 30 | +| 30 | | +| 40 | | ++--------+----+ +(4 rows) + +!ok diff --git a/core/src/test/resources/sql/within-distinct.iq b/core/src/test/resources/sql/within-distinct.iq index 8e04c3d642b9..7a44d7757fe5 100644 --- a/core/src/test/resources/sql/within-distinct.iq +++ b/core/src/test/resources/sql/within-distinct.iq @@ -963,4 +963,79 @@ FROM FriendStates; !ok +# AggregateMergeRule merges SUM over SUM WITHIN DISTINCT, and the merged +# call loses WITHIN DISTINCT (gave 60) +# Result validated with PostgreSQL 14, using SUM(DISTINCT deptno) for the +# inner call. +!use scott +select sum(s) as c +from (select job, sum(cast(deptno as integer)) within distinct (deptno) as s + from emp group by job); ++-----+ +| C | ++-----+ +| 180 | ++-----+ +(1 row) + +!ok + +# AggregateExpandDistinctAggregatesRule keeps the WITHIN DISTINCT keys of +# the old input, so a DISTINCT call next to a WITHIN DISTINCT call crashed. +# ENAME and EMPNO are unique, so WITHIN DISTINCT has no effect. +# Results validated with PostgreSQL 14, without WITHIN DISTINCT. +select sum(distinct sal) within distinct (ename) as s from emp; ++----------+ +| S | ++----------+ +| 24775.00 | ++----------+ +(1 row) + +!ok + +select count(distinct sal) as c, max(sal) within distinct (ename) as m +from emp; ++----+---------+ +| C | M | ++----+---------+ +| 12 | 5000.00 | ++----+---------+ +(1 row) + +!ok + +select count(distinct deptno) as c, + count(comm) within distinct (job, ename, empno) as n +from emp; ++---+---+ +| C | N | ++---+---+ +| 3 | 4 | ++---+---+ +(1 row) + +!ok + +# AggregateExpandWithinDistinctRule drops the WITHIN GROUP sort order of a +# DISTINCT call next to a WITHIN DISTINCT call +# Result validated with PostgreSQL 14, using +# STRING_AGG(DISTINCT job, ',' ORDER BY job DESC) and SUM(sal). +select deptno, + listagg(distinct job, ',') within group (order by job desc) as jobs, + sum(sal) within distinct (ename) as s +from emp +group by deptno +order by deptno; ++--------+-------------------------+----------+ +| DEPTNO | JOBS | S | ++--------+-------------------------+----------+ +| 10 | PRESIDENT,MANAGER,CLERK | 8750.00 | +| 20 | MANAGER,CLERK,ANALYST | 10875.00 | +| 30 | SALESMAN,MANAGER,CLERK | 9400.00 | ++--------+-------------------------+----------+ +(3 rows) + +!ok + # End within-distinct.iq diff --git a/testkit/src/main/java/org/apache/calcite/test/schemata/hr/HrSchema.java b/testkit/src/main/java/org/apache/calcite/test/schemata/hr/HrSchema.java index d1c2a655729d..e353ea9b44e8 100644 --- a/testkit/src/main/java/org/apache/calcite/test/schemata/hr/HrSchema.java +++ b/testkit/src/main/java/org/apache/calcite/test/schemata/hr/HrSchema.java @@ -16,6 +16,7 @@ */ package org.apache.calcite.test.schemata.hr; +import org.apache.calcite.adapter.java.ReflectiveSchema; import org.apache.calcite.schema.QueryableTable; import org.apache.calcite.schema.TranslatableTable; import org.apache.calcite.util.Smalls; @@ -54,6 +55,7 @@ * * */ +@ReflectiveSchema.Input public class HrSchema { @Override public String toString() { return "HrSchema";