Skip to content
Merged
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 @@ -106,7 +106,9 @@
import com.facebook.presto.sql.planner.iterative.rule.RemoveRedundantIdentityProjections;
import com.facebook.presto.sql.planner.iterative.rule.RemoveRedundantLimit;
import com.facebook.presto.sql.planner.iterative.rule.RemoveRedundantSort;
import com.facebook.presto.sql.planner.iterative.rule.RemoveRedundantSortColumns;
import com.facebook.presto.sql.planner.iterative.rule.RemoveRedundantTopN;
import com.facebook.presto.sql.planner.iterative.rule.RemoveRedundantTopNColumns;
import com.facebook.presto.sql.planner.iterative.rule.RemoveTrivialFilters;
import com.facebook.presto.sql.planner.iterative.rule.RemoveUnreferencedScalarApplyNodes;
import com.facebook.presto.sql.planner.iterative.rule.RemoveUnreferencedScalarLateralNodes;
Expand Down Expand Up @@ -557,7 +559,9 @@ public PlanOptimizers(
ImmutableSet.of(
new RemoveRedundantDistinct(),
new RemoveRedundantTopN(),
new RemoveRedundantTopNColumns(),
new RemoveRedundantSort(),
new RemoveRedundantSortColumns(),
new RemoveRedundantLimit(),
new RemoveRedundantDistinctLimit(),
new RemoveRedundantAggregateDistinct(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.iterative.rule;

import com.facebook.presto.matching.Captures;
import com.facebook.presto.matching.Pattern;
import com.facebook.presto.spi.plan.LogicalProperties;
import com.facebook.presto.spi.plan.OrderingScheme;
import com.facebook.presto.sql.planner.iterative.GroupReference;
import com.facebook.presto.sql.planner.iterative.Rule;
import com.facebook.presto.sql.planner.plan.SortNode;

import static com.facebook.presto.sql.planner.iterative.rule.Util.pruneOrderingColumns;
import static com.facebook.presto.sql.planner.plan.Patterns.sort;

/**
* Removes sort columns from input if the source has a Key that refers to the ordering columns
*/
public class RemoveRedundantSortColumns
implements Rule<SortNode>
{
private static final Pattern<SortNode> PATTERN = sort().matching(p -> ((GroupReference) p.getSource()).getLogicalProperties().isPresent());

@Override
public Pattern<SortNode> getPattern()
{
return PATTERN;
}

@Override
public Result apply(SortNode node, Captures captures, Context context)
{
OrderingScheme orderingScheme = node.getOrderingScheme();

LogicalProperties sourceLogicalProperties = ((GroupReference) node.getSource()).getLogicalProperties().get();
OrderingScheme newOrderingScheme = pruneOrderingColumns(orderingScheme, sourceLogicalProperties);

if (newOrderingScheme.equals(orderingScheme)) {
return Result.empty();
}

return Result.ofPlanNode(new SortNode(node.getSourceLocation(), node.getId(), node.getStatsEquivalentPlanNode(), node.getSource(), newOrderingScheme, node.isPartial()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.iterative.rule;

import com.facebook.presto.matching.Captures;
import com.facebook.presto.matching.Pattern;
import com.facebook.presto.spi.plan.LogicalProperties;
import com.facebook.presto.spi.plan.OrderingScheme;
import com.facebook.presto.spi.plan.TopNNode;
import com.facebook.presto.sql.planner.iterative.GroupReference;
import com.facebook.presto.sql.planner.iterative.Rule;

import static com.facebook.presto.sql.planner.iterative.rule.Util.pruneOrderingColumns;
import static com.facebook.presto.sql.planner.plan.Patterns.topN;

/**
* Removes TopN columns from input if the source has a Key that refers to the ordering columns
*/
public class RemoveRedundantTopNColumns
implements Rule<TopNNode>
{
private static final Pattern<TopNNode> PATTERN = topN().matching(p -> ((GroupReference) p.getSource()).getLogicalProperties().isPresent());

@Override
public Pattern<TopNNode> getPattern()
{
return PATTERN;
}

@Override
public Result apply(TopNNode node, Captures captures, Context context)
{
OrderingScheme orderingScheme = node.getOrderingScheme();

LogicalProperties sourceLogicalProperties = ((GroupReference) node.getSource()).getLogicalProperties().get();
OrderingScheme newOrderingScheme = pruneOrderingColumns(orderingScheme, sourceLogicalProperties);

if (newOrderingScheme.equals(orderingScheme)) {
return Result.empty();
}

return Result.ofPlanNode(new TopNNode(node.getSourceLocation(), node.getId(), node.getSource(), node.getCount(), newOrderingScheme, node.getStep()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
*/
package com.facebook.presto.sql.planner.iterative.rule;

import com.facebook.presto.spi.plan.LogicalProperties;
import com.facebook.presto.spi.plan.Ordering;
import com.facebook.presto.spi.plan.OrderingScheme;
import com.facebook.presto.spi.plan.PlanNode;
import com.facebook.presto.spi.plan.PlanNodeIdAllocator;
import com.facebook.presto.spi.plan.ProjectNode;
Expand All @@ -25,6 +28,7 @@
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
Expand All @@ -33,6 +37,7 @@
import static com.facebook.presto.sql.planner.plan.AssignmentUtils.identityAssignments;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;

class Util
{
Expand Down Expand Up @@ -124,4 +129,30 @@ public static Optional<PlanNode> restrictChildOutputs(PlanNodeIdAllocator idAllo
}
return Optional.of(node.replaceChildren(newChildrenBuilder.build()));
}

public static OrderingScheme pruneOrderingColumns(OrderingScheme nodeOrderingScheme, LogicalProperties sourceLogicalProperties)
{
requireNonNull(nodeOrderingScheme, "nodeOrderingScheme is null");
requireNonNull(sourceLogicalProperties, "nodeOrderingScheme is null");

List<VariableReferenceExpression> orderingVariables = nodeOrderingScheme.getOrderBy().stream().map(Ordering::getVariable).collect(toImmutableList());
int sizeSmallestDistinctPrefix = sizeSmallestDistinctPrefix(sourceLogicalProperties, orderingVariables);
if (sizeSmallestDistinctPrefix == 0) {
return nodeOrderingScheme;
}
List<Ordering> keyPrefix = nodeOrderingScheme.getOrderBy().subList(0, sizeSmallestDistinctPrefix);
return new OrderingScheme(keyPrefix);
}

private static int sizeSmallestDistinctPrefix(LogicalProperties logicalProperties, List<VariableReferenceExpression> candidateVariables)
{
HashSet<VariableReferenceExpression> possibleKeySet = new HashSet<>();
for (int prefixSize = 1; prefixSize < candidateVariables.size(); prefixSize++) {
possibleKeySet.add(candidateVariables.get(prefixSize - 1));
if (logicalProperties.isDistinct(possibleKeySet)) {
return prefixSize;
}
}
return 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public OptimizerAssert on(String sql)
{
checkState(plan == null, "plan has already been set");

//get an initial plan and apply a minimal set of optimizers in preparation foor applying the specific rules to be tested
//get an initial plan and apply a minimal set of optimizers in preparation for applying the specific rules to be tested
Plan result = queryRunner.inTransaction(session -> queryRunner.createPlan(session, sql, getMinimalOptimizers(), Optimizer.PlanStage.OPTIMIZED, WarningCollector.NOOP));
plan = result.getRoot();
types = result.getTypes();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.iterative.rule;

import com.facebook.presto.sql.planner.assertions.PlanMatchPattern;
import com.facebook.presto.sql.planner.iterative.properties.LogicalPropertiesProviderImpl;
import com.facebook.presto.sql.planner.iterative.rule.test.BaseRuleTest;
import com.facebook.presto.sql.planner.iterative.rule.test.RuleTester;
import com.facebook.presto.sql.relational.FunctionResolution;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.anyTree;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.output;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.sort;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.tableScan;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.topN;
import static com.facebook.presto.sql.tree.SortItem.NullOrdering.LAST;
import static com.facebook.presto.sql.tree.SortItem.Ordering.ASCENDING;
import static com.facebook.presto.sql.tree.SortItem.Ordering.DESCENDING;
import static java.util.Collections.emptyList;

public class TestRedundantSortColumnsRemoval
extends BaseRuleTest
{
private LogicalPropertiesProviderImpl logicalPropertiesProvider;

@BeforeClass
public final void setUp()
{
tester = new RuleTester(emptyList(), ImmutableMap.of("exploit_constraints", Boolean.toString(true)));
logicalPropertiesProvider = new LogicalPropertiesProviderImpl(new FunctionResolution(tester.getMetadata().getFunctionAndTypeManager().getFunctionAndTypeResolver()));
}

@Test
public void testRemoveRedundantColumnsFromTopN()
{
// OrderBy prefix matches GroupBy columns clause exactly
tester().assertThat(ImmutableSet.of(new MergeLimitWithSort(), new RemoveRedundantTopNColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY orderkey, custkey, sum(totalprice), min(orderdate) LIMIT 10")
.matches(topNMatchWith(ImmutableList.of(sort("ORDERKEY", ASCENDING, LAST), sort("CUSTKEY", ASCENDING, LAST))));

// Flipped order matches too since the Grouping set remains the same
tester().assertThat(ImmutableSet.of(new MergeLimitWithSort(), new RemoveRedundantTopNColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY custkey, orderkey, sum(totalprice), min(orderdate) LIMIT 10")
.matches(topNMatchWith(ImmutableList.of(sort("CUSTKEY", ASCENDING, LAST), sort("ORDERKEY", ASCENDING, LAST))));

// No impact due to sort direction
tester().assertThat(ImmutableSet.of(new MergeLimitWithSort(), new RemoveRedundantTopNColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY custkey DESC, orderkey ASC, sum(totalprice), min(orderdate) LIMIT 10")
.matches(topNMatchWith(ImmutableList.of(sort("CUSTKEY", DESCENDING, LAST), sort("ORDERKEY", ASCENDING, LAST))));

// Negative test - No prefix matches the grouping set, so TopN columns are not pruned
tester().assertThat(ImmutableSet.of(new MergeLimitWithSort(), new RemoveRedundantTopNColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY orderkey, sum(totalprice), custkey, min(orderdate) LIMIT 10")
.doesNotMatch(topNMatchWith(ImmutableList.of(sort("ORDERKEY", ASCENDING, LAST), sort("CUSTKEY", ASCENDING, LAST))));
}

@Test
public void testRemoveRedundantColumnsFromSort()
{
// OrderBy prefix matches GroupBy columns clause exactly
tester().assertThat(ImmutableSet.of(new RemoveRedundantSortColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY orderkey, custkey, sum(totalprice), min(orderdate)")
.matches(sortWith(ImmutableList.of(sort("ORDERKEY", ASCENDING, LAST), sort("CUSTKEY", ASCENDING, LAST))));

// Flipped order matches too since the Grouping set remains the same
tester().assertThat(ImmutableSet.of(new RemoveRedundantSortColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY custkey, orderkey, sum(totalprice), min(orderdate)")
.matches(sortWith(ImmutableList.of(sort("CUSTKEY", ASCENDING, LAST), sort("ORDERKEY", ASCENDING, LAST))));

// No impact due to sort direction
tester().assertThat(ImmutableSet.of(new RemoveRedundantSortColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY custkey DESC, orderkey ASC, sum(totalprice), min(orderdate)")
.matches(sortWith(ImmutableList.of(sort("CUSTKEY", DESCENDING, LAST), sort("ORDERKEY", ASCENDING, LAST))));

// Negative test - No prefix matches the grouping set, so TopN columns are not pruned
tester().assertThat(ImmutableSet.of(new RemoveRedundantSortColumns()), logicalPropertiesProvider)
.on("SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders GROUP BY orderkey, custkey " +
"ORDER BY orderkey, sum(totalprice), custkey, min(orderdate)")
.doesNotMatch(sortWith(ImmutableList.of(sort("ORDERKEY", ASCENDING, LAST), sort("CUSTKEY", ASCENDING, LAST))));
}

private static PlanMatchPattern topNMatchWith(ImmutableList<PlanMatchPattern.Ordering> orderBy)
{
return output(
topN(10, orderBy,
anyTree(
tableScan("orders", ImmutableMap.of(
"ORDERKEY", "orderkey",
"CUSTKEY", "custkey")))));
}

private static PlanMatchPattern sortWith(ImmutableList<PlanMatchPattern.Ordering> orderBy)
{
return output(
sort(orderBy,
anyTree(
tableScan("orders", ImmutableMap.of(
"ORDERKEY", "orderkey",
"CUSTKEY", "custkey")))));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.testng.annotations.Test;

import static com.facebook.presto.SystemSessionProperties.DISTRIBUTED_SORT;
import static com.facebook.presto.SystemSessionProperties.EXPLOIT_CONSTRAINTS;
import static com.facebook.presto.common.type.IntegerType.INTEGER;
import static com.facebook.presto.testing.MaterializedResult.resultBuilder;
import static com.facebook.presto.testing.assertions.Assert.assertEquals;
Expand Down Expand Up @@ -246,4 +247,23 @@ public void testCaseInsensitiveOutputAliasInOrderBy()
{
assertQueryOrdered("SELECT orderkey X FROM orders ORDER BY x");
}

@Test
public void testOrderByWithRedundantSortColumnsPruned()
{
Session session = Session.builder(getSession())
// With constraints framework turned on, RemoveRedundantTopNColumns & RemoveRedundantSortColumns will work to remove redundant columns from the OrderBy clause
.setSystemProperty(EXPLOIT_CONSTRAINTS, "true")
.build();

assertQuery(
session,
"SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders " +
"GROUP BY orderkey, custkey ORDER BY orderkey, custkey, sum(totalprice), min(orderdate) LIMIT 10");

assertQuery(
session,
"SELECT orderkey, custkey, sum(totalprice), min(orderdate) FROM orders " +
"GROUP BY orderkey, custkey ORDER BY orderkey, custkey, sum(totalprice), min(orderdate)");
}
}