Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions core/src/main/java/org/apache/calcite/rel/externalize/RelJson.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -344,15 +344,28 @@ private AggregateCall toAggCall(Map<String, Object> jsonAggCall) {
requireNonNull((List<Integer>) 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<Integer> jsonDistinctKeys =
(List<Integer>) jsonAggCall.get("distinctKeys");
@SuppressWarnings("unchecked")
final List<Map<String, Object>> jsonCollation =
(List<Map<String, Object>>) 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1421,15 +1420,16 @@
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,

Check warning on line 1429 in core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Method has 8 parameters, which is greater than 7 authorized.

See more on https://sonarcloud.io/project/issues?id=apache_calcite&issues=AaIelzkhE8TPPZNcWyyA&open=AaIelzkhE8TPPZNcWyyA&pullRequest=5464

Check failure on line 1429 in core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=apache_calcite&issues=AaIelzkhE8TPPZNcWyyB&open=AaIelzkhE8TPPZNcWyyB&pullRequest=5464
List<SqlNode> preOperandList, List<SqlNode> 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;

Expand All @@ -1440,7 +1440,7 @@
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);
}

Expand All @@ -1465,16 +1465,21 @@
newOperandList.addAll(Util.skip(operandList));
}
return toSql(op, distinct, preOperandList, newOperandList, -1,
collation, approximate);
distinctKeys, collation, approximate);
}

if (op instanceof SqlCountAggFunction && operandList.isEmpty()) {
// If there is no parameter in "count" function, add a star identifier
// 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;
Expand All @@ -1500,7 +1505,7 @@
}
final List<SqlNode> 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));
Expand Down Expand Up @@ -2520,10 +2525,9 @@
if (node instanceof SqlSelect) {
SqlNodeList selectList = ((SqlSelect) node).getSelectList();
if (!selectList.equals(SqlNodeList.SINGLETON_STAR)) {
final Set<Integer> aggregatesArgs = new HashSet<>();
for (AggregateCall aggregateCall : aggregate.getAggCallList()) {
aggregatesArgs.addAll(aggregateCall.getArgList());
}
final Set<Integer> aggregatesArgs =
RelOptUtil.getAllFields2(ImmutableBitSet.of(),
aggregate.getAggCallList());
for (int aggregatesArg : aggregatesArgs) {
if (selectList.get(aggregatesArg) instanceof SqlBasicCall) {
final SqlBasicCall call = (SqlBasicCall) selectList.get(aggregatesArg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ && isThreeArgCase(project.getProjects().get(singleArg))) {
private static @Nullable AggregateCall transform(AggregateCall call,
Project project, List<RexNode> newProjects) {
final int singleArg = soleArgument(call);
if (singleArg < 0) {
if (singleArg < 0 || call.distinctKeys != null) {
return null;
}

Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -85,27 +85,18 @@ 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<RexNode> projects = new ArrayList<>();
final Mapping mapping =
Mappings.create(MappingType.INVERSE_SURJECTION,
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++);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -109,7 +108,7 @@ protected AggregateFilterToCaseRule(Config config) {

private static AggregateCall transform(AggregateCall call,
RexBuilder rexBuilder, RelDataTypeFactory typeFactory, List<RexNode> newProjects) {
if (!call.hasFilter()) {
if (!call.hasFilter() || !call.getAggregation().skipsNullInputs()) {
return call;
}
final SqlKind kind = call.getAggregation().getKind();
Expand Down Expand Up @@ -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());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading
Loading