Search in sources :

Example 1 with AggregationNode

use of io.prestosql.spi.plan.AggregationNode in project hetu-core by openlookeng.

the class TestLogicalPlanner method testBroadcastCorrelatedSubqueryAvoidsRemoteExchangeBeforeAggregation.

@Test
public void testBroadcastCorrelatedSubqueryAvoidsRemoteExchangeBeforeAggregation() {
    Session broadcastJoin = Session.builder(this.getQueryRunner().getDefaultSession()).setSystemProperty(JOIN_DISTRIBUTION_TYPE, JoinDistributionType.BROADCAST.name()).setSystemProperty(FORCE_SINGLE_NODE_OUTPUT, Boolean.toString(false)).build();
    // make sure there is a remote exchange on the build side
    PlanMatchPattern joinBuildSideWithRemoteExchange = anyTree(node(JoinNode.class, anyTree(node(TableScanNode.class)), anyTree(exchange(REMOTE, REPLICATE, anyTree(node(TableScanNode.class))))));
    // validates that there exists only one remote exchange
    Consumer<Plan> validateSingleRemoteExchange = plan -> assertEquals(countOfMatchingNodes(plan, node -> node instanceof ExchangeNode && ((ExchangeNode) node).getScope() == REMOTE), 1);
    Consumer<Plan> validateSingleStreamingAggregation = plan -> assertEquals(countOfMatchingNodes(plan, node -> node instanceof AggregationNode && ((AggregationNode) node).getGroupingKeys().contains(new Symbol("unique")) && ((AggregationNode) node).isStreamable()), 1);
    // region is unpartitioned, AssignUniqueId should provide satisfying partitioning for count(*) after LEFT JOIN
    assertPlanWithSession("SELECT (SELECT count(*) FROM region r2 WHERE r2.regionkey > r1.regionkey) FROM region r1", broadcastJoin, false, joinBuildSideWithRemoteExchange, validateSingleRemoteExchange.andThen(validateSingleStreamingAggregation));
    // orders is naturally partitioned, AssignUniqueId should not overwrite its natural partitioning
    assertPlanWithSession("SELECT count(count) " + "FROM (SELECT o1.orderkey orderkey, (SELECT count(*) FROM orders o2 WHERE o2.orderkey > o1.orderkey) count FROM orders o1) " + "GROUP BY orderkey", broadcastJoin, false, joinBuildSideWithRemoteExchange, validateSingleRemoteExchange.andThen(validateSingleStreamingAggregation));
}
Also used : REPLICATED(io.prestosql.spi.plan.JoinNode.DistributionType.REPLICATED) SortNode(io.prestosql.sql.planner.plan.SortNode) JoinDistributionType(io.prestosql.sql.analyzer.FeaturesConfig.JoinDistributionType) OPTIMIZE_HASH_GENERATION(io.prestosql.SystemSessionProperties.OPTIMIZE_HASH_GENERATION) PlanMatchPattern.markDistinct(io.prestosql.sql.planner.assertions.PlanMatchPattern.markDistinct) ValueSet(io.prestosql.spi.predicate.ValueSet) Test(org.testng.annotations.Test) PlanMatchPattern.singleGroupingSet(io.prestosql.sql.planner.assertions.PlanMatchPattern.singleGroupingSet) AggregationNode(io.prestosql.spi.plan.AggregationNode) JOIN_REORDERING_STRATEGY(io.prestosql.SystemSessionProperties.JOIN_REORDERING_STRATEGY) PlanMatchPattern.values(io.prestosql.sql.planner.assertions.PlanMatchPattern.values) Slices(io.airlift.slice.Slices) Map(java.util.Map) Domain.singleValue(io.prestosql.spi.predicate.Domain.singleValue) PlanMatchPattern.node(io.prestosql.sql.planner.assertions.PlanMatchPattern.node) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) PlanMatchPattern.strictTableScan(io.prestosql.sql.planner.assertions.PlanMatchPattern.strictTableScan) PlanMatchPattern.expression(io.prestosql.sql.planner.assertions.PlanMatchPattern.expression) Assert.assertFalse(org.testng.Assert.assertFalse) PlanMatchPattern.join(io.prestosql.sql.planner.assertions.PlanMatchPattern.join) PlanMatchPattern.strictProject(io.prestosql.sql.planner.assertions.PlanMatchPattern.strictProject) PlanMatchPattern(io.prestosql.sql.planner.assertions.PlanMatchPattern) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) TableScanNode(io.prestosql.spi.plan.TableScanNode) PlanNode(io.prestosql.spi.plan.PlanNode) ProjectNode(io.prestosql.spi.plan.ProjectNode) VarcharType.createVarcharType(io.prestosql.spi.type.VarcharType.createVarcharType) MorePredicates(io.prestosql.util.MorePredicates) CheckSubqueryNodesAreRewritten(io.prestosql.sql.planner.optimizations.CheckSubqueryNodesAreRewritten) LongLiteral(io.prestosql.sql.tree.LongLiteral) QueryTemplate(io.prestosql.tests.QueryTemplate) LOCAL(io.prestosql.sql.planner.plan.ExchangeNode.Scope.LOCAL) Domain(io.prestosql.spi.predicate.Domain) INNER(io.prestosql.spi.plan.JoinNode.Type.INNER) StatisticsWriterNode(io.prestosql.sql.planner.plan.StatisticsWriterNode) DistinctLimitNode(io.prestosql.sql.planner.plan.DistinctLimitNode) OPTIMIZED(io.prestosql.sql.planner.LogicalPlanner.Stage.OPTIMIZED) JOIN_DISTRIBUTION_TYPE(io.prestosql.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE) QueryTemplate.queryTemplate(io.prestosql.tests.QueryTemplate.queryTemplate) PlanMatchPattern.equiJoinClause(io.prestosql.sql.planner.assertions.PlanMatchPattern.equiJoinClause) PlanMatchPattern.assignUniqueId(io.prestosql.sql.planner.assertions.PlanMatchPattern.assignUniqueId) REMOTE(io.prestosql.sql.planner.plan.ExchangeNode.Scope.REMOTE) GATHER(io.prestosql.sql.planner.plan.ExchangeNode.Type.GATHER) SINGLE(io.prestosql.spi.plan.AggregationNode.Step.SINGLE) REPARTITION(io.prestosql.sql.planner.plan.ExchangeNode.Type.REPARTITION) Session(io.prestosql.Session) PlanMatchPattern.anyTree(io.prestosql.sql.planner.assertions.PlanMatchPattern.anyTree) MoreCollectors.toOptional(com.google.common.collect.MoreCollectors.toOptional) PlanMatchPattern.output(io.prestosql.sql.planner.assertions.PlanMatchPattern.output) ExpressionMatcher(io.prestosql.sql.planner.assertions.ExpressionMatcher) PlanMatchPattern.anyNot(io.prestosql.sql.planner.assertions.PlanMatchPattern.anyNot) ValuesNode(io.prestosql.spi.plan.ValuesNode) DESCENDING(io.prestosql.sql.tree.SortItem.Ordering.DESCENDING) ColumnHandle(io.prestosql.spi.connector.ColumnHandle) LimitNode(io.prestosql.spi.plan.LimitNode) PlanOptimizer(io.prestosql.sql.planner.optimizations.PlanOptimizer) PlanMatchPattern.any(io.prestosql.sql.planner.assertions.PlanMatchPattern.any) PlanMatchPattern.aggregation(io.prestosql.sql.planner.assertions.PlanMatchPattern.aggregation) PlanMatchPattern.project(io.prestosql.sql.planner.assertions.PlanMatchPattern.project) PlanMatchPattern.tableScan(io.prestosql.sql.planner.assertions.PlanMatchPattern.tableScan) TpchColumnHandle(io.prestosql.plugin.tpch.TpchColumnHandle) PlanMatchPattern.semiJoin(io.prestosql.sql.planner.assertions.PlanMatchPattern.semiJoin) RowNumberSymbolMatcher(io.prestosql.sql.planner.assertions.RowNumberSymbolMatcher) ExchangeNode(io.prestosql.sql.planner.plan.ExchangeNode) FilterNode(io.prestosql.spi.plan.FilterNode) JoinReorderingStrategy(io.prestosql.sql.analyzer.FeaturesConfig.JoinReorderingStrategy) FORCE_SINGLE_NODE_OUTPUT(io.prestosql.SystemSessionProperties.FORCE_SINGLE_NODE_OUTPUT) ASC_NULLS_LAST(io.prestosql.spi.block.SortOrder.ASC_NULLS_LAST) ApplyNode(io.prestosql.sql.planner.plan.ApplyNode) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) FINAL(io.prestosql.spi.plan.AggregationNode.Step.FINAL) IndexJoinNode(io.prestosql.sql.planner.plan.IndexJoinNode) FILTERING_SEMI_JOIN_TO_INNER(io.prestosql.SystemSessionProperties.FILTERING_SEMI_JOIN_TO_INNER) String.format(java.lang.String.format) PlanMatchPattern.sort(io.prestosql.sql.planner.assertions.PlanMatchPattern.sort) List(java.util.List) EnforceSingleRowNode(io.prestosql.sql.planner.plan.EnforceSingleRowNode) MorePredicates.isInstanceOfAny(io.prestosql.util.MorePredicates.isInstanceOfAny) TopNNode(io.prestosql.spi.plan.TopNNode) Entry(java.util.Map.Entry) Optional(java.util.Optional) PlanMatchPattern.topNRankingNumber(io.prestosql.sql.planner.assertions.PlanMatchPattern.topNRankingNumber) PlanMatchPattern.topN(io.prestosql.sql.planner.assertions.PlanMatchPattern.topN) PlanMatchPattern.constrainedTableScan(io.prestosql.sql.planner.assertions.PlanMatchPattern.constrainedTableScan) LAST(io.prestosql.sql.tree.SortItem.NullOrdering.LAST) TpchTableHandle(io.prestosql.plugin.tpch.TpchTableHandle) LateralJoinNode(io.prestosql.sql.planner.plan.LateralJoinNode) PlanMatchPattern.apply(io.prestosql.sql.planner.assertions.PlanMatchPattern.apply) Assert.assertEquals(org.testng.Assert.assertEquals) PARTITIONED(io.prestosql.spi.plan.JoinNode.DistributionType.PARTITIONED) PARTIAL(io.prestosql.spi.plan.AggregationNode.Step.PARTIAL) SemiJoinNode(io.prestosql.sql.planner.plan.SemiJoinNode) SUBQUERY_MULTIPLE_ROWS(io.prestosql.spi.StandardErrorCode.SUBQUERY_MULTIPLE_ROWS) ImmutableList(com.google.common.collect.ImmutableList) Range(io.prestosql.spi.predicate.Range) PlanMatchPattern.functionCall(io.prestosql.sql.planner.assertions.PlanMatchPattern.functionCall) PlanMatchPattern.filter(io.prestosql.sql.planner.assertions.PlanMatchPattern.filter) PlanMatchPattern.exchange(io.prestosql.sql.planner.assertions.PlanMatchPattern.exchange) REPLICATE(io.prestosql.sql.planner.plan.ExchangeNode.Type.REPLICATE) JoinNode(io.prestosql.spi.plan.JoinNode) Symbol(io.prestosql.spi.plan.Symbol) BasePlanTest(io.prestosql.sql.planner.assertions.BasePlanTest) ASCENDING(io.prestosql.sql.tree.SortItem.Ordering.ASCENDING) DISTRIBUTED_SORT(io.prestosql.SystemSessionProperties.DISTRIBUTED_SORT) TupleDomain(io.prestosql.spi.predicate.TupleDomain) PlanMatchPattern.limit(io.prestosql.sql.planner.assertions.PlanMatchPattern.limit) Consumer(java.util.function.Consumer) PlanNodeSearcher.searchFrom(io.prestosql.sql.planner.optimizations.PlanNodeSearcher.searchFrom) PlanMatchPattern.rowNumber(io.prestosql.sql.planner.assertions.PlanMatchPattern.rowNumber) AddLocalExchanges(io.prestosql.sql.planner.optimizations.AddLocalExchanges) LEFT(io.prestosql.spi.plan.JoinNode.Type.LEFT) PlanMatchPattern.constrainedTableScanWithTableLayout(io.prestosql.sql.planner.assertions.PlanMatchPattern.constrainedTableScanWithTableLayout) TableScanNode(io.prestosql.spi.plan.TableScanNode) ExchangeNode(io.prestosql.sql.planner.plan.ExchangeNode) IndexJoinNode(io.prestosql.sql.planner.plan.IndexJoinNode) LateralJoinNode(io.prestosql.sql.planner.plan.LateralJoinNode) SemiJoinNode(io.prestosql.sql.planner.plan.SemiJoinNode) JoinNode(io.prestosql.spi.plan.JoinNode) Symbol(io.prestosql.spi.plan.Symbol) PlanMatchPattern(io.prestosql.sql.planner.assertions.PlanMatchPattern) AggregationNode(io.prestosql.spi.plan.AggregationNode) Session(io.prestosql.Session) Test(org.testng.annotations.Test) BasePlanTest(io.prestosql.sql.planner.assertions.BasePlanTest)

