Search in sources :

Example 31 with ComparisonExpression

use of com.facebook.presto.sql.tree.ComparisonExpression in project presto by prestodb.

the class TestSqlParser method testExists.

@Test
public void testExists() {
    assertStatement("SELECT EXISTS(SELECT 1)", simpleQuery(selectList(exists(simpleQuery(selectList(new LongLiteral("1")))))));
    assertStatement("SELECT EXISTS(SELECT 1) = EXISTS(SELECT 2)", simpleQuery(selectList(new ComparisonExpression(ComparisonExpression.Operator.EQUAL, exists(simpleQuery(selectList(new LongLiteral("1")))), exists(simpleQuery(selectList(new LongLiteral("2"))))))));
    assertStatement("SELECT NOT EXISTS(SELECT 1) = EXISTS(SELECT 2)", simpleQuery(selectList(new NotExpression(new ComparisonExpression(ComparisonExpression.Operator.EQUAL, exists(simpleQuery(selectList(new LongLiteral("1")))), exists(simpleQuery(selectList(new LongLiteral("2")))))))));
    assertStatement("SELECT (NOT EXISTS(SELECT 1)) = EXISTS(SELECT 2)", simpleQuery(selectList(new ComparisonExpression(ComparisonExpression.Operator.EQUAL, new NotExpression(exists(simpleQuery(selectList(new LongLiteral("1"))))), exists(simpleQuery(selectList(new LongLiteral("2"))))))));
}
Also used : QuantifiedComparisonExpression(com.facebook.presto.sql.tree.QuantifiedComparisonExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) NotExpression(com.facebook.presto.sql.tree.NotExpression) Test(org.testng.annotations.Test)

Example 32 with ComparisonExpression

use of com.facebook.presto.sql.tree.ComparisonExpression in project presto by prestodb.

the class ExpressionDomainTranslator method extractDisjuncts.

private List<Expression> extractDisjuncts(Type type, Ranges ranges, SymbolReference reference) {
    List<Expression> disjuncts = new ArrayList<>();
    List<Expression> singleValues = new ArrayList<>();
    List<Range> orderedRanges = ranges.getOrderedRanges();
    SortedRangeSet sortedRangeSet = SortedRangeSet.copyOf(type, orderedRanges);
    SortedRangeSet complement = sortedRangeSet.complement();
    List<Range> singleValueExclusionsList = complement.getOrderedRanges().stream().filter(Range::isSingleValue).collect(toList());
    List<Range> originalUnionSingleValues = SortedRangeSet.copyOf(type, singleValueExclusionsList).union(sortedRangeSet).getOrderedRanges();
    PeekingIterator<Range> singleValueExclusions = peekingIterator(singleValueExclusionsList.iterator());
    for (Range range : originalUnionSingleValues) {
        if (range.isSingleValue()) {
            singleValues.add(literalEncoder.toExpression(range.getSingleValue(), type));
            continue;
        }
        // attempt to optimize ranges that can be coalesced as long as single value points are excluded
        List<Expression> singleValuesInRange = new ArrayList<>();
        while (singleValueExclusions.hasNext() && range.contains(singleValueExclusions.peek())) {
            singleValuesInRange.add(literalEncoder.toExpression(singleValueExclusions.next().getSingleValue(), type));
        }
        if (!singleValuesInRange.isEmpty()) {
            disjuncts.add(combineRangeWithExcludedPoints(type, reference, range, singleValuesInRange));
            continue;
        }
        disjuncts.add(processRange(type, range, reference));
    }
    // Add back all of the possible single values either as an equality or an IN predicate
    if (singleValues.size() == 1) {
        disjuncts.add(new ComparisonExpression(EQUAL, reference, getOnlyElement(singleValues)));
    } else if (singleValues.size() > 1) {
        disjuncts.add(new InPredicate(reference, new InListExpression(singleValues)));
    }
    return disjuncts;
}
Also used : ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) SortedRangeSet(com.facebook.presto.common.predicate.SortedRangeSet) NotExpression(com.facebook.presto.sql.tree.NotExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) InListExpression(com.facebook.presto.sql.tree.InListExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) ArrayList(java.util.ArrayList) InListExpression(com.facebook.presto.sql.tree.InListExpression) Range(com.facebook.presto.common.predicate.Range) InPredicate(com.facebook.presto.sql.tree.InPredicate)

Example 33 with ComparisonExpression

use of com.facebook.presto.sql.tree.ComparisonExpression in project presto by prestodb.

the class ExpressionDomainTranslator method processRange.

