Search in sources :

Example 66 with ImmutableBitSet

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.util.ImmutableBitSet in project flink by apache.

the class StreamPhysicalPythonOverAggregateRule method convert.

@Override
public RelNode convert(RelNode rel) {
    FlinkLogicalOverAggregate logicWindow = (FlinkLogicalOverAggregate) rel;
    if (logicWindow.groups.size() > 1) {
        throw new TableException("Over Agg: Unsupported use of OVER windows. " + "All aggregates must be computed on the same window. " + "please re-check the over window statement.");
    }
    ImmutableBitSet keys = logicWindow.groups.get(0).keys;
    FlinkRelDistribution requiredDistribution;
    if (!keys.isEmpty()) {
        requiredDistribution = FlinkRelDistribution.hash(keys.asList(), true);
    } else {
        requiredDistribution = FlinkRelDistribution.SINGLETON();
    }
    RelNode input = logicWindow.getInput();
    RelTraitSet requiredTraitSet = input.getTraitSet().replace(FlinkConventions.STREAM_PHYSICAL()).replace(requiredDistribution);
    RelTraitSet providedTraitSet = rel.getTraitSet().replace(FlinkConventions.STREAM_PHYSICAL());
    RelNode newInput = RelOptRule.convert(input, requiredTraitSet);
    return new StreamPhysicalPythonOverAggregate(rel.getCluster(), providedTraitSet, newInput, rel.getRowType(), logicWindow);
}
Also used : TableException(org.apache.flink.table.api.TableException) FlinkRelDistribution(org.apache.flink.table.planner.plan.trait.FlinkRelDistribution) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) RelNode(org.apache.calcite.rel.RelNode) FlinkLogicalOverAggregate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalOverAggregate) StreamPhysicalPythonOverAggregate(org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalPythonOverAggregate) RelTraitSet(org.apache.calcite.plan.RelTraitSet)

Example 67 with ImmutableBitSet

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.util.ImmutableBitSet in project flink by apache.

the class RankProcessStrategy method analyzeRankProcessStrategies.

/**
 * Gets {@link RankProcessStrategy} based on input, partitionKey and orderKey.
 */
