Search in sources :

Example 16 with Quantifier

use of com.apple.foundationdb.record.query.plan.temp.Quantifier in project fdb-record-layer by FoundationDB.

the class ImplementDistinctUnionRule method onMatch.

@Override
@SuppressWarnings("java:S135")
public void onMatch(@Nonnull PlannerRuleCall call) {
    final PlanContext context = call.getContext();
    final Optional<Set<RequestedOrdering>> requiredOrderingsOptional = call.getInterestingProperty(OrderingAttribute.ORDERING);
    if (requiredOrderingsOptional.isEmpty()) {
        return;
    }
    final Set<RequestedOrdering> requestedOrderings = requiredOrderingsOptional.get();
    final KeyExpression commonPrimaryKey = context.getCommonPrimaryKey();
    if (commonPrimaryKey == null) {
        return;
    }
    final List<KeyExpression> commonPrimaryKeyParts = commonPrimaryKey.normalizeKeyForPositions();
    final PlannerBindings bindings = call.getBindings();
    final Quantifier.ForEach unionForEachQuantifier = bindings.get(unionForEachQuantifierMatcher);
    final List<? extends Collection<? extends RecordQueryPlan>> plansByQuantifier = bindings.getAll(unionLegPlansMatcher);
    // group each leg's plans by their provided ordering
    final ImmutableList<Set<Map.Entry<Ordering, ImmutableList<RecordQueryPlan>>>> plansByQuantifierOrdering = plansByQuantifier.stream().map(plansForQuantifier -> {
        final Map<Ordering, ImmutableList<RecordQueryPlan>> groupedBySortedness = plansForQuantifier.stream().flatMap(plan -> {
            final Optional<Ordering> orderingForLegOptional = OrderingProperty.evaluate(plan, context);
            return orderingForLegOptional.stream().map(ordering -> Pair.of(ordering, plan));
        }).collect(Collectors.groupingBy(Pair::getLeft, Collectors.mapping(Pair::getRight, ImmutableList.toImmutableList())));
        return groupedBySortedness.entrySet();
    }).collect(ImmutableList.toImmutableList());
    for (final List<Map.Entry<Ordering, ImmutableList<RecordQueryPlan>>> entries : CrossProduct.crossProduct(plansByQuantifierOrdering)) {
        final ImmutableList<Optional<Ordering>> orderingOptionals = entries.stream().map(entry -> Optional.of(entry.getKey())).collect(ImmutableList.toImmutableList());
        for (final RequestedOrdering requestedOrdering : requestedOrderings) {
            final Optional<Ordering> combinedOrderingOptional = OrderingProperty.deriveForUnionFromOrderings(orderingOptionals, requestedOrdering, Ordering::intersectEqualityBoundKeys);
            pushInterestingOrders(call, unionForEachQuantifier, orderingOptionals, requestedOrdering);
            if (combinedOrderingOptional.isEmpty()) {
                // 
                continue;
            }
            final Ordering ordering = combinedOrderingOptional.get();
            final Set<KeyExpression> equalityBoundKeys = ordering.getEqualityBoundKeys();
            final List<KeyPart> orderingKeyParts = ordering.getOrderingKeyParts();
            final List<KeyExpression> orderingKeys = orderingKeyParts.stream().map(KeyPart::getNormalizedKeyExpression).collect(ImmutableList.toImmutableList());
            // make sure the common primary key parts are either bound through equality or they are part of the ordering
            if (!isPrimaryKeyCompatibleWithOrdering(commonPrimaryKeyParts, orderingKeys, equalityBoundKeys)) {
                continue;
            }
            // 
            // At this point we know we can implement the distinct union over the partitions of compatibly ordered plans
            // 
            final KeyExpression comparisonKey = orderingKeys.size() == 1 ? Iterables.getOnlyElement(orderingKeys) : Key.Expressions.concat(orderingKeys);
            // 
            // create new references
            // 
            final ImmutableList<Quantifier.Physical> newQuantifiers = entries.stream().map(Map.Entry::getValue).map(GroupExpressionRef::from).map(Quantifier::physical).collect(ImmutableList.toImmutableList());
            call.yield(call.ref(RecordQueryUnionPlan.fromQuantifiers(newQuantifiers, comparisonKey, true)));
        }
    }
}
Also used : PlannerRuleCall(com.apple.foundationdb.record.query.plan.temp.PlannerRuleCall) ReferenceMatchers.references(com.apple.foundationdb.record.query.plan.temp.matchers.ReferenceMatchers.references) OrderingAttribute(com.apple.foundationdb.record.query.plan.temp.OrderingAttribute) Iterables(com.google.common.collect.Iterables) PlannerRule(com.apple.foundationdb.record.query.plan.temp.PlannerRule) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) CollectionMatcher(com.apple.foundationdb.record.query.plan.temp.matchers.CollectionMatcher) Ordering(com.apple.foundationdb.record.query.plan.temp.Ordering) GroupExpressionRef(com.apple.foundationdb.record.query.plan.temp.GroupExpressionRef) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) Key(com.apple.foundationdb.record.metadata.Key) ImmutableList(com.google.common.collect.ImmutableList) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) MultiMatcher.some(com.apple.foundationdb.record.query.plan.temp.matchers.MultiMatcher.some) RecordQueryUnionPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryUnionPlan) Nonnull(javax.annotation.Nonnull) RequestedOrdering(com.apple.foundationdb.record.query.plan.temp.RequestedOrdering) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) ImmutableSet(com.google.common.collect.ImmutableSet) LogicalDistinctExpression(com.apple.foundationdb.record.query.plan.temp.expressions.LogicalDistinctExpression) Collection(java.util.Collection) Set(java.util.Set) MultiMatcher.all(com.apple.foundationdb.record.query.plan.temp.matchers.MultiMatcher.all) PlannerBindings(com.apple.foundationdb.record.query.plan.temp.matchers.PlannerBindings) KeyPart(com.apple.foundationdb.record.query.plan.temp.KeyPart) RelationalExpressionMatchers.logicalUnionExpression(com.apple.foundationdb.record.query.plan.temp.matchers.RelationalExpressionMatchers.logicalUnionExpression) Collectors(java.util.stream.Collectors) LogicalUnionExpression(com.apple.foundationdb.record.query.plan.temp.expressions.LogicalUnionExpression) List(java.util.List) BindingMatcher(com.apple.foundationdb.record.query.plan.temp.matchers.BindingMatcher) CrossProduct(com.apple.foundationdb.record.query.combinatorics.CrossProduct) OrderingProperty(com.apple.foundationdb.record.query.plan.temp.properties.OrderingProperty) PlanContext(com.apple.foundationdb.record.query.plan.temp.PlanContext) Optional(java.util.Optional) RelationalExpressionMatchers.logicalDistinctExpression(com.apple.foundationdb.record.query.plan.temp.matchers.RelationalExpressionMatchers.logicalDistinctExpression) API(com.apple.foundationdb.annotation.API) QuantifierMatchers.forEachQuantifierOverRef(com.apple.foundationdb.record.query.plan.temp.matchers.QuantifierMatchers.forEachQuantifierOverRef) ListMatcher.exactly(com.apple.foundationdb.record.query.plan.temp.matchers.ListMatcher.exactly) QuantifierMatchers.forEachQuantifier(com.apple.foundationdb.record.query.plan.temp.matchers.QuantifierMatchers.forEachQuantifier) RecordQueryPlanMatchers(com.apple.foundationdb.record.query.plan.temp.matchers.RecordQueryPlanMatchers) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ImmutableList(com.google.common.collect.ImmutableList) KeyPart(com.apple.foundationdb.record.query.plan.temp.KeyPart) PlannerBindings(com.apple.foundationdb.record.query.plan.temp.matchers.PlannerBindings) Ordering(com.apple.foundationdb.record.query.plan.temp.Ordering) RequestedOrdering(com.apple.foundationdb.record.query.plan.temp.RequestedOrdering) Pair(org.apache.commons.lang3.tuple.Pair) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) Optional(java.util.Optional) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) RequestedOrdering(com.apple.foundationdb.record.query.plan.temp.RequestedOrdering) GroupExpressionRef(com.apple.foundationdb.record.query.plan.temp.GroupExpressionRef) PlanContext(com.apple.foundationdb.record.query.plan.temp.PlanContext) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) QuantifierMatchers.forEachQuantifier(com.apple.foundationdb.record.query.plan.temp.matchers.QuantifierMatchers.forEachQuantifier) Map(java.util.Map)