private Expression processRange(Type type, Range range, SymbolReference reference) {
    if (range.isAll()) {
        return TRUE_LITERAL;
    }
    if (isBetween(range)) {
        // specialize the range with BETWEEN expression if possible b/c it is currently more efficient
        return new BetweenPredicate(reference, literalEncoder.toExpression(range.getLowBoundedValue(), type), literalEncoder.toExpression(range.getHighBoundedValue(), type));
    }
    List<Expression> rangeConjuncts = new ArrayList<>();
    if (!range.isLowUnbounded()) {
        rangeConjuncts.add(new ComparisonExpression(range.isLowInclusive() ? GREATER_THAN_OR_EQUAL : GREATER_THAN, reference, literalEncoder.toExpression(range.getLowBoundedValue(), type)));
    }
    if (!range.isHighUnbounded()) {
        rangeConjuncts.add(new ComparisonExpression(range.isHighInclusive() ? LESS_THAN_OR_EQUAL : LESS_THAN, reference, literalEncoder.toExpression(range.getHighBoundedValue(), type)));
    }
    // If rangeConjuncts is null, then the range was ALL, which should already have been checked for
    checkState(!rangeConjuncts.isEmpty());
    return combineConjuncts(rangeConjuncts);
}
Also used : ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) BetweenPredicate(com.facebook.presto.sql.tree.BetweenPredicate) NotExpression(com.facebook.presto.sql.tree.NotExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) InListExpression(com.facebook.presto.sql.tree.InListExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) ArrayList(java.util.ArrayList)

Example 34 with ComparisonExpression

use of com.facebook.presto.sql.tree.ComparisonExpression in project presto by prestodb.

the class RelationPlanner method visitJoin.

