Java Code Examples for org.apache.calcite.tools.RelBuilder#getRexBuilder()

The following examples show how to use org.apache.calcite.tools.RelBuilder#getRexBuilder() . 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 File: RelOptUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Deprecated // to be removed before 2.0
public static RelNode createProjectJoinRel(List<Integer> outputProj, RelNode joinRel) {
    int newProjectOutputSize = outputProj.size();
    List<RelDataTypeField> joinOutputFields = joinRel.getRowType().getFieldList();

    // If no projection was passed in, or the number of desired projection
    // columns is the same as the number of columns returned from the
    // join, then no need to create a projection
    if ((newProjectOutputSize > 0) && (newProjectOutputSize < joinOutputFields.size())) {
        final List<Pair<RexNode, String>> newProjects = new ArrayList<>();
        final RelBuilder relBuilder = RelFactories.LOGICAL_BUILDER.create(joinRel.getCluster(), null);
        final RexBuilder rexBuilder = relBuilder.getRexBuilder();
        for (int fieldIndex : outputProj) {
            final RelDataTypeField field = joinOutputFields.get(fieldIndex);
            newProjects.add(Pair.of(rexBuilder.makeInputRef(field.getType(), fieldIndex), field.getName()));
        }

        // Create a project rel on the output of the join.
        return relBuilder.push(joinRel).project(Pair.left(newProjects), Pair.right(newProjects), true).build();
    }

    return joinRel;
}
 
Example 2
Source File: AggregateValuesRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Aggregate aggregate = call.rel(0);
  final Values values = call.rel(1);
  Util.discard(values);
  final RelBuilder relBuilder = call.builder();
  final RexBuilder rexBuilder = relBuilder.getRexBuilder();

  final List<RexLiteral> literals = new ArrayList<>();
  for (final AggregateCall aggregateCall : aggregate.getAggCallList()) {
    switch (aggregateCall.getAggregation().getKind()) {
    case COUNT:
    case SUM0:
      literals.add((RexLiteral) rexBuilder.makeLiteral(
          BigDecimal.ZERO, aggregateCall.getType(), false));
      break;

    case MIN:
    case MAX:
    case SUM:
      literals.add((RexLiteral) rexBuilder.makeCast(
          aggregateCall.getType(), rexBuilder.constantNull()));
      break;

    default:
      // Unknown what this aggregate call should do on empty Values. Bail out to be safe.
      return;
    }
  }

  call.transformTo(
      relBuilder.values(ImmutableList.of(literals), aggregate.getRowType())
          .build());

  // New plan is absolutely better than old plan.
  call.getPlanner().setImportance(aggregate, 0.0);
}
 
Example 3
Source File: AggregateValuesRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Aggregate aggregate = call.rel(0);
  final Values values = call.rel(1);
  Util.discard(values);
  final RelBuilder relBuilder = call.builder();
  final RexBuilder rexBuilder = relBuilder.getRexBuilder();

  final List<RexLiteral> literals = new ArrayList<>();
  for (final AggregateCall aggregateCall : aggregate.getAggCallList()) {
    switch (aggregateCall.getAggregation().getKind()) {
    case COUNT:
    case SUM0:
      literals.add(
          (RexLiteral) rexBuilder.makeLiteral(
              BigDecimal.ZERO, aggregateCall.getType(), false));
      break;

    case MIN:
    case MAX:
    case SUM:
      literals.add(rexBuilder.makeNullLiteral(aggregateCall.getType()));
      break;

    default:
      // Unknown what this aggregate call should do on empty Values. Bail out to be safe.
      return;
    }
  }

  call.transformTo(
      relBuilder.values(ImmutableList.of(literals), aggregate.getRowType())
          .build());

  // New plan is absolutely better than old plan.
  call.getPlanner().prune(aggregate);
}
 
Example 4
Source File: RelOptUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static RelNode createProjectJoinRel(
    List<Integer> outputProj,
    RelNode joinRel) {
  int newProjectOutputSize = outputProj.size();
  List<RelDataTypeField> joinOutputFields =
      joinRel.getRowType().getFieldList();

  // If no projection was passed in, or the number of desired projection
  // columns is the same as the number of columns returned from the
  // join, then no need to create a projection
  if ((newProjectOutputSize > 0)
      && (newProjectOutputSize < joinOutputFields.size())) {
    final List<Pair<RexNode, String>> newProjects = new ArrayList<>();
    final RelBuilder relBuilder =
        RelFactories.LOGICAL_BUILDER.create(joinRel.getCluster(), null);
    final RexBuilder rexBuilder = relBuilder.getRexBuilder();
    for (int fieldIndex : outputProj) {
      final RelDataTypeField field = joinOutputFields.get(fieldIndex);
      newProjects.add(
          Pair.of(
              rexBuilder.makeInputRef(field.getType(), fieldIndex),
              field.getName()));
    }

    // Create a project rel on the output of the join.
    return relBuilder.push(joinRel)
        .project(Pair.left(newProjects), Pair.right(newProjects), true)
        .build();
  }

  return joinRel;
}
 
