Java Code Examples for org.apache.calcite.rel.RelFieldCollation

The following examples show how to use org.apache.calcite.rel.RelFieldCollation. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: kylin   Source File: OLAPWindowRel.java    License: Apache License 2.0 6 votes vote down vote up
ColumnRowType buildColumnRowType() {
    OLAPRel olapChild = (OLAPRel) getInput(0);
    ColumnRowType inputColumnRowType = olapChild.getColumnRowType();

    List<TblColRef> columns = new ArrayList<>();
    // the input col always be collected by left
    columns.addAll(inputColumnRowType.getAllColumns());

    // add window aggregate calls column
    for (Group group : groups) {
        List<TupleExpression> sourceColOuter = Lists.newArrayList();
        group.keys.asSet().stream().map(inputColumnRowType::getTupleExpressionByIndex).forEach(sourceColOuter::add);
        group.orderKeys.getFieldCollations().stream().map(RelFieldCollation::getFieldIndex)
                .map(inputColumnRowType::getTupleExpressionByIndex).forEach(sourceColOuter::add);
        for (AggregateCall aggrCall : group.getAggregateCalls(this)) {
            TblColRef aggrCallCol = TblColRef.newInnerColumn(aggrCall.getName(),
                    TblColRef.InnerDataTypeEnum.LITERAL);
            List<TupleExpression> sourceColInner = Lists.newArrayList(sourceColOuter.iterator());
            aggrCall.getArgList().stream().filter(i -> i < inputColumnRowType.size())
                    .map(inputColumnRowType::getTupleExpressionByIndex).forEach(sourceColInner::add);
            aggrCallCol.setSubTupleExps(sourceColInner);
            columns.add(aggrCallCol);
        }
    }
    return new ColumnRowType(columns);
}
 
Example 2
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
/** Converts a collation to an ORDER BY item. */
public SqlNode toSql(RelFieldCollation collation) {
    SqlNode node = field(collation.getFieldIndex());
    switch (collation.getDirection()) {
    case DESCENDING:
    case STRICTLY_DESCENDING:
        node = SqlStdOperatorTable.DESC.createCall(POS, node);
    }
    if (collation.nullDirection != dialect.defaultNullDirection(collation.direction)) {
        switch (collation.nullDirection) {
        case FIRST:
            node = SqlStdOperatorTable.NULLS_FIRST.createCall(POS, node);
            break;
        case LAST:
            node = SqlStdOperatorTable.NULLS_LAST.createCall(POS, node);
            break;
        }
    }
    return node;
}
 
Example 3
Source Project: calcite   Source File: GeodeSort.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void implement(GeodeImplementContext geodeImplementContext) {
  geodeImplementContext.visitChild(getInput());

  List<RelFieldCollation> sortCollations = collation.getFieldCollations();

  if (!sortCollations.isEmpty()) {

    List<String> orderByFields = new ArrayList<>();

    for (RelFieldCollation fieldCollation : sortCollations) {
      final String name = fieldName(fieldCollation.getFieldIndex());
      orderByFields.add(name + " " + direction(fieldCollation.getDirection()));
    }
    geodeImplementContext.addOrderByFields(orderByFields);
  }

  if (fetch != null) {
    geodeImplementContext.setLimit(((RexLiteral) fetch).getValueAs(Long.class));
  }
}
 
Example 4
Source Project: Bats   Source File: RelStructuredTypeFlattener.java    License: Apache License 2.0 6 votes vote down vote up
public void rewriteRel(Sort rel) {
    RelCollation oldCollation = rel.getCollation();
    final RelNode oldChild = rel.getInput();
    final RelNode newChild = getNewForOldRel(oldChild);
    final Mappings.TargetMapping mapping = getNewForOldInputMapping(oldChild);

    // validate
    for (RelFieldCollation field : oldCollation.getFieldCollations()) {
        int oldInput = field.getFieldIndex();
        RelDataType sortFieldType = oldChild.getRowType().getFieldList().get(oldInput).getType();
        if (sortFieldType.isStruct()) {
            // TODO jvs 10-Feb-2005
            throw Util.needToImplement("sorting on structured types");
        }
    }
    RelCollation newCollation = RexUtil.apply(mapping, oldCollation);
    Sort newRel = LogicalSort.create(newChild, newCollation, rel.offset, rel.fetch);
    setNewForOldRel(rel, newRel);
}
 