Example 17 with Quantifier

use of com.apple.foundationdb.record.query.plan.temp.Quantifier in project fdb-record-layer by FoundationDB.

the class ImplementInJoinRule method getInSourcesForRequestedOrdering.

@Nonnull
@SuppressWarnings("unchecked")
private ImmutableList<InSource> getInSourcesForRequestedOrdering(@Nonnull final Map<CorrelationIdentifier, Quantifier> explodeAliasToQuantifierMap, @Nonnull final Set<CorrelationIdentifier> explodeAliases, @Nonnull final IdentityBiMap<Quantifier.ForEach, ExplodeExpression> quantifierToExplodeBiMap, @Nonnull final Ordering providedInnerOrdering, @Nonnull final RequestedOrdering requestedOrdering) {
    final var availableExplodeAliases = Sets.newLinkedHashSet(explodeAliases);
    final var requestedOrderingKeyParts = requestedOrdering.getOrderingKeyParts();
    final var sourcesBuilder = ImmutableList.<InSource>builder();
    final var resultOrderingKeyPartsBuilder = ImmutableList.<KeyPart>builder();
    final var innerOrderingKeyParts = providedInnerOrdering.getOrderingKeyParts();
    final var innerEqualityBoundKeyMap = providedInnerOrdering.getEqualityBoundKeyMap();
    final var resultOrderingEqualityBoundKeyMap = HashMultimap.create(innerEqualityBoundKeyMap);
    for (var i = 0; i < requestedOrderingKeyParts.size() && !availableExplodeAliases.isEmpty(); i++) {
        final var requestedOrderingKeyPart = requestedOrderingKeyParts.get(i);
        final var comparisons = innerEqualityBoundKeyMap.get(requestedOrderingKeyPart.getNormalizedKeyExpression());
        if (comparisons.isEmpty()) {
            return ImmutableList.of();
        }
        final var comparisonsCorrelatedTo = comparisons.stream().flatMap(comparison -> comparison.getCorrelatedTo().stream()).collect(ImmutableSet.toImmutableSet());
        if (comparisonsCorrelatedTo.size() > 1) {
            return ImmutableList.of();
        }
        if (Sets.intersection(comparisonsCorrelatedTo, explodeAliases).isEmpty()) {
            // 
            continue;
        }
        final var explodeAlias = Iterables.getOnlyElement(comparisonsCorrelatedTo);
        // 
        if (!availableExplodeAliases.contains(explodeAlias)) {
            return ImmutableList.of();
        }
        // 
        // We need to find the one quantifier over an explode expression that we can use to establish
        // the requested order.
        // 
        final var explodeQuantifier = Objects.requireNonNull(explodeAliasToQuantifierMap.get(explodeAlias));
        final var explodeExpression = Objects.requireNonNull(quantifierToExplodeBiMap.getUnwrapped(explodeQuantifier));
        // 
        // At this point we have a bound key expression that matches the requested order at this position,
        // and we have our hands on a particular explode expression leading us directly do the in source.
        // 
        final var explodeResultValues = explodeExpression.getResultValues();
        if (explodeResultValues.size() != 1) {
            return ImmutableList.of();
        }
        final var explodeValue = Iterables.getOnlyElement(explodeResultValues);
        final InSource inSource;
        if (explodeValue instanceof LiteralValue<?>) {
            final Object literalValue = ((LiteralValue<?>) explodeValue).getLiteralValue();
            if (literalValue instanceof List<?>) {
                inSource = new SortedInValuesSource(CORRELATION.bindingName(explodeQuantifier.getAlias().getId()), (List<Object>) literalValue, requestedOrderingKeyPart.isReverse());
            } else {
                return ImmutableList.of();
            }
        } else if (explodeValue instanceof QuantifiedColumnValue) {
            inSource = new SortedInParameterSource(CORRELATION.bindingName(explodeQuantifier.getAlias().getId()), ((QuantifiedColumnValue) explodeValue).getAlias().getId(), requestedOrderingKeyPart.isReverse());
        } else {
            return ImmutableList.of();
        }
        availableExplodeAliases.remove(explodeAlias);
        sourcesBuilder.add(inSource);
        resultOrderingEqualityBoundKeyMap.removeAll(requestedOrderingKeyPart.getNormalizedKeyExpression());
        resultOrderingKeyPartsBuilder.add(requestedOrderingKeyPart);
    }
    if (availableExplodeAliases.isEmpty()) {
        // 
        // All available explode aliases have been depleted. Create an ordering and check against the requested
        // ordering.
        // 
        resultOrderingKeyPartsBuilder.addAll(innerOrderingKeyParts);
        final var resultOrdering = new Ordering(resultOrderingEqualityBoundKeyMap, resultOrderingKeyPartsBuilder.build(), providedInnerOrdering.isDistinct());
        return Ordering.satisfiesRequestedOrdering(resultOrdering, requestedOrdering) ? sourcesBuilder.build() : ImmutableList.of();
    } else {
        // 
        for (final var explodeAlias : availableExplodeAliases) {
            final var explodeQuantifier = Objects.requireNonNull(explodeAliasToQuantifierMap.get(explodeAlias));
            final var explodeExpression = Objects.requireNonNull(quantifierToExplodeBiMap.getUnwrapped(explodeQuantifier));
            final var explodeResultValues = explodeExpression.getResultValues();
            if (explodeResultValues.size() != 1) {
                return ImmutableList.of();
            }
            final var explodeValue = Iterables.getOnlyElement(explodeResultValues);
            final InSource inSource;
            if (explodeValue instanceof LiteralValue<?>) {
                final Object literalValue = ((LiteralValue<?>) explodeValue).getLiteralValue();
                if (literalValue instanceof List<?>) {
                    inSource = new InValuesSource(CORRELATION.bindingName(explodeQuantifier.getAlias().getId()), (List<Object>) literalValue);
                } else {
                    return ImmutableList.of();
                }
            } else if (explodeValue instanceof QuantifiedColumnValue) {
                inSource = new InParameterSource(CORRELATION.bindingName(explodeQuantifier.getAlias().getId()), ((QuantifiedColumnValue) explodeValue).getAlias().getId());
            } else {
                return ImmutableList.of();
            }
            sourcesBuilder.add(inSource);
        }
    }
    // 
    return sourcesBuilder.build();
}
Also used : PlannerRuleCall(com.apple.foundationdb.record.query.plan.temp.PlannerRuleCall) OrderingAttribute(com.apple.foundationdb.record.query.plan.temp.OrderingAttribute) LinkedIdentitySet(com.apple.foundationdb.record.query.plan.temp.LinkedIdentitySet) GroupExpressionRef(com.apple.foundationdb.record.query.plan.temp.GroupExpressionRef) HashMultimap(com.google.common.collect.HashMultimap) Pair(org.apache.commons.lang3.tuple.Pair) RelationalExpressionMatchers.selectExpression(com.apple.foundationdb.record.query.plan.temp.matchers.RelationalExpressionMatchers.selectExpression) Map(java.util.Map) RequestedOrdering(com.apple.foundationdb.record.query.plan.temp.RequestedOrdering) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) SelectExpression(com.apple.foundationdb.record.query.plan.temp.expressions.SelectExpression) LiteralValue(com.apple.foundationdb.record.query.predicates.LiteralValue) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Value(com.apple.foundationdb.record.query.predicates.Value) List(java.util.List) RecordQueryInUnionPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryInUnionPlan) CorrelationIdentifier(com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier) OrderingProperty(com.apple.foundationdb.record.query.plan.temp.properties.OrderingProperty) Optional(java.util.Optional) API(com.apple.foundationdb.annotation.API) InParameterSource(com.apple.foundationdb.record.query.plan.plans.InParameterSource) CORRELATION(com.apple.foundationdb.record.Bindings.Internal.CORRELATION) Iterables(com.google.common.collect.Iterables) PlannerRule(com.apple.foundationdb.record.query.plan.temp.PlannerRule) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) CollectionMatcher(com.apple.foundationdb.record.query.plan.temp.matchers.CollectionMatcher) Ordering(com.apple.foundationdb.record.query.plan.temp.Ordering) Quantifiers(com.apple.foundationdb.record.query.plan.temp.Quantifiers) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) RelationalExpressionMatchers.explodeExpression(com.apple.foundationdb.record.query.plan.temp.matchers.RelationalExpressionMatchers.explodeExpression) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) IdentityBiMap(com.apple.foundationdb.record.query.plan.temp.IdentityBiMap) PushInterestingOrderingThroughInLikeSelectRule.findInnerQuantifier(com.apple.foundationdb.record.query.plan.temp.rules.PushInterestingOrderingThroughInLikeSelectRule.findInnerQuantifier) InSource(com.apple.foundationdb.record.query.plan.plans.InSource) InValuesSource(com.apple.foundationdb.record.query.plan.plans.InValuesSource) MultiMatcher.some(com.apple.foundationdb.record.query.plan.temp.matchers.MultiMatcher.some) Nonnull(javax.annotation.Nonnull) SortedInValuesSource(com.apple.foundationdb.record.query.plan.plans.SortedInValuesSource) KeyPart(com.apple.foundationdb.record.query.plan.temp.KeyPart) SortedInParameterSource(com.apple.foundationdb.record.query.plan.plans.SortedInParameterSource) BindingMatcher(com.apple.foundationdb.record.query.plan.temp.matchers.BindingMatcher) QuantifierMatchers.forEachQuantifier(com.apple.foundationdb.record.query.plan.temp.matchers.QuantifierMatchers.forEachQuantifier) QuantifiedColumnValue(com.apple.foundationdb.record.query.predicates.QuantifiedColumnValue) ExplodeExpression(com.apple.foundationdb.record.query.plan.temp.expressions.ExplodeExpression) SortedInParameterSource(com.apple.foundationdb.record.query.plan.plans.SortedInParameterSource) KeyPart(com.apple.foundationdb.record.query.plan.temp.KeyPart) LiteralValue(com.apple.foundationdb.record.query.predicates.LiteralValue) InParameterSource(com.apple.foundationdb.record.query.plan.plans.InParameterSource) SortedInParameterSource(com.apple.foundationdb.record.query.plan.plans.SortedInParameterSource) QuantifiedColumnValue(com.apple.foundationdb.record.query.predicates.QuantifiedColumnValue) InSource(com.apple.foundationdb.record.query.plan.plans.InSource) RequestedOrdering(com.apple.foundationdb.record.query.plan.temp.RequestedOrdering) Ordering(com.apple.foundationdb.record.query.plan.temp.Ordering) InValuesSource(com.apple.foundationdb.record.query.plan.plans.InValuesSource) SortedInValuesSource(com.apple.foundationdb.record.query.plan.plans.SortedInValuesSource) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) SortedInValuesSource(com.apple.foundationdb.record.query.plan.plans.SortedInValuesSource) Nonnull(javax.annotation.Nonnull)