@Override
protected RelationPlan visitJoin(Join node, Void context) {
    // TODO: translate the RIGHT join into a mirrored LEFT join when we refactor (@martint)
    RelationPlan leftPlan = process(node.getLeft(), context);
    Optional<Unnest> unnest = getUnnest(node.getRight());
    if (unnest.isPresent()) {
        if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
            throw notSupportedException(unnest.get(), "UNNEST on other than the right side of CROSS JOIN");
        }
        return planCrossJoinUnnest(leftPlan, node, unnest.get());
    }
    Optional<Lateral> lateral = getLateral(node.getRight());
    if (lateral.isPresent()) {
        if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
            throw notSupportedException(lateral.get(), "LATERAL on other than the right side of CROSS JOIN");
        }
        return planLateralJoin(node, leftPlan, lateral.get());
    }
    RelationPlan rightPlan = process(node.getRight(), context);
    if (node.getCriteria().isPresent() && node.getCriteria().get() instanceof JoinUsing) {
        return planJoinUsing(node, leftPlan, rightPlan);
    }
    PlanBuilder leftPlanBuilder = initializePlanBuilder(leftPlan);
    PlanBuilder rightPlanBuilder = initializePlanBuilder(rightPlan);
    // NOTE: variables must be in the same order as the outputDescriptor
    List<VariableReferenceExpression> outputs = ImmutableList.<VariableReferenceExpression>builder().addAll(leftPlan.getFieldMappings()).addAll(rightPlan.getFieldMappings()).build();
    ImmutableList.Builder<JoinNode.EquiJoinClause> equiClauses = ImmutableList.builder();
    List<Expression> complexJoinExpressions = new ArrayList<>();
    List<Expression> postInnerJoinConditions = new ArrayList<>();
    if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
        Expression criteria = analysis.getJoinCriteria(node);
        RelationType left = analysis.getOutputDescriptor(node.getLeft());
        RelationType right = analysis.getOutputDescriptor(node.getRight());
        List<Expression> leftComparisonExpressions = new ArrayList<>();
        List<Expression> rightComparisonExpressions = new ArrayList<>();
        List<ComparisonExpression.Operator> joinConditionComparisonOperators = new ArrayList<>();
        for (Expression conjunct : ExpressionUtils.extractConjuncts(criteria)) {
            conjunct = ExpressionUtils.normalize(conjunct);
            if (!isEqualComparisonExpression(conjunct) && node.getType() != INNER) {
                complexJoinExpressions.add(conjunct);
                continue;
            }
            Set<QualifiedName> dependencies = VariablesExtractor.extractNames(conjunct, analysis.getColumnReferences());
            if (dependencies.stream().allMatch(left::canResolve) || dependencies.stream().allMatch(right::canResolve)) {
                // If the conjunct can be evaluated entirely with the inputs on either side of the join, add
                // it to the list complex expressions and let the optimizers figure out how to push it down later.
                complexJoinExpressions.add(conjunct);
            } else if (conjunct instanceof ComparisonExpression) {
                Expression firstExpression = ((ComparisonExpression) conjunct).getLeft();
                Expression secondExpression = ((ComparisonExpression) conjunct).getRight();
                ComparisonExpression.Operator comparisonOperator = ((ComparisonExpression) conjunct).getOperator();
                Set<QualifiedName> firstDependencies = VariablesExtractor.extractNames(firstExpression, analysis.getColumnReferences());
                Set<QualifiedName> secondDependencies = VariablesExtractor.extractNames(secondExpression, analysis.getColumnReferences());
                if (firstDependencies.stream().allMatch(left::canResolve) && secondDependencies.stream().allMatch(right::canResolve)) {
                    leftComparisonExpressions.add(firstExpression);
                    rightComparisonExpressions.add(secondExpression);
                    addNullFilters(complexJoinExpressions, node.getType(), firstExpression, secondExpression);
                    joinConditionComparisonOperators.add(comparisonOperator);
                } else if (firstDependencies.stream().allMatch(right::canResolve) && secondDependencies.stream().allMatch(left::canResolve)) {
                    leftComparisonExpressions.add(secondExpression);
                    rightComparisonExpressions.add(firstExpression);
                    addNullFilters(complexJoinExpressions, node.getType(), secondExpression, firstExpression);
                    joinConditionComparisonOperators.add(comparisonOperator.flip());
                } else {
                    // the case when we mix variables from both left and right join side on either side of condition.
                    complexJoinExpressions.add(conjunct);
                }
            } else {
                complexJoinExpressions.add(conjunct);
            }
        }
        leftPlanBuilder = subqueryPlanner.handleSubqueries(leftPlanBuilder, leftComparisonExpressions, node);
        rightPlanBuilder = subqueryPlanner.handleSubqueries(rightPlanBuilder, rightComparisonExpressions, node);
        // Add projections for join criteria
        leftPlanBuilder = leftPlanBuilder.appendProjections(leftComparisonExpressions, variableAllocator, idAllocator);
        rightPlanBuilder = rightPlanBuilder.appendProjections(rightComparisonExpressions, variableAllocator, idAllocator);
        for (int i = 0; i < leftComparisonExpressions.size(); i++) {
            if (joinConditionComparisonOperators.get(i) == ComparisonExpression.Operator.EQUAL) {
                VariableReferenceExpression leftVariable = leftPlanBuilder.translateToVariable(leftComparisonExpressions.get(i));
                VariableReferenceExpression righVariable = rightPlanBuilder.translateToVariable(rightComparisonExpressions.get(i));
                equiClauses.add(new JoinNode.EquiJoinClause(leftVariable, righVariable));
            } else {
                Expression leftExpression = leftPlanBuilder.rewrite(leftComparisonExpressions.get(i));
                Expression rightExpression = rightPlanBuilder.rewrite(rightComparisonExpressions.get(i));
                postInnerJoinConditions.add(new ComparisonExpression(joinConditionComparisonOperators.get(i), leftExpression, rightExpression));
            }
        }
    }
    PlanNode root = new JoinNode(getSourceLocation(node), idAllocator.getNextId(), JoinNodeUtils.typeConvert(node.getType()), leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(), ImmutableList.<VariableReferenceExpression>builder().addAll(leftPlanBuilder.getRoot().getOutputVariables()).addAll(rightPlanBuilder.getRoot().getOutputVariables()).build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), ImmutableMap.of());
    if (node.getType() != INNER) {
        for (Expression complexExpression : complexJoinExpressions) {
            Set<InPredicate> inPredicates = subqueryPlanner.collectInPredicateSubqueries(complexExpression, node);
            if (!inPredicates.isEmpty()) {
                InPredicate inPredicate = Iterables.getLast(inPredicates);
                throw notSupportedException(inPredicate, "IN with subquery predicate in join condition");
            }
        }
        // subqueries can be applied only to one side of join - left side is selected in arbitrary way
        leftPlanBuilder = subqueryPlanner.handleUncorrelatedSubqueries(leftPlanBuilder, complexJoinExpressions, node);
    }
    RelationPlan intermediateRootRelationPlan = new RelationPlan(root, analysis.getScope(node), outputs);
    TranslationMap translationMap = new TranslationMap(intermediateRootRelationPlan, analysis, lambdaDeclarationToVariableMap);
    translationMap.setFieldMappings(outputs);
    translationMap.putExpressionMappingsFrom(leftPlanBuilder.getTranslations());
    translationMap.putExpressionMappingsFrom(rightPlanBuilder.getTranslations());
    if (node.getType() != INNER && !complexJoinExpressions.isEmpty()) {
        Expression joinedFilterCondition = ExpressionUtils.and(complexJoinExpressions);
        Expression rewrittenFilterCondition = translationMap.rewrite(joinedFilterCondition);
        root = new JoinNode(getSourceLocation(node), idAllocator.getNextId(), JoinNodeUtils.typeConvert(node.getType()), leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(), ImmutableList.<VariableReferenceExpression>builder().addAll(leftPlanBuilder.getRoot().getOutputVariables()).addAll(rightPlanBuilder.getRoot().getOutputVariables()).build(), Optional.of(castToRowExpression(rewrittenFilterCondition)), Optional.empty(), Optional.empty(), Optional.empty(), ImmutableMap.of());
    }
    if (node.getType() == INNER) {
        // rewrite all the other conditions using output variables from left + right plan node.
        PlanBuilder rootPlanBuilder = new PlanBuilder(translationMap, root);
        rootPlanBuilder = subqueryPlanner.handleSubqueries(rootPlanBuilder, complexJoinExpressions, node);
        for (Expression expression : complexJoinExpressions) {
            postInnerJoinConditions.add(rootPlanBuilder.rewrite(expression));
        }
        root = rootPlanBuilder.getRoot();
        Expression postInnerJoinCriteria;
        if (!postInnerJoinConditions.isEmpty()) {
            postInnerJoinCriteria = ExpressionUtils.and(postInnerJoinConditions);
            root = new FilterNode(getSourceLocation(postInnerJoinCriteria), idAllocator.getNextId(), root, castToRowExpression(postInnerJoinCriteria));
        }
    }
    return new RelationPlan(root, analysis.getScope(node), outputs);
}
Also used : AggregationNode.singleGroupingSet(com.facebook.presto.spi.plan.AggregationNode.singleGroupingSet) Set(java.util.Set) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) FilterNode(com.facebook.presto.spi.plan.FilterNode) ArrayList(java.util.ArrayList) PlanNode(com.facebook.presto.spi.plan.PlanNode) RelationType(com.facebook.presto.sql.analyzer.RelationType) Unnest(com.facebook.presto.sql.tree.Unnest) Lateral(com.facebook.presto.sql.tree.Lateral) LateralJoinNode(com.facebook.presto.sql.planner.plan.LateralJoinNode) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) QualifiedName(com.facebook.presto.sql.tree.QualifiedName) JoinUsing(com.facebook.presto.sql.tree.JoinUsing) InPredicate(com.facebook.presto.sql.tree.InPredicate) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) ExpressionTreeUtils.isEqualComparisonExpression(com.facebook.presto.sql.analyzer.ExpressionTreeUtils.isEqualComparisonExpression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) OriginalExpressionUtils.castToRowExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToRowExpression) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) RowExpression(com.facebook.presto.spi.relation.RowExpression) DereferenceExpression(com.facebook.presto.sql.tree.DereferenceExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) ExpressionTreeUtils.isEqualComparisonExpression(com.facebook.presto.sql.analyzer.ExpressionTreeUtils.isEqualComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression)