Example 5
Source Project: calcite   Source File: RelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static RelFieldCollation collation(RexNode node,
    RelFieldCollation.Direction direction,
    RelFieldCollation.NullDirection nullDirection, List<RexNode> extraNodes) {
  switch (node.getKind()) {
  case INPUT_REF:
    return new RelFieldCollation(((RexInputRef) node).getIndex(), direction,
        Util.first(nullDirection, direction.defaultNullDirection()));
  case DESCENDING:
    return collation(((RexCall) node).getOperands().get(0),
        RelFieldCollation.Direction.DESCENDING,
        nullDirection, extraNodes);
  case NULLS_FIRST:
    return collation(((RexCall) node).getOperands().get(0), direction,
        RelFieldCollation.NullDirection.FIRST, extraNodes);
  case NULLS_LAST:
    return collation(((RexCall) node).getOperands().get(0), direction,
        RelFieldCollation.NullDirection.LAST, extraNodes);
  default:
    final int fieldIndex = extraNodes.size();
    extraNodes.add(node);
    return new RelFieldCollation(fieldIndex, direction,
        Util.first(nullDirection, direction.defaultNullDirection()));
  }
}
 
Example 6
Source Project: Bats   Source File: RelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns references to fields for a given collation. */
public ImmutableList<RexNode> fields(RelCollation collation) {
    final ImmutableList.Builder<RexNode> nodes = ImmutableList.builder();
    for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
        RexNode node = field(fieldCollation.getFieldIndex());
        switch (fieldCollation.direction) {
        case DESCENDING:
            node = desc(node);
        }
        switch (fieldCollation.nullDirection) {
        case FIRST:
            node = nullsFirst(node);
            break;
        case LAST:
            node = nullsLast(node);
            break;
        }
        nodes.add(node);
    }
    return nodes.build();
}
 
Example 7
Source Project: Bats   Source File: RelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static RelFieldCollation collation(RexNode node, RelFieldCollation.Direction direction,
        RelFieldCollation.NullDirection nullDirection, List<RexNode> extraNodes) {
    switch (node.getKind()) {
    case INPUT_REF:
        return new RelFieldCollation(((RexInputRef) node).getIndex(), direction,
                Util.first(nullDirection, direction.defaultNullDirection()));
    case DESCENDING:
        return collation(((RexCall) node).getOperands().get(0), RelFieldCollation.Direction.DESCENDING,
                nullDirection, extraNodes);
    case NULLS_FIRST:
        return collation(((RexCall) node).getOperands().get(0), direction, RelFieldCollation.NullDirection.FIRST,
                extraNodes);
    case NULLS_LAST:
        return collation(((RexCall) node).getOperands().get(0), direction, RelFieldCollation.NullDirection.LAST,
                extraNodes);
    default:
        final int fieldIndex = extraNodes.size();
        extraNodes.add(node);
        return new RelFieldCollation(fieldIndex, direction,
                Util.first(nullDirection, direction.defaultNullDirection()));
    }
}
 
Example 8
Source Project: Bats   Source File: RexCallBinding.java    License: Apache License 2.0 6 votes vote down vote up
@Override public SqlMonotonicity getOperandMonotonicity(int ordinal) {
  RexNode operand = operands.get(ordinal);

  if (operand instanceof RexInputRef) {
    for (RelCollation ic : inputCollations) {
      if (ic.getFieldCollations().isEmpty()) {
        continue;
      }

      for (RelFieldCollation rfc : ic.getFieldCollations()) {
        if (rfc.getFieldIndex() == ((RexInputRef) operand).getIndex()) {
          return rfc.direction.monotonicity();
          // TODO: Is it possible to have more than one RelFieldCollation for a RexInputRef?
        }
      }
    }
  } else if (operand instanceof RexCall) {
    final RexCallBinding binding =
        RexCallBinding.create(typeFactory, (RexCall) operand, inputCollations);
    return ((RexCall) operand).getOperator().getMonotonicity(binding);
  }

  return SqlMonotonicity.NOT_MONOTONIC;
}
 