Example 2 with AggregationNode

use of io.prestosql.spi.plan.AggregationNode in project hetu-core by openlookeng.

the class TestEffectivePredicateExtractor method testGroupByEmpty.

@Test
public void testGroupByEmpty() {
    PlanNode node = new AggregationNode(newId(), filter(baseTableScan, FALSE_LITERAL), ImmutableMap.of(), globalAggregation(), ImmutableList.of(), AggregationNode.Step.FINAL, Optional.empty(), Optional.empty(), AggregationNode.AggregationType.HASH, Optional.empty());
    Expression effectivePredicate = effectivePredicateExtractor.extract(SESSION, node, TypeProvider.empty(), typeAnalyzer);
    assertEquals(effectivePredicate, TRUE_LITERAL);
}
Also used : PlanNode(io.prestosql.spi.plan.PlanNode) CallExpression(io.prestosql.spi.relation.CallExpression) OriginalExpressionUtils.castToRowExpression(io.prestosql.sql.relational.OriginalExpressionUtils.castToRowExpression) InListExpression(io.prestosql.sql.tree.InListExpression) ComparisonExpression(io.prestosql.sql.tree.ComparisonExpression) RowExpression(io.prestosql.spi.relation.RowExpression) Expression(io.prestosql.sql.tree.Expression) AggregationNode(io.prestosql.spi.plan.AggregationNode) Test(org.testng.annotations.Test)