Aggregations

ComparisonExpression (com.facebook.presto.sql.tree.ComparisonExpression)34 Test (org.testng.annotations.Test)16 Expression (com.facebook.presto.sql.tree.Expression)15 VariableReferenceExpression (com.facebook.presto.spi.relation.VariableReferenceExpression)12 SymbolReference (com.facebook.presto.sql.tree.SymbolReference)12 LongLiteral (com.facebook.presto.sql.tree.LongLiteral)10 ArrayList (java.util.ArrayList)10 LogicalBinaryExpression (com.facebook.presto.sql.tree.LogicalBinaryExpression)9 NotExpression (com.facebook.presto.sql.tree.NotExpression)9 InListExpression (com.facebook.presto.sql.tree.InListExpression)7 Cast (com.facebook.presto.sql.tree.Cast)6 StringLiteral (com.facebook.presto.sql.tree.StringLiteral)6 DoubleLiteral (com.facebook.presto.sql.tree.DoubleLiteral)5 ImmutableList (com.google.common.collect.ImmutableList)5 InPredicate (com.facebook.presto.sql.tree.InPredicate)4 IsNullPredicate (com.facebook.presto.sql.tree.IsNullPredicate)4 Session (com.facebook.presto.Session)3 ProjectNode (com.facebook.presto.spi.plan.ProjectNode)3 JoinNode (com.facebook.presto.sql.planner.plan.JoinNode)3 BetweenPredicate (com.facebook.presto.sql.tree.BetweenPredicate)3