static List<RankProcessStrategy> analyzeRankProcessStrategies(StreamPhysicalRel rank, ImmutableBitSet partitionKey, RelCollation orderKey) {
    FlinkRelMetadataQuery mq = (FlinkRelMetadataQuery) rank.getCluster().getMetadataQuery();
    List<RelFieldCollation> fieldCollations = orderKey.getFieldCollations();
    boolean isUpdateStream = !ChangelogPlanUtils.inputInsertOnly(rank);
    RelNode input = rank.getInput(0);
    if (isUpdateStream) {
        Set<ImmutableBitSet> upsertKeys = mq.getUpsertKeysInKeyGroupRange(input, partitionKey.toArray());
        if (upsertKeys == null || upsertKeys.isEmpty() || // upsert key should contains partition key
        upsertKeys.stream().noneMatch(k -> k.contains(partitionKey))) {
            // and we fall back to using retract rank
            return Collections.singletonList(RETRACT_STRATEGY);
        } else {
            FlinkRelMetadataQuery fmq = FlinkRelMetadataQuery.reuseOrCreate(mq);
            RelModifiedMonotonicity monotonicity = fmq.getRelModifiedMonotonicity(input);
            boolean isMonotonic = false;
            if (monotonicity != null && !fieldCollations.isEmpty()) {
                isMonotonic = fieldCollations.stream().allMatch(collation -> {
                    SqlMonotonicity fieldMonotonicity = monotonicity.fieldMonotonicities()[collation.getFieldIndex()];
                    RelFieldCollation.Direction direction = collation.direction;
                    if ((fieldMonotonicity == SqlMonotonicity.DECREASING || fieldMonotonicity == SqlMonotonicity.STRICTLY_DECREASING) && direction == RelFieldCollation.Direction.ASCENDING) {
                        // is decreasing
                        return true;
                    } else if ((fieldMonotonicity == SqlMonotonicity.INCREASING || fieldMonotonicity == SqlMonotonicity.STRICTLY_INCREASING) && direction == RelFieldCollation.Direction.DESCENDING) {
                        // is increasing
                        return true;
                    } else {
                        // it is monotonic
                        return fieldMonotonicity == SqlMonotonicity.CONSTANT;
                    }
                });
            }
            if (isMonotonic) {
                // TODO: choose a set of primary key
                return Arrays.asList(new UpdateFastStrategy(upsertKeys.iterator().next().toArray()), RETRACT_STRATEGY);
            } else {
                return Collections.singletonList(RETRACT_STRATEGY);
            }
        }
    } else {
        return Collections.singletonList(APPEND_FAST_STRATEGY);
    }
}
Also used : ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) SqlMonotonicity(org.apache.calcite.sql.validate.SqlMonotonicity) Arrays(java.util.Arrays) JsonCreator(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator) FlinkRelMetadataQuery(org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery) RelModifiedMonotonicity(org.apache.flink.table.planner.plan.trait.RelModifiedMonotonicity) JsonSubTypes(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonSubTypes) Set(java.util.Set) RelNode(org.apache.calcite.rel.RelNode) FlinkChangelogModeInferenceProgram(org.apache.flink.table.planner.plan.optimize.program.FlinkChangelogModeInferenceProgram) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) StringUtils(org.apache.commons.lang3.StringUtils) StreamPhysicalRel(org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalRel) JsonProperty(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty) JsonIgnore(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore) List(java.util.List) RelCollation(org.apache.calcite.rel.RelCollation) JsonTypeInfo(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo) JsonIgnoreProperties(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties) JsonTypeName(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeName) Collections(java.util.Collections) RelNode(org.apache.calcite.rel.RelNode) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) SqlMonotonicity(org.apache.calcite.sql.validate.SqlMonotonicity) FlinkRelMetadataQuery(org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery) RelModifiedMonotonicity(org.apache.flink.table.planner.plan.trait.RelModifiedMonotonicity)

Example 68 with ImmutableBitSet

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.util.ImmutableBitSet in project beam by apache.

the class AggregateScanConverter method convert.

@Override
public RelNode convert(ResolvedAggregateScan zetaNode, List<RelNode> inputs) {
    LogicalProject input = convertAggregateScanInputScanToLogicalProject(zetaNode, inputs.get(0));
    // Calcite LogicalAggregate's GroupSet is indexes of group fields starting from 0.
    int groupFieldsListSize = zetaNode.getGroupByList().size();
    ImmutableBitSet groupSet;
    if (groupFieldsListSize != 0) {
        groupSet = ImmutableBitSet.of(IntStream.rangeClosed(0, groupFieldsListSize - 1).boxed().collect(Collectors.toList()));
    } else {
        groupSet = ImmutableBitSet.of();
    }
    // TODO: add support for indicator
    List<AggregateCall> aggregateCalls;
    if (zetaNode.getAggregateList().isEmpty()) {
        aggregateCalls = ImmutableList.of();
    } else {
        aggregateCalls = new ArrayList<>();
        // For aggregate calls, their input ref follow after GROUP BY input ref.
        int columnRefoff = groupFieldsListSize;
        for (ResolvedComputedColumn computedColumn : zetaNode.getAggregateList()) {
            AggregateCall aggCall = convertAggCall(computedColumn, columnRefoff, groupSet.size(), input);
            aggregateCalls.add(aggCall);
            if (!aggCall.getArgList().isEmpty()) {
                // Only increment column reference offset when aggregates use them (BEAM-8042).
                // Ex: COUNT(*) does not have arguments, while COUNT(`field`) does.
                columnRefoff++;
            }
        }
    }
    LogicalAggregate logicalAggregate = new LogicalAggregate(getCluster(), input.getTraitSet(), input, groupSet, ImmutableList.of(groupSet), aggregateCalls);
    return logicalAggregate;
}
Also used : AggregateCall(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.core.AggregateCall) LogicalAggregate(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.logical.LogicalAggregate) ImmutableBitSet(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.util.ImmutableBitSet) LogicalProject(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.logical.LogicalProject) ResolvedComputedColumn(com.google.zetasql.resolvedast.ResolvedNodes.ResolvedComputedColumn)