Example 9
Source Project: calcite   Source File: EnumerableTraitsUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determine whether there is mapping between project input and output fields.
 * Bail out if sort relies on non-trivial expressions.
 */
private static boolean isCollationOnTrivialExpr(
    List<RexNode> projects, RelDataTypeFactory typeFactory,
    Mappings.TargetMapping map, RelFieldCollation fc, boolean passDown) {
  final int index = fc.getFieldIndex();
  int target = map.getTargetOpt(index);
  if (target < 0) {
    return false;
  }

  final RexNode node = passDown ? projects.get(index) : projects.get(target);
  if (node.isA(SqlKind.CAST)) {
    // Check whether it is a monotonic preserving cast
    final RexCall cast = (RexCall) node;
    RelFieldCollation newFieldCollation = Objects.requireNonNull(RexUtil.apply(map, fc));
    final RexCallBinding binding =
        RexCallBinding.create(typeFactory, cast,
            ImmutableList.of(RelCollations.of(newFieldCollation)));
    if (cast.getOperator().getMonotonicity(binding)
        == SqlMonotonicity.NOT_MONOTONIC) {
      return false;
    }
  }

  return true;
}
 
Example 10
Source Project: Bats   Source File: DrillSortRel.java    License: Apache License 2.0 6 votes vote down vote up
public static RelNode convert(Order order, ConversionContext context) throws InvalidRelException{

    // if there are compound expressions in the order by, we need to convert into projects on either side.
    RelNode input = context.toRel(order.getInput());
    List<String> fields = input.getRowType().getFieldNames();

    // build a map of field names to indices.
    Map<String, Integer> fieldMap = Maps.newHashMap();
    int i =0;
    for(String field : fields){
      fieldMap.put(field, i);
      i++;
    }

    List<RelFieldCollation> collations = Lists.newArrayList();

    for(Ordering o : order.getOrderings()){
      String fieldName = ExprHelper.getFieldName(o.getExpr());
      int fieldId = fieldMap.get(fieldName);
      RelFieldCollation c = new RelFieldCollation(fieldId, o.getDirection(), o.getNullDirection());
      collations.add(c);
    }
    return new DrillSortRel(context.getCluster(), context.getLogicalTraits(), input, RelCollations.of(collations));
  }
 
Example 11
Source Project: calcite   Source File: RelStructuredTypeFlattener.java    License: Apache License 2.0 6 votes vote down vote up
public void rewriteRel(Sort rel) {
  RelCollation oldCollation = rel.getCollation();
  final RelNode oldChild = rel.getInput();
  final RelNode newChild = getNewForOldRel(oldChild);
  final Mappings.TargetMapping mapping =
      getNewForOldInputMapping(oldChild);

  // validate
  for (RelFieldCollation field : oldCollation.getFieldCollations()) {
    int oldInput = field.getFieldIndex();
    RelDataType sortFieldType =
        oldChild.getRowType().getFieldList().get(oldInput).getType();
    if (sortFieldType.isStruct()) {
      // TODO jvs 10-Feb-2005
      throw Util.needToImplement("sorting on structured types");
    }
  }
  RelCollation newCollation = RexUtil.apply(mapping, oldCollation);
  Sort newRel =
      LogicalSort.create(newChild, newCollation, rel.offset, rel.fetch);
  setNewForOldRel(rel, newRel);
}
 
Example 12
Source Project: calcite   Source File: SqlToRelTestBase.java    License: Apache License 2.0 6 votes vote down vote up
private List<RelCollation> deduceMonotonicity(SqlValidatorTable table) {
  final RelDataType rowType = table.getRowType();
  final List<RelCollation> collationList = new ArrayList<>();

  // Deduce which fields the table is sorted on.
  int i = -1;
  for (RelDataTypeField field : rowType.getFieldList()) {
    ++i;
    final SqlMonotonicity monotonicity =
        table.getMonotonicity(field.getName());
    if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
      final RelFieldCollation.Direction direction =
          monotonicity.isDecreasing()
              ? RelFieldCollation.Direction.DESCENDING
              : RelFieldCollation.Direction.ASCENDING;
      collationList.add(
          RelCollations.of(new RelFieldCollation(i, direction)));
    }
  }
  return collationList;
}
 