Example 3 with AggregationNode

use of io.prestosql.spi.plan.AggregationNode in project hetu-core by openlookeng.

the class TestEffectivePredicateExtractor method testAggregation.

@Test
public void testAggregation() {
    PlanNode node = new AggregationNode(newId(), filter(baseTableScan, and(equals(AE, DE), equals(BE, EE), equals(CE, FE), lessThan(DE, bigintLiteral(10)), lessThan(CE, DE), greaterThan(AE, bigintLiteral(2)), equals(EE, FE))), ImmutableMap.of(C, new Aggregation(new CallExpression("test", new FunctionResolution(metadata.getFunctionAndTypeManager()).countFunction(), BIGINT, ImmutableList.of()), ImmutableList.of(), false, Optional.empty(), Optional.empty(), Optional.empty()), D, new Aggregation(new CallExpression("test", new FunctionResolution(metadata.getFunctionAndTypeManager()).countFunction(), BIGINT, ImmutableList.of()), ImmutableList.of(), false, Optional.empty(), Optional.empty(), Optional.empty())), singleGroupingSet(ImmutableList.of(A, B, C)), ImmutableList.of(), AggregationNode.Step.FINAL, Optional.empty(), Optional.empty(), AggregationNode.AggregationType.HASH, Optional.empty());
    Expression effectivePredicate = effectivePredicateExtractor.extract(SESSION, node, TypeProvider.empty(), typeAnalyzer);
    // Rewrite in terms of group by symbols
    assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjunctsSet(lessThan(AE, bigintLiteral(10)), lessThan(BE, AE), greaterThan(AE, bigintLiteral(2)), equals(BE, CE)));
}
Also used : AggregationNode.globalAggregation(io.prestosql.spi.plan.AggregationNode.globalAggregation) Aggregation(io.prestosql.spi.plan.AggregationNode.Aggregation) PlanNode(io.prestosql.spi.plan.PlanNode) CallExpression(io.prestosql.spi.relation.CallExpression) OriginalExpressionUtils.castToRowExpression(io.prestosql.sql.relational.OriginalExpressionUtils.castToRowExpression) InListExpression(io.prestosql.sql.tree.InListExpression) ComparisonExpression(io.prestosql.sql.tree.ComparisonExpression) RowExpression(io.prestosql.spi.relation.RowExpression) Expression(io.prestosql.sql.tree.Expression) AggregationNode(io.prestosql.spi.plan.AggregationNode) CallExpression(io.prestosql.spi.relation.CallExpression) FunctionResolution(io.prestosql.sql.relational.FunctionResolution) Test(org.testng.annotations.Test)