Example 18 with Quantifier

use of com.apple.foundationdb.record.query.plan.temp.Quantifier in project fdb-record-layer by FoundationDB.

the class PushSetOperationThroughFetchRule method onMatch.

@Override
@SuppressWarnings("java:S1905")
public void onMatch(@Nonnull PlannerRuleCall call) {
    final PlannerBindings bindings = call.getBindings();
    final RecordQuerySetPlan setOperationPlan = bindings.get(getMatcher());
    final List<? extends Quantifier.Physical> quantifiersOverFetches = bindings.getAll(quantifierOverFetchMatcher);
    // if set operation is dynamic all quantifiers must have fetches
    if (setOperationPlan.isDynamic()) {
        if (quantifiersOverFetches.size() < setOperationPlan.getQuantifiers().size()) {
            return;
        }
    } else {
        if (quantifiersOverFetches.size() <= 1) {
            // pulling up the fetch is meaningless in this case
            return;
        }
    }
    final List<? extends RecordQueryFetchFromPartialRecordPlan> fetchPlans = bindings.getAll(fetchPlanMatcher);
    final ImmutableList<TranslateValueFunction> dependentFunctions = fetchPlans.stream().map(RecordQueryFetchFromPartialRecordPlan::getPushValueFunction).collect(ImmutableList.toImmutableList());
    Verify.verify(quantifiersOverFetches.size() == fetchPlans.size());
    Verify.verify(fetchPlans.size() == dependentFunctions.size());
    final List<? extends Value> requiredValues = setOperationPlan.getRequiredValues(CorrelationIdentifier.uniqueID());
    final Set<CorrelationIdentifier> pushableAliases = setOperationPlan.tryPushValues(dependentFunctions, quantifiersOverFetches, requiredValues);
    // if set operation is dynamic all aliases must be pushable
    if (setOperationPlan.isDynamic()) {
        if (pushableAliases.size() < setOperationPlan.getQuantifiers().size()) {
            return;
        }
    } else {
        if (pushableAliases.size() <= 1) {
            // pulling up the fetch is meaningless in this case
            return;
        }
    }
    final ImmutableList.Builder<Quantifier.Physical> pushableQuantifiersBuilder = ImmutableList.builder();
    final ImmutableList.Builder<RecordQueryFetchFromPartialRecordPlan> pushableFetchPlansBuilder = ImmutableList.builder();
    final ImmutableList.Builder<TranslateValueFunction> pushableDependentFunctionsBuilder = ImmutableList.builder();
    for (int i = 0; i < quantifiersOverFetches.size(); i++) {
        final Quantifier.Physical quantifier = quantifiersOverFetches.get(i);
        if (pushableAliases.contains(quantifier.getAlias())) {
            pushableQuantifiersBuilder.add(quantifier);
            pushableFetchPlansBuilder.add(fetchPlans.get(i));
            pushableDependentFunctionsBuilder.add(dependentFunctions.get(i));
        }
    }
    final ImmutableList<Quantifier.Physical> pushableQuantifiers = pushableQuantifiersBuilder.build();
    final ImmutableList<RecordQueryFetchFromPartialRecordPlan> pushableFetchPlans = pushableFetchPlansBuilder.build();
    final ImmutableList<TranslateValueFunction> pushableDependentFunctions = pushableDependentFunctionsBuilder.build();
    final ImmutableList<Quantifier.Physical> nonPushableQuantifiers = setOperationPlan.getQuantifiers().stream().map(quantifier -> (Quantifier.Physical) quantifier).filter(quantifier -> !pushableAliases.contains(quantifier.getAlias())).collect(ImmutableList.toImmutableList());
    final List<? extends ExpressionRef<RecordQueryPlan>> newPushedInnerPlans = pushableFetchPlans.stream().map(RecordQueryFetchFromPartialRecordPlan::getChild).map(GroupExpressionRef::of).collect(ImmutableList.toImmutableList());
    Verify.verify(pushableQuantifiers.size() + nonPushableQuantifiers.size() == setOperationPlan.getQuantifiers().size());
    final TranslateValueFunction combinedTranslateValueFunction = setOperationPlan.pushValueFunction(pushableDependentFunctions);
    final RecordQuerySetPlan newSetOperationPlan = setOperationPlan.withChildrenReferences(newPushedInnerPlans);
    final RecordQueryFetchFromPartialRecordPlan newFetchPlan = new RecordQueryFetchFromPartialRecordPlan(newSetOperationPlan, combinedTranslateValueFunction);
    if (nonPushableQuantifiers.isEmpty()) {
        call.yield(GroupExpressionRef.of(newFetchPlan));
    } else {
        final List<ExpressionRef<? extends RecordQueryPlan>> newFetchPlanAndResidualInners = Streams.concat(Stream.of(GroupExpressionRef.of(newFetchPlan)), nonPushableQuantifiers.stream().map(Quantifier.Physical::getRangesOver).map(RecordQueryPlan::narrowReference)).collect(ImmutableList.toImmutableList());
        call.yield(GroupExpressionRef.of(setOperationPlan.withChildrenReferences(newFetchPlanAndResidualInners)));
    }
}
Also used : TranslateValueFunction(com.apple.foundationdb.record.query.plan.plans.TranslateValueFunction) PlannerRuleCall(com.apple.foundationdb.record.query.plan.temp.PlannerRuleCall) RecordQueryFetchFromPartialRecordPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryFetchFromPartialRecordPlan) PlannerRule(com.apple.foundationdb.record.query.plan.temp.PlannerRule) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) RecordQueryPlanMatchers.anyPlan(com.apple.foundationdb.record.query.plan.temp.matchers.RecordQueryPlanMatchers.anyPlan) GroupExpressionRef(com.apple.foundationdb.record.query.plan.temp.GroupExpressionRef) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) RecordQueryPlanMatchers.fetchFromPartialRecordPlan(com.apple.foundationdb.record.query.plan.temp.matchers.RecordQueryPlanMatchers.fetchFromPartialRecordPlan) ImmutableList(com.google.common.collect.ImmutableList) RelationalExpressionMatchers.ofTypeOwning(com.apple.foundationdb.record.query.plan.temp.matchers.RelationalExpressionMatchers.ofTypeOwning) ExpressionRef(com.apple.foundationdb.record.query.plan.temp.ExpressionRef) MultiMatcher.some(com.apple.foundationdb.record.query.plan.temp.matchers.MultiMatcher.some) Nonnull(javax.annotation.Nonnull) Verify(com.google.common.base.Verify) RecordQuerySetPlan(com.apple.foundationdb.record.query.plan.plans.RecordQuerySetPlan) QuantifierMatchers.physicalQuantifier(com.apple.foundationdb.record.query.plan.temp.matchers.QuantifierMatchers.physicalQuantifier) Set(java.util.Set) PlannerBindings(com.apple.foundationdb.record.query.plan.temp.matchers.PlannerBindings) Streams(com.google.common.collect.Streams) Value(com.apple.foundationdb.record.query.predicates.Value) List(java.util.List) BindingMatcher(com.apple.foundationdb.record.query.plan.temp.matchers.BindingMatcher) Stream(java.util.stream.Stream) CorrelationIdentifier(com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier) API(com.apple.foundationdb.annotation.API) ImmutableList(com.google.common.collect.ImmutableList) GroupExpressionRef(com.apple.foundationdb.record.query.plan.temp.GroupExpressionRef) ExpressionRef(com.apple.foundationdb.record.query.plan.temp.ExpressionRef) PlannerBindings(com.apple.foundationdb.record.query.plan.temp.matchers.PlannerBindings) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) TranslateValueFunction(com.apple.foundationdb.record.query.plan.plans.TranslateValueFunction) RecordQueryFetchFromPartialRecordPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryFetchFromPartialRecordPlan) RecordQuerySetPlan(com.apple.foundationdb.record.query.plan.plans.RecordQuerySetPlan) CorrelationIdentifier(com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) QuantifierMatchers.physicalQuantifier(com.apple.foundationdb.record.query.plan.temp.matchers.QuantifierMatchers.physicalQuantifier)