Example 13
Source Project: calcite   Source File: CassandraFilter.java    License: Apache License 2.0 6 votes vote down vote up
/** Infer the implicit correlation from the unrestricted clustering keys.
 *
 * @return The collation of the filtered results
 */
public RelCollation getImplicitCollation() {
  // No collation applies if we aren't restricted to a single partition
  if (!isSinglePartition()) {
    return RelCollations.EMPTY;
  }

  // Pull out the correct fields along with their original collations
  List<RelFieldCollation> fieldCollations = new ArrayList<>();
  for (int i = restrictedClusteringKeys; i < clusteringKeys.size(); i++) {
    int fieldIndex = fieldNames.indexOf(clusteringKeys.get(i));
    RelFieldCollation.Direction direction = implicitFieldCollations.get(i).getDirection();
    fieldCollations.add(new RelFieldCollation(fieldIndex, direction));
  }

  return RelCollations.of(fieldCollations);
}
 
Example 14
Source Project: Bats   Source File: SortPrel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Prel prepareForLateralUnnestPipeline(List<RelNode> children) {
  List<RelFieldCollation> relFieldCollations = Lists.newArrayList();
  relFieldCollations.add(new RelFieldCollation(0,
                          RelFieldCollation.Direction.ASCENDING, RelFieldCollation.NullDirection.FIRST));
  for (RelFieldCollation fieldCollation : this.collation.getFieldCollations()) {
    relFieldCollations.add(new RelFieldCollation(fieldCollation.getFieldIndex() + 1,
            fieldCollation.direction, fieldCollation.nullDirection));
  }

  RelCollation collationTrait = RelCollationImpl.of(relFieldCollations);
  RelTraitSet traits = RelTraitSet.createEmpty()
                                  .replace(this.getTraitSet().getTrait(DrillDistributionTraitDef.INSTANCE))
                                  .replace(collationTrait)
                                  .replace(DRILL_PHYSICAL);

  return this.copy(traits, children.get(0), collationTrait, this.offset, this.fetch);
}
 
Example 15
Source Project: calcite   Source File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
/** Converts a RexFieldCollation to an ORDER BY item. */
private void addOrderItem(List<SqlNode> orderByList,
                          RexProgram program, RexFieldCollation field) {
  SqlNode node = toSql(program, field.left);
  SqlNode nullDirectionNode = null;
  if (field.getNullDirection() != RelFieldCollation.NullDirection.UNSPECIFIED) {
    final boolean first =
              field.getNullDirection() == RelFieldCollation.NullDirection.FIRST;
    nullDirectionNode = dialect.emulateNullDirection(
            node, first, field.getDirection().isDescending());
  }
  if (nullDirectionNode != null) {
    orderByList.add(nullDirectionNode);
    switch (field.getDirection()) {
    case DESCENDING:
    case STRICTLY_DESCENDING:
      node = SqlStdOperatorTable.DESC.createCall(POS, node);
      break;
    default:
      break;
    }
    orderByList.add(node);
  } else {
    orderByList.add(toSql(program, field));
  }
}
 
Example 16
Source Project: calcite   Source File: RelMdCollation.java    License: Apache License 2.0 6 votes vote down vote up
private static List<RelCollation> enumerableJoin0(RelMetadataQuery mq,
    RelNode left, RelNode right, JoinRelType joinType) {
  // The current implementation can preserve the sort order of the left input if one of the
  // following conditions hold:
  // (i) join type is INNER or LEFT;
  // (ii) RelCollation always orders nulls last.
  final ImmutableList<RelCollation> leftCollations = mq.collations(left);
  switch (joinType) {
  case SEMI:
  case ANTI:
  case INNER:
  case LEFT:
    return leftCollations;
  case RIGHT:
  case FULL:
    for (RelCollation collation : leftCollations) {
      for (RelFieldCollation field : collation.getFieldCollations()) {
        if (!(RelFieldCollation.NullDirection.LAST == field.nullDirection)) {
          return ImmutableList.of();
        }
      }
    }
    return leftCollations;
  }
  return ImmutableList.of();
}
 