Example 4 with AggregationNode

use of io.prestosql.spi.plan.AggregationNode in project hetu-core by openlookeng.

the class QueryPlanner method aggregate.

private PlanBuilder aggregate(PlanBuilder inputSubPlan, QuerySpecification node) {
    PlanBuilder subPlan = inputSubPlan;
    if (!analysis.isAggregation(node)) {
        return subPlan;
    }
    // 1. Pre-project all scalar inputs (arguments and non-trivial group by expressions)
    Set<Expression> groupByExpressions = ImmutableSet.copyOf(analysis.getGroupByExpressions(node));
    ImmutableList.Builder<Expression> arguments = ImmutableList.builder();
    analysis.getAggregates(node).stream().map(FunctionCall::getArguments).flatMap(List::stream).filter(// lambda expression is generated at execution time
    exp -> !(exp instanceof LambdaExpression)).forEach(arguments::add);
    analysis.getAggregates(node).stream().map(FunctionCall::getOrderBy).filter(Optional::isPresent).map(Optional::get).map(OrderBy::getSortItems).flatMap(List::stream).map(SortItem::getSortKey).forEach(arguments::add);
    // filter expressions need to be projected first
    analysis.getAggregates(node).stream().map(FunctionCall::getFilter).filter(Optional::isPresent).map(Optional::get).forEach(arguments::add);
    Iterable<Expression> inputs = Iterables.concat(groupByExpressions, arguments.build());
    subPlan = handleSubqueries(subPlan, node, inputs);
    if (!Iterables.isEmpty(inputs)) {
        // avoid an empty projection if the only aggregation is COUNT (which has no arguments)
        subPlan = project(subPlan, inputs);
    }
    // 2. Aggregate
    // 2.a. Rewrite aggregate arguments
    TranslationMap argumentTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToSymbolMap);
    ImmutableList.Builder<Symbol> aggregationArgumentsBuilder = ImmutableList.builder();
    for (Expression argument : arguments.build()) {
        Symbol symbol = subPlan.translate(argument);
        argumentTranslations.put(argument, symbol);
        aggregationArgumentsBuilder.add(symbol);
    }
    List<Symbol> aggregationArguments = aggregationArgumentsBuilder.build();
    // 2.b. Rewrite grouping columns
    TranslationMap groupingTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToSymbolMap);
    Map<Symbol, Symbol> groupingSetMappings = new LinkedHashMap<>();
    for (Expression expression : groupByExpressions) {
        Symbol input = subPlan.translate(expression);
        Symbol output = planSymbolAllocator.newSymbol(expression, analysis.getTypeWithCoercions(expression), "gid");
        groupingTranslations.put(expression, output);
        groupingSetMappings.put(output, input);
    }
    // This tracks the grouping sets before complex expressions are considered (see comments below)
    // It's also used to compute the descriptors needed to implement grouping()
    List<Set<FieldId>> columnOnlyGroupingSets = ImmutableList.of(ImmutableSet.of());
    List<List<Symbol>> groupingSets = ImmutableList.of(ImmutableList.of());
    if (node.getGroupBy().isPresent()) {
        // For the purpose of "distinct", we need to canonicalize column references that may have varying
        // syntactic forms (e.g., "t.a" vs "a"). Thus we need to enumerate grouping sets based on the underlying
        // fieldId associated with each column reference expression.
        // The catch is that simple group-by expressions can be arbitrary expressions (this is a departure from the SQL specification).
        // But, they don't affect the number of grouping sets or the behavior of "distinct" . We can compute all the candidate
        // grouping sets in terms of fieldId, dedup as appropriate and then cross-join them with the complex expressions.
        Analysis.GroupingSetAnalysis groupingSetAnalysis = analysis.getGroupingSets(node);
        columnOnlyGroupingSets = enumerateGroupingSets(groupingSetAnalysis);
        if (node.getGroupBy().get().isDistinct()) {
            columnOnlyGroupingSets = columnOnlyGroupingSets.stream().distinct().collect(toImmutableList());
        }
        // add in the complex expressions an turn materialize the grouping sets in terms of plan columns
        ImmutableList.Builder<List<Symbol>> groupingSetBuilder = ImmutableList.builder();
        for (Set<FieldId> groupingSet : columnOnlyGroupingSets) {
            ImmutableList.Builder<Symbol> columns = ImmutableList.builder();
            groupingSetAnalysis.getComplexExpressions().stream().map(groupingTranslations::get).forEach(columns::add);
            groupingSet.stream().map(field -> groupingTranslations.get(new FieldReference(field.getFieldIndex()))).forEach(columns::add);
            groupingSetBuilder.add(columns.build());
        }
        groupingSets = groupingSetBuilder.build();
    }
    // 2.c. Generate GroupIdNode (multiple grouping sets) or ProjectNode (single grouping set)
    Optional<Symbol> groupIdSymbol = Optional.empty();
    if (groupingSets.size() > 1) {
        groupIdSymbol = Optional.of(planSymbolAllocator.newSymbol("groupId", BIGINT));
        GroupIdNode groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), groupingSets, groupingSetMappings, aggregationArguments, groupIdSymbol.get());
        subPlan = new PlanBuilder(groupingTranslations, groupId);
    } else {
        Assignments.Builder assignments = Assignments.builder();
        aggregationArguments.forEach(symbol -> assignments.put(symbol, castToRowExpression(toSymbolReference(symbol))));
        groupingSetMappings.forEach((key, value) -> assignments.put(key, castToRowExpression(toSymbolReference(value))));
        ProjectNode project = new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), assignments.build());
        subPlan = new PlanBuilder(groupingTranslations, project);
    }
    TranslationMap aggregationTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToSymbolMap);
    aggregationTranslations.copyMappingsFrom(groupingTranslations);
    // 2.d. Rewrite aggregates
    ImmutableMap.Builder<Symbol, Aggregation> aggregationsBuilder = ImmutableMap.builder();
    boolean needPostProjectionCoercion = false;
    for (FunctionCall aggregate : analysis.getAggregates(node)) {
        Expression rewritten = argumentTranslations.rewrite(aggregate);
        Symbol newSymbol = planSymbolAllocator.newSymbol(rewritten, analysis.getType(aggregate));
        // Therefore we can end up with this implicit cast, and have to move it into a post-projection
        if (rewritten instanceof Cast) {
            rewritten = ((Cast) rewritten).getExpression();
            needPostProjectionCoercion = true;
        }
        aggregationTranslations.put(aggregate, newSymbol);
        FunctionCall functionCall = (FunctionCall) rewritten;
        aggregationsBuilder.put(newSymbol, new Aggregation(call(aggregate.getName().getSuffix(), analysis.getFunctionHandle(aggregate), analysis.getType(aggregate), functionCall.getArguments().stream().map(OriginalExpressionUtils::castToRowExpression).collect(toImmutableList())), functionCall.getArguments().stream().map(OriginalExpressionUtils::castToRowExpression).collect(toImmutableList()), functionCall.isDistinct(), functionCall.getFilter().map(SymbolUtils::from), functionCall.getOrderBy().map(OrderingSchemeUtils::fromOrderBy), Optional.empty()));
    }
    Map<Symbol, Aggregation> aggregations = aggregationsBuilder.build();
    ImmutableSet.Builder<Integer> globalGroupingSets = ImmutableSet.builder();
    for (int i = 0; i < groupingSets.size(); i++) {
        if (groupingSets.get(i).isEmpty()) {
            globalGroupingSets.add(i);
        }
    }
    ImmutableList.Builder<Symbol> groupingKeys = ImmutableList.builder();
    groupingSets.stream().flatMap(List::stream).distinct().forEach(groupingKeys::add);
    groupIdSymbol.ifPresent(groupingKeys::add);
    AggregationNode aggregationNode = new AggregationNode(idAllocator.getNextId(), subPlan.getRoot(), aggregations, groupingSets(groupingKeys.build(), groupingSets.size(), globalGroupingSets.build()), ImmutableList.of(), AggregationNode.Step.SINGLE, Optional.empty(), groupIdSymbol, AggregationNode.AggregationType.HASH, Optional.empty());
    subPlan = new PlanBuilder(aggregationTranslations, aggregationNode);
    // TODO: this is a hack, we should change type coercions to coerce the inputs to functions/operators instead of coercing the output
    if (needPostProjectionCoercion) {
        ImmutableList.Builder<Expression> alreadyCoerced = ImmutableList.builder();
        alreadyCoerced.addAll(groupByExpressions);
        groupIdSymbol.map(SymbolUtils::toSymbolReference).ifPresent(alreadyCoerced::add);
        subPlan = explicitCoercionFields(subPlan, alreadyCoerced.build(), analysis.getAggregates(node));
    }
    // 4. Project and re-write all grouping functions
    return handleGroupingOperations(subPlan, node, groupIdSymbol, columnOnlyGroupingSets);
}
Also used : Table(io.prestosql.sql.tree.Table) SortNode(io.prestosql.sql.planner.plan.SortNode) Property(io.prestosql.sql.tree.Property) SortOrder(io.prestosql.spi.block.SortOrder) AggregationNode(io.prestosql.spi.plan.AggregationNode) Cast(io.prestosql.sql.tree.Cast) HeuristicIndexUtils(io.prestosql.utils.HeuristicIndexUtils) Statement(io.prestosql.sql.tree.Statement) HetuConstant(io.prestosql.spi.HetuConstant) Map(java.util.Map) OriginalExpressionUtils.castToRowExpression(io.prestosql.sql.relational.OriginalExpressionUtils.castToRowExpression) FetchFirst(io.prestosql.sql.tree.FetchFirst) Identifier(io.prestosql.sql.tree.Identifier) PlanNodeId(io.prestosql.spi.plan.PlanNodeId) CreateIndexNode(io.prestosql.sql.planner.plan.CreateIndexNode) AssignmentItem(io.prestosql.sql.tree.AssignmentItem) Delete(io.prestosql.sql.tree.Delete) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) TableScanNode(io.prestosql.spi.plan.TableScanNode) Set(java.util.Set) PlanNode(io.prestosql.spi.plan.PlanNode) ProjectNode(io.prestosql.spi.plan.ProjectNode) Metadata(io.prestosql.metadata.Metadata) NodeRef(io.prestosql.sql.tree.NodeRef) LambdaExpression(io.prestosql.sql.tree.LambdaExpression) SymbolUtils.toSymbolReference(io.prestosql.sql.planner.SymbolUtils.toSymbolReference) ReuseExchangeOperator(io.prestosql.spi.operator.ReuseExchangeOperator) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) SymbolReference(io.prestosql.sql.tree.SymbolReference) StringLiteral(io.prestosql.sql.tree.StringLiteral) LEVEL_PROP_KEY(io.prestosql.spi.connector.CreateIndexMetadata.LEVEL_PROP_KEY) SymbolUtils.from(io.prestosql.sql.planner.SymbolUtils.from) Field(io.prestosql.sql.analyzer.Field) OriginalExpressionUtils(io.prestosql.sql.relational.OriginalExpressionUtils) GroupIdNode(io.prestosql.spi.plan.GroupIdNode) Iterables(com.google.common.collect.Iterables) TableMetadata(io.prestosql.metadata.TableMetadata) NodeUtils.getSortItemsFromOrderBy(io.prestosql.sql.NodeUtils.getSortItemsFromOrderBy) Node(io.prestosql.sql.tree.Node) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) OrderingSchemeUtils.sortItemToSortOrder(io.prestosql.sql.planner.OrderingSchemeUtils.sortItemToSortOrder) MetadataUtil(io.prestosql.metadata.MetadataUtil) Session(io.prestosql.Session) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) FrameBoundType(io.prestosql.spi.sql.expression.Types.FrameBoundType) DeleteNode(io.prestosql.sql.planner.plan.DeleteNode) AssignmentUtils(io.prestosql.sql.planner.plan.AssignmentUtils) Properties(java.util.Properties) Query(io.prestosql.sql.tree.Query) Assignments(io.prestosql.spi.plan.Assignments) Streams.stream(com.google.common.collect.Streams.stream) DeleteTarget(io.prestosql.sql.planner.plan.TableWriterNode.DeleteTarget) VARBINARY(io.prestosql.spi.type.VarbinaryType.VARBINARY) ValuesNode(io.prestosql.spi.plan.ValuesNode) ColumnHandle(io.prestosql.spi.connector.ColumnHandle) CreateIndexMetadata(io.prestosql.spi.connector.CreateIndexMetadata) WindowNode(io.prestosql.spi.plan.WindowNode) LimitNode(io.prestosql.spi.plan.LimitNode) Expression(io.prestosql.sql.tree.Expression) OffsetNode(io.prestosql.sql.planner.plan.OffsetNode) CURRENT_ROW(io.prestosql.spi.sql.expression.Types.FrameBoundType.CURRENT_ROW) UpdateIndexNode(io.prestosql.sql.planner.plan.UpdateIndexNode) UNBOUNDED_PRECEDING(io.prestosql.spi.sql.expression.Types.FrameBoundType.UNBOUNDED_PRECEDING) QualifiedName(io.prestosql.sql.tree.QualifiedName) FieldReference(io.prestosql.sql.tree.FieldReference) ExchangeNode(io.prestosql.sql.planner.plan.ExchangeNode) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) FilterNode(io.prestosql.spi.plan.FilterNode) Expressions.call(io.prestosql.sql.relational.Expressions.call) WindowFrame(io.prestosql.sql.tree.WindowFrame) Locale(java.util.Locale) Window(io.prestosql.sql.tree.Window) Type(io.prestosql.spi.type.Type) QuerySpecification(io.prestosql.sql.tree.QuerySpecification) TypeCoercion(io.prestosql.type.TypeCoercion) BIGINT(io.prestosql.spi.type.BigintType.BIGINT) AggregationNode.singleGroupingSet(io.prestosql.spi.plan.AggregationNode.singleGroupingSet) ImmutableSet(com.google.common.collect.ImmutableSet) WindowFrameType(io.prestosql.spi.sql.expression.Types.WindowFrameType) ImmutableMap(com.google.common.collect.ImmutableMap) GroupingOperation(io.prestosql.sql.tree.GroupingOperation) SystemSessionProperties.isSkipRedundantSort(io.prestosql.SystemSessionProperties.isSkipRedundantSort) RANGE(io.prestosql.spi.sql.expression.Types.WindowFrameType.RANGE) CreateIndex(io.prestosql.sql.tree.CreateIndex) PropertyService(io.prestosql.spi.service.PropertyService) UUID(java.util.UUID) RelationType(io.prestosql.sql.analyzer.RelationType) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Pair(io.prestosql.spi.heuristicindex.Pair) String.format(java.lang.String.format) Scope(io.prestosql.sql.analyzer.Scope) List(java.util.List) AggregationNode.groupingSets(io.prestosql.spi.plan.AggregationNode.groupingSets) Entry(java.util.Map.Entry) Optional(java.util.Optional) Analysis(io.prestosql.sql.analyzer.Analysis) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) FieldId(io.prestosql.sql.analyzer.FieldId) IntStream(java.util.stream.IntStream) UpdateIndex(io.prestosql.sql.tree.UpdateIndex) UpdateIndexMetadata(io.prestosql.spi.connector.UpdateIndexMetadata) HashMap(java.util.HashMap) RelationId(io.prestosql.sql.analyzer.RelationId) TableHandle(io.prestosql.spi.metadata.TableHandle) DecimalLiteral(io.prestosql.sql.tree.DecimalLiteral) INDEX_SUPPORTED_TYPES(io.prestosql.spi.connector.CreateIndexMetadata.INDEX_SUPPORTED_TYPES) ImmutableList(com.google.common.collect.ImmutableList) FunctionCall(io.prestosql.sql.tree.FunctionCall) OrderingScheme(io.prestosql.spi.plan.OrderingScheme) Objects.requireNonNull(java.util.Objects.requireNonNull) SortItem(io.prestosql.sql.tree.SortItem) Symbol(io.prestosql.spi.plan.Symbol) TableWriterNode(io.prestosql.sql.planner.plan.TableWriterNode) Iterator(java.util.Iterator) ColumnMetadata(io.prestosql.spi.connector.ColumnMetadata) OrderBy(io.prestosql.sql.tree.OrderBy) UpdateNode(io.prestosql.sql.planner.plan.UpdateNode) LambdaArgumentDeclaration(io.prestosql.sql.tree.LambdaArgumentDeclaration) Update(io.prestosql.sql.tree.Update) Offset(io.prestosql.sql.tree.Offset) AUTOLOAD_PROP_KEY(io.prestosql.spi.connector.CreateIndexMetadata.AUTOLOAD_PROP_KEY) Aggregation(io.prestosql.spi.plan.AggregationNode.Aggregation) PlanNodeIdAllocator(io.prestosql.spi.plan.PlanNodeIdAllocator) RowExpression(io.prestosql.spi.relation.RowExpression) Assignments(io.prestosql.spi.plan.Assignments) LinkedHashMap(java.util.LinkedHashMap) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Optional(java.util.Optional) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) Analysis(io.prestosql.sql.analyzer.Analysis) OriginalExpressionUtils(io.prestosql.sql.relational.OriginalExpressionUtils) LambdaExpression(io.prestosql.sql.tree.LambdaExpression) Cast(io.prestosql.sql.tree.Cast) Set(java.util.Set) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) AggregationNode.singleGroupingSet(io.prestosql.spi.plan.AggregationNode.singleGroupingSet) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Symbol(io.prestosql.spi.plan.Symbol) Aggregation(io.prestosql.spi.plan.AggregationNode.Aggregation) GroupIdNode(io.prestosql.spi.plan.GroupIdNode) FunctionCall(io.prestosql.sql.tree.FunctionCall) FieldReference(io.prestosql.sql.tree.FieldReference) AggregationNode(io.prestosql.spi.plan.AggregationNode) OriginalExpressionUtils.castToRowExpression(io.prestosql.sql.relational.OriginalExpressionUtils.castToRowExpression) LambdaExpression(io.prestosql.sql.tree.LambdaExpression) Expression(io.prestosql.sql.tree.Expression) RowExpression(io.prestosql.spi.relation.RowExpression) FieldId(io.prestosql.sql.analyzer.FieldId) ProjectNode(io.prestosql.spi.plan.ProjectNode)