Example 19 with Quantifier

use of com.apple.foundationdb.record.query.plan.temp.Quantifier in project fdb-record-layer by FoundationDB.

the class RemoveRedundantTypeFilterRule method onMatch.

@Override
public void onMatch(@Nonnull PlannerRuleCall call) {
    final LogicalTypeFilterExpression typeFilter = call.get(root);
    final Quantifier.ForEach qun = call.get(qunMatcher);
    // TODO add overload
    final Set<String> childRecordTypes = RecordTypesProperty.evaluate(call.getContext(), call.getAliasResolver(), qun.getRangesOver());
    final Set<String> filterRecordTypes = Sets.newHashSet(typeFilter.getRecordTypes());
    if (filterRecordTypes.containsAll(childRecordTypes)) {
        // type filter is completely redundant, so remove it entirely
        call.yield(qun.getRangesOver());
    } else {
        // otherwise, keep a logical filter on record types which the quantifier might produce and are included in the filter
        final Set<String> unsatisfiedTypeFilters = Sets.intersection(childRecordTypes, filterRecordTypes);
        if (!unsatisfiedTypeFilters.equals(filterRecordTypes)) {
            // there were some unnecessary filters, so remove them
            call.yield(GroupExpressionRef.of(new LogicalTypeFilterExpression(unsatisfiedTypeFilters, qun)));
        }
    // otherwise, nothing changes
    }
}
Also used : LogicalTypeFilterExpression(com.apple.foundationdb.record.query.plan.temp.expressions.LogicalTypeFilterExpression) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier)