Example 5
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void project1(int value, SqlTypeName sqlTypeName, String message, String expected) {
  final RelBuilder builder = RelBuilder.create(config().build());
  RexBuilder rex = builder.getRexBuilder();
  RelNode actual =
      builder.values(new String[]{"x"}, 42)
          .empty()
          .project(
              rex.makeLiteral(value,
                  rex.getTypeFactory().createSqlType(sqlTypeName), false))
          .build();
  assertThat(message, actual, hasTree(expected));
}
 
Example 6
Source File: RelWriterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testCalc() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RexBuilder rexBuilder = builder.getRexBuilder();
  final LogicalTableScan scan = (LogicalTableScan) builder.scan("EMP").build();
  final RexProgramBuilder programBuilder =
      new RexProgramBuilder(scan.getRowType(), rexBuilder);
  final RelDataTypeField field = scan.getRowType().getField("SAL", false, false);
  programBuilder.addIdentity();
  programBuilder.addCondition(
      rexBuilder.makeCall(SqlStdOperatorTable.GREATER_THAN,
          new RexInputRef(field.getIndex(), field.getType()),
          builder.literal(10)));
  final LogicalCalc calc = LogicalCalc.create(scan, programBuilder.getProgram());
  String relJson = RelOptUtil.dumpPlan("", calc,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        final RelJsonReader reader = new RelJsonReader(
            cluster, getSchema(calc), rootSchema);
        RelNode node;
        try {
          node = reader.read(relJson);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });
  final String expected =
      "LogicalCalc(expr#0..7=[{inputs}], expr#8=[10], expr#9=[>($t5, $t8)],"
          + " proj#0..7=[{exprs}], $condition=[$t9])\n"
          + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 7
Source File: RelWriterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Mock a {@link RelNode} for sql:
 * select count(*) over (partition by {@code partitionKeyNames}
 * order by {@code orderKeyNames}) from {@code table}
 * @param table Table name
 * @param partitionKeyNames Partition by column names, may empty, can not be null
 * @param orderKeyNames Order by column names, may empty, can not be null
 * @return RelNode for the sql
 */
private RelNode mockCountOver(String table,
    List<String> partitionKeyNames, List<String> orderKeyNames) {

  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RexBuilder rexBuilder = builder.getRexBuilder();
  final RelDataType type = rexBuilder.getTypeFactory().createSqlType(SqlTypeName.BIGINT);
  List<RexNode> partitionKeys = new ArrayList<>(partitionKeyNames.size());
  builder.scan(table);
  for (String partitionkeyName: partitionKeyNames) {
    partitionKeys.add(builder.field(partitionkeyName));
  }
  List<RexFieldCollation> orderKeys = new ArrayList<>(orderKeyNames.size());
  for (String orderKeyName: orderKeyNames) {
    orderKeys.add(new RexFieldCollation(builder.field(orderKeyName), ImmutableSet.of()));
  }
  final RelNode rel = builder
      .project(
          rexBuilder.makeOver(
              type,
              SqlStdOperatorTable.COUNT,
              ImmutableList.of(),
              partitionKeys,
              ImmutableList.copyOf(orderKeys),
              RexWindowBounds.UNBOUNDED_PRECEDING,
              RexWindowBounds.CURRENT_ROW,
              true, true, false, false, false))
      .build();
  return rel;
}
 
Example 8
Source File: AggregateRemoveRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Aggregate aggregate = call.rel(0);
  final RelNode input = aggregate.getInput();
  final RelMetadataQuery mq = call.getMetadataQuery();
  if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) {
    return;
  }

  final RelBuilder relBuilder = call.builder();
  final RexBuilder rexBuilder = relBuilder.getRexBuilder();
  final List<RexNode> projects = new ArrayList<>();
  for (AggregateCall aggCall : aggregate.getAggCallList()) {
    final SqlAggFunction aggregation = aggCall.getAggregation();
    if (aggregation.getKind() == SqlKind.SUM0) {
      // Bail out for SUM0 to avoid potential infinite rule matching,
      // because it may be generated by transforming SUM aggregate
      // function to SUM0 and COUNT.
      return;
    }
    final SqlSplittableAggFunction splitter =
        Objects.requireNonNull(
            aggregation.unwrap(SqlSplittableAggFunction.class));
    final RexNode singleton = splitter.singleton(
        rexBuilder, input.getRowType(), aggCall);
    projects.add(singleton);
  }

  final RelNode newInput = convert(input, aggregate.getTraitSet().simplify());
  relBuilder.push(newInput);
  if (!projects.isEmpty()) {
    projects.addAll(0, relBuilder.fields(aggregate.getGroupSet()));
    relBuilder.project(projects);
  } else if (newInput.getRowType().getFieldCount()
      > aggregate.getRowType().getFieldCount()) {
    // If aggregate was projecting a subset of columns, and there were no
    // aggregate functions, add a project for the same effect.
    relBuilder.project(relBuilder.fields(aggregate.getGroupSet()));
  }
  call.getPlanner().prune(aggregate);
  call.transformTo(relBuilder.build());
}