Example 69 with ImmutableBitSet

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.util.ImmutableBitSet in project druid by druid-io.

the class Grouping method applyProject.

/**
 * Applies a post-grouping projection.
 *
 * @see DruidQuery#computeGrouping which uses this
 */
public Grouping applyProject(final PlannerContext plannerContext, final Project project) {
    final List<DimensionExpression> newDimensions = new ArrayList<>();
    final List<Aggregation> newAggregations = new ArrayList<>(aggregations);
    final Subtotals newSubtotals;
    final Projection postAggregationProjection = Projection.postAggregation(project, plannerContext, outputRowSignature, "p");
    postAggregationProjection.getPostAggregators().forEach(postAggregator -> newAggregations.add(Aggregation.create(postAggregator)));
    // Remove literal dimensions that did not appear in the projection. This is useful for queries
    // like "SELECT COUNT(*) FROM tbl GROUP BY 'dummy'" which some tools can generate, and for which we don't
    // actually want to include a dimension 'dummy'.
    final ImmutableBitSet aggregateProjectBits = RelOptUtil.InputFinder.bits(project.getChildExps(), null);
    final int[] newDimIndexes = new int[dimensions.size()];
    boolean droppedDimensions = false;
    for (int i = 0; i < dimensions.size(); i++) {
        final DimensionExpression dimension = dimensions.get(i);
        if (Parser.parse(dimension.getDruidExpression().getExpression(), plannerContext.getExprMacroTable()).isLiteral() && !aggregateProjectBits.get(i)) {
            droppedDimensions = true;
            newDimIndexes[i] = -1;
        } else {
            newDimIndexes[i] = newDimensions.size();
            newDimensions.add(dimension);
        }
    }
    // Renumber subtotals, if needed, to account for removed dummy dimensions.
    if (newDimensions.size() != dimensions.size()) {
        final List<IntList> newSubtotalsList = new ArrayList<>();
        for (IntList subtotal : subtotals.getSubtotals()) {
            final IntList newSubtotal = new IntArrayList();
            for (int dimIndex : subtotal) {
                final int newDimIndex = newDimIndexes[dimIndex];
                if (newDimIndex >= 0) {
                    newSubtotal.add(newDimIndex);
                }
            }
            newSubtotalsList.add(newSubtotal);
        }
        newSubtotals = new Subtotals(newSubtotalsList);
    } else {
        newSubtotals = subtotals;
    }
    return Grouping.create(newDimensions, newSubtotals, newAggregations, havingFilter, postAggregationProjection.getOutputRowSignature(), droppedDimensions);
}
Also used : ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) ArrayList(java.util.ArrayList) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) DimensionExpression(org.apache.druid.sql.calcite.aggregation.DimensionExpression) IntList(it.unimi.dsi.fastutil.ints.IntList) Aggregation(org.apache.druid.sql.calcite.aggregation.Aggregation) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList)

Example 70 with ImmutableBitSet

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.util.ImmutableBitSet in project hive by apache.

the class RelOptHiveTable method generateKeys.