Example 5 with AggregationNode

use of io.prestosql.spi.plan.AggregationNode in project hetu-core by openlookeng.

the class ImplementFilteredAggregations method apply.

@Override
public Result apply(AggregationNode aggregationNode, Captures captures, Context context) {
    Assignments.Builder newAssignments = Assignments.builder();
    ImmutableMap.Builder<Symbol, Aggregation> aggregations = ImmutableMap.builder();
    ImmutableList.Builder<Expression> maskSymbols = ImmutableList.builder();
    boolean aggregateWithoutFilterPresent = false;
    for (Map.Entry<Symbol, Aggregation> entry : aggregationNode.getAggregations().entrySet()) {
        Symbol output = entry.getKey();
        // strip the filters
        Aggregation aggregation = entry.getValue();
        Optional<Symbol> mask = aggregation.getMask();
        if (aggregation.getFilter().isPresent()) {
            Symbol filter = aggregation.getFilter().get();
            Symbol symbol = context.getSymbolAllocator().newSymbol(filter.getName(), BOOLEAN);
            verify(!mask.isPresent(), "Expected aggregation without mask symbols, see Rule pattern");
            newAssignments.put(symbol, castToRowExpression(toSymbolReference(filter)));
            mask = Optional.of(symbol);
            maskSymbols.add(toSymbolReference(symbol));
        } else {
            aggregateWithoutFilterPresent = true;
        }
        aggregations.put(output, new Aggregation(aggregation.getFunctionCall(), aggregation.getArguments(), aggregation.isDistinct(), Optional.empty(), aggregation.getOrderingScheme(), mask));
    }
    Expression predicate = TRUE_LITERAL;
    if (!aggregationNode.hasNonEmptyGroupingSet() && !aggregateWithoutFilterPresent) {
        predicate = combineDisjunctsWithDefault(maskSymbols.build(), TRUE_LITERAL);
    }
    // identity projection for all existing inputs
    newAssignments.putAll(AssignmentUtils.identityAsSymbolReferences(aggregationNode.getSource().getOutputSymbols()));
    return Result.ofPlanNode(new AggregationNode(context.getIdAllocator().getNextId(), new FilterNode(context.getIdAllocator().getNextId(), new ProjectNode(context.getIdAllocator().getNextId(), aggregationNode.getSource(), newAssignments.build()), castToRowExpression(predicate)), aggregations.build(), aggregationNode.getGroupingSets(), ImmutableList.of(), aggregationNode.getStep(), aggregationNode.getHashSymbol(), aggregationNode.getGroupIdSymbol(), aggregationNode.getAggregationType(), aggregationNode.getFinalizeSymbol()));
}
Also used : Symbol(io.prestosql.spi.plan.Symbol) ImmutableList(com.google.common.collect.ImmutableList) FilterNode(io.prestosql.spi.plan.FilterNode) Assignments(io.prestosql.spi.plan.Assignments) AggregationNode(io.prestosql.spi.plan.AggregationNode) ImmutableMap(com.google.common.collect.ImmutableMap) Aggregation(io.prestosql.spi.plan.AggregationNode.Aggregation) OriginalExpressionUtils.castToRowExpression(io.prestosql.sql.relational.OriginalExpressionUtils.castToRowExpression) Expression(io.prestosql.sql.tree.Expression) ProjectNode(io.prestosql.spi.plan.ProjectNode) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map)