Example 17
Source Project: calcite   Source File: ElasticsearchSort.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void implement(Implementor implementor) {
  implementor.visitChild(0, getInput());
  final List<RelDataTypeField> fields = getRowType().getFieldList();

  for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
    final String name = fields.get(fieldCollation.getFieldIndex()).getName();
    final String rawName = implementor.expressionItemMap.getOrDefault(name, name);
    implementor.addSort(rawName, fieldCollation.getDirection());
  }

  if (offset != null) {
    implementor.offset(((RexLiteral) offset).getValueAs(Long.class));
  }

  if (fetch != null) {
    implementor.fetch(((RexLiteral) fetch).getValueAs(Long.class));
  }
}
 
Example 18
Source Project: calcite   Source File: Window.java    License: Apache License 2.0 6 votes vote down vote up
public static RelCollation getCollation(
    final List<RexFieldCollation> collations) {
  return RelCollations.of(
      new AbstractList<RelFieldCollation>() {
        public RelFieldCollation get(int index) {
          final RexFieldCollation collation = collations.get(index);
          return new RelFieldCollation(
              ((RexLocalRef) collation.left).getIndex(),
              collation.getDirection(),
              collation.getNullDirection());
        }

        public int size() {
          return collations.size();
        }
      });
}
 
Example 19
Source Project: dremio-oss   Source File: StreamAggPrel.java    License: Apache License 2.0 6 votes vote down vote up
public static void validateCollation(RelOptCluster cluster, RelNode child, ImmutableBitSet groupSet) {
  if (groupSet.isEmpty()) {
    // If no groups, no collation is required
    return;
  }

  final RelCollation requiredCollation = RelCollations.of(
      StreamSupport.stream(groupSet.spliterator(), false).map(RelFieldCollation::new).collect(Collectors.toList()));

  final RelMetadataQuery mq = cluster.getMetadataQuery();
  final List<RelCollation> collations = mq.collations(child);

  for(RelCollation collation: collations) {
    if (collation.satisfies(requiredCollation)) {
      return;
    }
  }

  throw new AssertionError("child collations [" + collations + "] does not match expected collation [" + requiredCollation + "]");
}
 
Example 20
Source Project: calcite   Source File: SqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns whether NULL values are sorted first or last, in this dialect,
 * in an ORDER BY item of a given direction. */
public @Nonnull RelFieldCollation.NullDirection defaultNullDirection(
    RelFieldCollation.Direction direction) {
  switch (direction) {
  case ASCENDING:
  case STRICTLY_ASCENDING:
    return getNullCollation().last(false)
        ? RelFieldCollation.NullDirection.LAST
        : RelFieldCollation.NullDirection.FIRST;
  case DESCENDING:
  case STRICTLY_DESCENDING:
    return getNullCollation().last(true)
        ? RelFieldCollation.NullDirection.LAST
        : RelFieldCollation.NullDirection.FIRST;
  default:
    return RelFieldCollation.NullDirection.UNSPECIFIED;
  }
}
 
Example 21
Source Project: dremio-oss   Source File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a collation to an ORDER BY item.
 */
public SqlNode toSql(RelFieldCollation collation) {
  SqlNode node = field(collation.getFieldIndex());
  switch (collation.getDirection()) {
    case DESCENDING:
    case STRICTLY_DESCENDING:
      node = SqlStdOperatorTable.DESC.createCall(POS, node);
  }
  if (collation.nullDirection != dialect.defaultNullDirection(collation.direction)) {
    switch (collation.nullDirection) {
      case FIRST:
        node = SqlStdOperatorTable.NULLS_FIRST.createCall(POS, node);
        break;
      case LAST:
        node = SqlStdOperatorTable.NULLS_LAST.createCall(POS, node);
        break;
    }
  }
  return node;
}
 