Example 20 with Quantifier

use of com.apple.foundationdb.record.query.plan.temp.Quantifier in project fdb-record-layer by FoundationDB.

the class RelationalExpressionWithChildren method getCorrelatedTo.

@Nonnull
@Override
@SuppressWarnings("squid:S2201")
default Set<CorrelationIdentifier> getCorrelatedTo() {
    final ImmutableSet.Builder<CorrelationIdentifier> builder = ImmutableSet.builder();
    final List<? extends Quantifier> quantifiers = getQuantifiers();
    final Map<CorrelationIdentifier, ? extends Quantifier> aliasToQuantifierMap = quantifiers.stream().collect(Collectors.toMap(Quantifier::getAlias, Function.identity()));
    // We should check if the graph is sound here, if it is not we should throw an exception. This method
    // will properly return with an empty. There are other algorithms that may not be as defensive and we
    // must protect ourselves from illegal graphs (and bugs).
    final Optional<List<CorrelationIdentifier>> orderedOptional = TopologicalSort.anyTopologicalOrderPermutation(quantifiers.stream().map(Quantifier::getAlias).collect(Collectors.toSet()), alias -> Objects.requireNonNull(aliasToQuantifierMap.get(alias)).getCorrelatedTo());
    orderedOptional.orElseThrow(() -> new IllegalArgumentException("correlations are cyclic"));
    getCorrelatedToWithoutChildren().stream().filter(correlationIdentifier -> !aliasToQuantifierMap.containsKey(correlationIdentifier)).forEach(builder::add);
    for (final Quantifier quantifier : quantifiers) {
        quantifier.getCorrelatedTo().stream().filter(correlationIdentifier -> !canCorrelate() || !aliasToQuantifierMap.containsKey(correlationIdentifier)).forEach(builder::add);
    }
    return builder.build();
}
Also used : LinkedIdentitySet(com.apple.foundationdb.record.query.plan.temp.LinkedIdentitySet) ImmutableSet(com.google.common.collect.ImmutableSet) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) Set(java.util.Set) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) RelationalExpression(com.apple.foundationdb.record.query.plan.temp.RelationalExpression) Objects(java.util.Objects) PartialMatch(com.apple.foundationdb.record.query.plan.temp.PartialMatch) List(java.util.List) CorrelationIdentifier(com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier) Map(java.util.Map) MatchInfo(com.apple.foundationdb.record.query.plan.temp.MatchInfo) Optional(java.util.Optional) API(com.apple.foundationdb.annotation.API) AliasMap(com.apple.foundationdb.record.query.plan.temp.AliasMap) Nonnull(javax.annotation.Nonnull) TopologicalSort(com.apple.foundationdb.record.query.combinatorics.TopologicalSort) ImmutableSet(com.google.common.collect.ImmutableSet) CorrelationIdentifier(com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier) List(java.util.List) Quantifier(com.apple.foundationdb.record.query.plan.temp.Quantifier) Nonnull(javax.annotation.Nonnull)