Aggregations

AggregationNode (io.prestosql.spi.plan.AggregationNode)49 Symbol (io.prestosql.spi.plan.Symbol)37 PlanNode (io.prestosql.spi.plan.PlanNode)28 ProjectNode (io.prestosql.spi.plan.ProjectNode)23 Map (java.util.Map)22 CallExpression (io.prestosql.spi.relation.CallExpression)19 ImmutableMap (com.google.common.collect.ImmutableMap)16 Assignments (io.prestosql.spi.plan.Assignments)15 Aggregation (io.prestosql.spi.plan.AggregationNode.Aggregation)14 Expression (io.prestosql.sql.tree.Expression)14 List (java.util.List)14 ImmutableList (com.google.common.collect.ImmutableList)13 Optional (java.util.Optional)13 RowExpression (io.prestosql.spi.relation.RowExpression)12 OriginalExpressionUtils.castToRowExpression (io.prestosql.sql.relational.OriginalExpressionUtils.castToRowExpression)12 Session (io.prestosql.Session)11 FilterNode (io.prestosql.spi.plan.FilterNode)11 TableScanNode (io.prestosql.spi.plan.TableScanNode)11 Metadata (io.prestosql.metadata.Metadata)9 JoinNode (io.prestosql.spi.plan.JoinNode)9