Example 22
Source Project: dremio-oss   Source File: RelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #dispatch
 */
public Result visit(Sort e) {
  Result x = visitChild(0, e.getInput());
  Builder builder = x.builder(e, Clause.ORDER_BY);
  List<SqlNode> orderByList = Expressions.list();
  for (RelFieldCollation field : e.getCollation().getFieldCollations()) {
    builder.addOrderItem(orderByList, field);
  }
  if (!orderByList.isEmpty()) {
    builder.setOrderBy(new SqlNodeList(orderByList, POS));
    x = builder.result();
  }
  if (e.fetch != null) {
    builder = x.builder(e, Clause.FETCH);
    builder.setFetch(builder.context.toSql(null, e.fetch));
    x = builder.result();
  }
  if (e.offset != null) {
    builder = x.builder(e, Clause.OFFSET);
    builder.setOffset(builder.context.toSql(null, e.offset));
    x = builder.result();
  }
  return x;
}
 
Example 23
Source Project: Bats   Source File: RelJson.java    License: Apache License 2.0 5 votes vote down vote up
public Object toJson(RelCollationImpl node) {
  final List<Object> list = new ArrayList<>();
  for (RelFieldCollation fieldCollation : node.getFieldCollations()) {
    final Map<String, Object> map = jsonBuilder.map();
    map.put("field", fieldCollation.getFieldIndex());
    map.put("direction", fieldCollation.getDirection().name());
    map.put("nulls", fieldCollation.nullDirection.name());
    list.add(map);
  }
  return list;
}
 
Example 24
Source Project: Bats   Source File: RelJson.java    License: Apache License 2.0 5 votes vote down vote up
public RelCollation toCollation(
    List<Map<String, Object>> jsonFieldCollations) {
  final List<RelFieldCollation> fieldCollations = new ArrayList<>();
  for (Map<String, Object> map : jsonFieldCollations) {
    fieldCollations.add(toFieldCollation(map));
  }
  return RelCollations.of(fieldCollations);
}
 
Example 25
Source Project: Bats   Source File: RelMdCollation.java    License: Apache License 2.0 5 votes vote down vote up
/** Helper method to determine a
 * {@link org.apache.calcite.rel.core.Values}'s collation.
 *
 * <p>We actually under-report the collations. A Values with 0 or 1 rows - an
 * edge case, but legitimate and very common - is ordered by every permutation
 * of every subset of the columns.
 *
 * <p>So, our algorithm aims to:<ul>
 *   <li>produce at most N collations (where N is the number of columns);
 *   <li>make each collation as long as possible;
 *   <li>do not repeat combinations already emitted -
 *       if we've emitted {@code (a, b)} do not later emit {@code (b, a)};
 *   <li>probe the actual values and make sure that each collation is
 *      consistent with the data
 * </ul>
 *
 * <p>So, for an empty Values with 4 columns, we would emit
 * {@code (a, b, c, d), (b, c, d), (c, d), (d)}. */
public static List<RelCollation> values(RelMetadataQuery mq,
    RelDataType rowType, ImmutableList<ImmutableList<RexLiteral>> tuples) {
  Util.discard(mq); // for future use
  final List<RelCollation> list = new ArrayList<>();
  final int n = rowType.getFieldCount();
  final List<Pair<RelFieldCollation, Ordering<List<RexLiteral>>>> pairs =
      new ArrayList<>();
outer:
  for (int i = 0; i < n; i++) {
    pairs.clear();
    for (int j = i; j < n; j++) {
      final RelFieldCollation fieldCollation = new RelFieldCollation(j);
      Ordering<List<RexLiteral>> comparator = comparator(fieldCollation);
      Ordering<List<RexLiteral>> ordering;
      if (pairs.isEmpty()) {
        ordering = comparator;
      } else {
        ordering = Util.last(pairs).right.compound(comparator);
      }
      pairs.add(Pair.of(fieldCollation, ordering));
      if (!ordering.isOrdered(tuples)) {
        if (j == i) {
          continue outer;
        }
        pairs.remove(pairs.size() - 1);
      }
    }
    if (!pairs.isEmpty()) {
      list.add(RelCollations.of(Pair.left(pairs)));
    }
  }
  return list;
}
 
Example 26
Source Project: calcite   Source File: SortRemoveConstantKeysRule.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Sort sort = call.rel(0);
  final RelMetadataQuery mq = call.getMetadataQuery();
  final RelNode input = sort.getInput();
  final RelOptPredicateList predicates = mq.getPulledUpPredicates(input);
  if (predicates == null) {
    return;
  }

  final RexBuilder rexBuilder = sort.getCluster().getRexBuilder();
  final List<RelFieldCollation> collationsList =
      sort.getCollation().getFieldCollations().stream()
          .filter(fc ->
              !predicates.constantMap.containsKey(
                  rexBuilder.makeInputRef(input, fc.getFieldIndex())))
          .collect(Collectors.toList());

  if (collationsList.size() == sort.collation.getFieldCollations().size()) {
    return;
  }

  // No active collations. Remove the sort completely
  if (collationsList.isEmpty() && sort.offset == null && sort.fetch == null) {
    call.transformTo(input);
    call.getPlanner().prune(sort);
    return;
  }

  final Sort result =
      sort.copy(sort.getTraitSet(), input, RelCollations.of(collationsList));
  call.transformTo(result);
  call.getPlanner().prune(sort);
}
 
Example 27
Source Project: Bats   Source File: Window.java    License: Apache License 2.0 5 votes vote down vote up
public static RelCollation getCollation(final List<RexFieldCollation> collations) {
    return RelCollations.of(new AbstractList<RelFieldCollation>() {
        @Override
        public RelFieldCollation get(int index) {
            final RexFieldCollation collation = collations.get(index);
            return new RelFieldCollation(((RexLocalRef) collation.left).getIndex(), collation.getDirection(),
                    collation.getNullDirection());
        }

        @Override
        public int size() {
            return collations.size();
        }
    });
}
 
Example 28
Source Project: calcite   Source File: RexUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies a mapping to a field collation.
 *
 * <p>If the field is not mapped, returns null.
 *
 * @param mapping        Mapping
 * @param fieldCollation Field collation
 * @return collation with mapping applied
 */
public static RelFieldCollation apply(
    Mappings.TargetMapping mapping,
    RelFieldCollation fieldCollation) {
  final int target =
      mapping.getTargetOpt(fieldCollation.getFieldIndex());
  if (target < 0) {
    return null;
  }
  return fieldCollation.withFieldIndex(target);
}
 
Example 29
Source Project: calcite   Source File: ElasticSearchAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testSort() {
  final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
      + "  ElasticsearchSort(sort0=[$4], dir0=[ASC])\n"
      + "    ElasticsearchProject(city=[CAST(ITEM($0, 'city')):VARCHAR(20)], longitude=[CAST(ITEM(ITEM($0, 'loc'), 0)):FLOAT], latitude=[CAST(ITEM(ITEM($0, 'loc'), 1)):FLOAT], pop=[CAST(ITEM($0, 'pop')):INTEGER], state=[CAST(ITEM($0, 'state')):VARCHAR(2)], id=[CAST(ITEM($0, 'id')):VARCHAR(5)])\n"
      + "      ElasticsearchTableScan(table=[[elastic, zips]])";

  calciteAssert()
      .query("select * from zips order by state")
      .returnsCount(ZIPS_SIZE)
      .returns(sortedResultSetChecker("state", RelFieldCollation.Direction.ASCENDING))
      .explainContains(explain);
}
 
Example 30
Source Project: Bats   Source File: RexFieldCollation.java    License: Apache License 2.0 5 votes vote down vote up
public RelFieldCollation.NullDirection getNullDirection() {
  return right.contains(SqlKind.NULLS_LAST)
      ? RelFieldCollation.NullDirection.LAST
      : right.contains(SqlKind.NULLS_FIRST)
          ? RelFieldCollation.NullDirection.FIRST
          : getDirection().defaultNullDirection();
}