/*
 * 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.Pattern;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.sql.planner.iterative.Lookup;
import com.facebook.presto.sql.planner.iterative.Rule;
import com.facebook.presto.sql.planner.optimizations.ScalarAggregationToJoinRewriter;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode;
import com.facebook.presto.sql.planner.plan.LateralJoinNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;

import java.util.Optional;

import static com.facebook.presto.sql.planner.optimizations.PlanNodeSearcher.searchFrom;
import static com.facebook.presto.sql.planner.optimizations.QueryCardinalityUtil.isScalar;
import static com.facebook.presto.util.MorePredicates.isInstanceOfAny;
import static java.util.Objects.requireNonNull;

public class TransformCorrelatedScalarAggregationToJoin
        implements Rule
{
    private static final Pattern PATTERN = Pattern.typeOf(LateralJoinNode.class);

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

    private final FunctionRegistry functionRegistry;

    public TransformCorrelatedScalarAggregationToJoin(FunctionRegistry functionRegistry)
    {
        this.functionRegistry = requireNonNull(functionRegistry, "functionRegistry is null");
    }

    @Override
    public Optional<PlanNode> apply(PlanNode node, Context context)
    {
        if (!(node instanceof LateralJoinNode)) {
            return Optional.empty();
        }

        LateralJoinNode lateralJoinNode = (LateralJoinNode) node;
        PlanNode subquery = context.getLookup().resolve(lateralJoinNode.getSubquery());

        if (lateralJoinNode.getCorrelation().isEmpty() || !(isScalar(subquery, context.getLookup()))) {
            return Optional.empty();
        }

        Optional<AggregationNode> aggregation = findAggregation(subquery, context.getLookup());
        if (!(aggregation.isPresent() && aggregation.get().getGroupingKeys().isEmpty())) {
            return Optional.empty();
        }

        ScalarAggregationToJoinRewriter rewriter = new ScalarAggregationToJoinRewriter(functionRegistry, context.getSymbolAllocator(), context.getIdAllocator(), context.getLookup());

        PlanNode rewrittenNode = rewriter.rewriteScalarAggregation(lateralJoinNode, aggregation.get());

        if (rewrittenNode instanceof LateralJoinNode) {
            return Optional.empty();
        }

        return Optional.of(rewrittenNode);
    }

    private static Optional<AggregationNode> findAggregation(PlanNode rootNode, Lookup lookup)
    {
        return searchFrom(rootNode, lookup)
                .where(AggregationNode.class::isInstance)
                .recurseOnlyWhen(isInstanceOfAny(ProjectNode.class, EnforceSingleRowNode.class))
                .findFirst();
    }
}

@@ -1537,16 +1537,1079 @@
 nNull;%0A%0A
+/**%0A * Scalar aggregation is aggregation with GROUP BY 'a constant' (or empty GROUP BY).%0A * It always returns single row.%0A * %3Cp%3E%0A * This optimizer rewrites correlated scalar aggregation subquery to left outer join in a way described here:%0A * https://github.com/prestodb/presto/wiki/Correlated-subqueries%0A * %3Cp%3E%0A * From:%0A * %3Cpre%3E%0A * - LateralJoin (with correlation list: %5BC%5D)%0A *   - (input) plan which produces symbols: %5BA, B, C%5D%0A *   - (subquery) Aggregation(GROUP BY (); functions: %5Bsum(F), count(), ...%5D%0A *     - Filter(D = C AND E %3E 5)%0A *       - plan which produces symbols: %5BD, E, F%5D%0A * %3C/pre%3E%0A * to:%0A * %3Cpre%3E%0A * - Aggregation(GROUP BY A, B, C, U; functions: %5Bsum(F), count(non_null), ...%5D%0A *   - Join(LEFT_OUTER, D = C)%0A *     - AssignUniqueId(adds symbol U)%0A *       - (input) plan which produces symbols: %5BA, B, C%5D%0A *     - Filter(E %3E 5)%0A *       - projection which adds non null symbol used for count() function%0A *         - plan which produces symbols: %5BD, E, F%5D%0A * %3C/pre%3E%0A * %3Cp%3E%0A * Note that only conjunction predicates in FilterNode are supported%0A */%0A
 public c

Add missing javadoc