private Pair<List<ImmutableBitSet>, List<ImmutableBitSet>> generateKeys() {
    final PrimaryKeyInfo primaryKeyInfo = hiveTblMetadata.getPrimaryKeyInfo();
    final UniqueConstraint uniqueKeyInfo = hiveTblMetadata.getUniqueKeyInfo();
    ImmutableList.Builder<ImmutableBitSet> builder = ImmutableList.builder();
    ImmutableList.Builder<ImmutableBitSet> nonNullbuilder = ImmutableList.builder();
    // First PK
    if (primaryKeyInfo != null && !primaryKeyInfo.getColNames().isEmpty()) {
        ImmutableBitSet.Builder keys = ImmutableBitSet.builder();
        for (String pkColName : primaryKeyInfo.getColNames().values()) {
            int pkPos;
            for (pkPos = 0; pkPos < rowType.getFieldNames().size(); pkPos++) {
                String colName = rowType.getFieldNames().get(pkPos);
                if (pkColName.equals(colName)) {
                    break;
                }
            }
            if (pkPos == rowType.getFieldNames().size()) {
                LOG.error("Column for primary key definition " + pkColName + " not found");
            }
            keys.set(pkPos);
        }
        ImmutableBitSet key = keys.build();
        builder.add(key);
        nonNullbuilder.add(key);
    }
    // Then UKs
    if (uniqueKeyInfo != null && !uniqueKeyInfo.getUniqueConstraints().isEmpty()) {
        for (List<UniqueConstraintCol> ukCols : uniqueKeyInfo.getUniqueConstraints().values()) {
            ImmutableBitSet.Builder keys = ImmutableBitSet.builder();
            boolean isNonNullable = true;
            for (UniqueConstraintCol ukCol : ukCols) {
                int ukPos;
                for (ukPos = 0; ukPos < rowType.getFieldNames().size(); ukPos++) {
                    String colName = rowType.getFieldNames().get(ukPos);
                    if (ukCol.colName.equals(colName)) {
                        if (rowType.getFieldList().get(ukPos).getType().isNullable()) {
                            // they should all be nullable
                            isNonNullable = false;
                        }
                        break;
                    }
                }
                if (ukPos == rowType.getFieldNames().size()) {
                    LOG.error("Column for unique constraint definition " + ukCol.colName + " not found");
                }
                keys.set(ukPos);
            }
            ImmutableBitSet key = keys.build();
            builder.add(key);
            if (isNonNullable) {
                nonNullbuilder.add(key);
            }
        }
    }
    return new Pair<>(builder.build(), nonNullbuilder.build());
}
Also used : UniqueConstraintCol(org.apache.hadoop.hive.ql.metadata.UniqueConstraint.UniqueConstraintCol) PrimaryKeyInfo(org.apache.hadoop.hive.ql.metadata.PrimaryKeyInfo) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) ImmutableList(com.google.common.collect.ImmutableList) UniqueConstraint(org.apache.hadoop.hive.ql.metadata.UniqueConstraint) UniqueConstraint(org.apache.hadoop.hive.ql.metadata.UniqueConstraint) RelReferentialConstraint(org.apache.calcite.rel.RelReferentialConstraint) IntPair(org.apache.calcite.util.mapping.IntPair) Pair(org.apache.calcite.util.Pair)

Aggregations

ImmutableBitSet (org.apache.calcite.util.ImmutableBitSet)208 RexNode (org.apache.calcite.rex.RexNode)127 RelNode (org.apache.calcite.rel.RelNode)110 ArrayList (java.util.ArrayList)101 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)66 RexBuilder (org.apache.calcite.rex.RexBuilder)60 AggregateCall (org.apache.calcite.rel.core.AggregateCall)55 RexInputRef (org.apache.calcite.rex.RexInputRef)45 RelDataType (org.apache.calcite.rel.type.RelDataType)39 HashMap (java.util.HashMap)36 RelBuilder (org.apache.calcite.tools.RelBuilder)36 RelMetadataQuery (org.apache.calcite.rel.metadata.RelMetadataQuery)30 Mapping (org.apache.calcite.util.mapping.Mapping)30 Pair (org.apache.calcite.util.Pair)29 Aggregate (org.apache.calcite.rel.core.Aggregate)27 ImmutableList (com.google.common.collect.ImmutableList)23 LinkedHashSet (java.util.LinkedHashSet)23 List (java.util.List)22 HashSet (java.util.HashSet)20 RelOptUtil (org.apache.calcite.plan.RelOptUtil)18