Aggregations

Quantifier (com.apple.foundationdb.record.query.plan.temp.Quantifier)23 Nonnull (javax.annotation.Nonnull)13 API (com.apple.foundationdb.annotation.API)10 ImmutableList (com.google.common.collect.ImmutableList)10 List (java.util.List)9 RelationalExpression (com.apple.foundationdb.record.query.plan.temp.RelationalExpression)8 CorrelationIdentifier (com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier)7 AliasMap (com.apple.foundationdb.record.query.plan.temp.AliasMap)6 BindingMatcher (com.apple.foundationdb.record.query.plan.temp.matchers.BindingMatcher)6 QueryPredicate (com.apple.foundationdb.record.query.predicates.QueryPredicate)6 Value (com.apple.foundationdb.record.query.predicates.Value)6 GroupExpressionRef (com.apple.foundationdb.record.query.plan.temp.GroupExpressionRef)5 PlannerRule (com.apple.foundationdb.record.query.plan.temp.PlannerRule)5 PlannerRuleCall (com.apple.foundationdb.record.query.plan.temp.PlannerRuleCall)5 ImmutableSet (com.google.common.collect.ImmutableSet)5 Collection (java.util.Collection)5 Set (java.util.Set)5 RecordQueryPlan (com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan)4 MatchInfo (com.apple.foundationdb.record.query.plan.temp.MatchInfo)4 PartialMatch (com.apple.foundationdb.record.query.plan.temp.PartialMatch)4