All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.trino.sql.planner.iterative.rule.RemoveRedundantExists Maven / Gradle / Ivy

/*
 * 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 io.trino.sql.planner.iterative.rule;

import io.trino.matching.Captures;
import io.trino.matching.Pattern;
import io.trino.sql.ir.Expression;
import io.trino.sql.planner.Symbol;
import io.trino.sql.planner.iterative.Rule;
import io.trino.sql.planner.optimizations.Cardinality;
import io.trino.sql.planner.plan.ApplyNode;
import io.trino.sql.planner.plan.Assignments;
import io.trino.sql.planner.plan.ProjectNode;

import static io.trino.sql.ir.Booleans.FALSE;
import static io.trino.sql.ir.Booleans.TRUE;
import static io.trino.sql.planner.optimizations.QueryCardinalityUtil.extractCardinality;
import static io.trino.sql.planner.plan.Patterns.applyNode;

/**
 * Given:
 *
 * 
 * - Apply [X.*, e = EXISTS (true)]
 *   - X
 *   - S with cardinality >= 1
 * 
*

* Produces: * *

 * - Project [X.*, e = true]
 *   - X
 * 
*

* Given: * *

 * - Apply [X.*, e = EXISTS (true)]
 *   - X
 *   - S with cardinality = 0
 * 
*

* Produces: * *

 * - Project [X.*, e = false]
 *   - X
 * 
*/ public class RemoveRedundantExists implements Rule { private static final Pattern PATTERN = applyNode() .matching(node -> node.getSubqueryAssignments().values().stream().allMatch(ApplyNode.Exists.class::isInstance)); @Override public Pattern getPattern() { return PATTERN; } @Override public Result apply(ApplyNode node, Captures captures, Context context) { Assignments.Builder assignments = Assignments.builder(); assignments.putIdentities(node.getInput().getOutputSymbols()); Cardinality subqueryCardinality = extractCardinality(node.getSubquery(), context.getLookup()); Expression result; if (subqueryCardinality.isEmpty()) { result = FALSE; } else if (subqueryCardinality.isAtLeastScalar()) { result = TRUE; } else { return Result.empty(); } for (Symbol output : node.getSubqueryAssignments().keySet()) { assignments.put(output, result); } return Result.ofPlanNode(new ProjectNode( context.getIdAllocator().getNextId(), node.getInput(), assignments.build())); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy