Java Code Examples for org.apache.calcite.linq4j.tree.BlockBuilder#toBlock()

The following examples show how to use org.apache.calcite.linq4j.tree.BlockBuilder#toBlock() . 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: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void checkBlockBuilder(boolean optimizing, String expected) {
  BlockBuilder statements = new BlockBuilder(optimizing);
  Expression one =
      statements.append(
          "one", Expressions.constant(1));
  Expression two =
      statements.append(
          "two", Expressions.constant(2));
  Expression three =
      statements.append(
          "three", Expressions.add(one, two));
  Expression six =
      statements.append(
          "six",
          Expressions.multiply(three, two));
  Expression nine =
      statements.append(
          "nine",
          Expressions.multiply(three, three));
  Expression eighteen =
      statements.append(
          "eighteen",
          Expressions.add(
              Expressions.add(three, six),
              nine));
  statements.add(Expressions.return_(null, eighteen));
  BlockStatement expression = statements.toBlock();
  assertEquals(expected, Expressions.toString(expression));
  expression.accept(new Shuttle());
}
 
Example 2
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testBlockBuilder2() {
  BlockBuilder statements = new BlockBuilder();
  Expression element =
      statements.append(
          "element", Expressions.constant(null));
  Expression comparator =
      statements.append(
          "comparator", Expressions.constant(null, Comparator.class));
  Expression treeSet =
      statements.append(
          "treeSet",
          Expressions.new_(
              TreeSet.class,
              Arrays.asList(comparator)));
  statements.add(
      Expressions.return_(
          null,
          Expressions.call(
              treeSet,
              "add",
              element)));
  BlockStatement expression = statements.toBlock();
  final String expected = "{\n"
      + "  final java.util.TreeSet treeSet = new java.util.TreeSet(\n"
      + "    (java.util.Comparator) null);\n"
      + "  return treeSet.add(null);\n"
      + "}\n";
  assertThat(Expressions.toString(expression), is(expected));
  expression.accept(new Shuttle());
}
 
Example 3
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Expression implementResult(AggContext info,
    AggResultContext result) {
  WinAggResultContext winResult = (WinAggResultContext) result;

  List<RexNode> rexArgs = winResult.rexArguments();

  ParameterExpression res = Expressions.parameter(0, info.returnType(),
      result.currentBlock().newName("nth"));

  RexToLixTranslator currentRowTranslator =
      winResult.rowTranslator(
          winResult.computeIndex(Expressions.constant(0), SeekType.START));

  Expression dstIndex = winResult.computeIndex(
      Expressions.subtract(
          currentRowTranslator.translate(rexArgs.get(1), int.class),
          Expressions.constant(1)), SeekType.START);

  Expression rowInRange = winResult.rowInPartition(dstIndex);

  BlockBuilder thenBlock = result.nestBlock();
  Expression nthValue = winResult.rowTranslator(dstIndex)
      .translate(rexArgs.get(0), res.type);
  thenBlock.add(Expressions.statement(Expressions.assign(res, nthValue)));
  result.exitBlock();
  BlockStatement thenBranch = thenBlock.toBlock();

  Expression defaultValue = getDefaultValue(res.type);

  result.currentBlock().add(Expressions.declare(0, res, null));
  result.currentBlock().add(
      Expressions.ifThenElse(rowInRange, thenBranch,
          Expressions.statement(Expressions.assign(res, defaultValue))));
  return res;
}
 
Example 4
Source File: StrictAggImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
public final Expression implementResult(AggContext info,
    final AggResultContext result) {
  if (!needTrackEmptySet) {
    return EnumUtils.convert(
        implementNotNullResult(info, result), info.returnType());
  }
  String tmpName = result.accumulator().isEmpty()
      ? "ar"
      : (result.accumulator().get(0) + "$Res");
  ParameterExpression res = Expressions.parameter(0, info.returnType(),
      result.currentBlock().newName(tmpName));

  List<Expression> acc = result.accumulator();
  final BlockBuilder thenBlock = result.nestBlock();
  Expression nonNull = EnumUtils.convert(
      implementNotNullResult(info, result), info.returnType());
  result.exitBlock();
  thenBlock.add(Expressions.statement(Expressions.assign(res, nonNull)));
  BlockStatement thenBranch = thenBlock.toBlock();
  Expression seenNotNullRows =
      trackNullsPerRow
      ? acc.get(acc.size() - 1)
      : ((WinAggResultContext) result).hasRows();

  if (thenBranch.statements.size() == 1) {
    return Expressions.condition(seenNotNullRows,
        nonNull, RexImpTable.getDefaultValue(res.getType()));
  }
  result.currentBlock().add(Expressions.declare(0, res, null));
  result.currentBlock().add(
      Expressions.ifThenElse(seenNotNullRows,
          thenBranch,
          Expressions.statement(
              Expressions.assign(res,
                  RexImpTable.getDefaultValue(res.getType())))));
  return res;
}
 
Example 5
Source File: SparkRules.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Result implementSpark(Implementor implementor) {
  final JavaTypeFactory typeFactory = implementor.getTypeFactory();
  final BlockBuilder builder = new BlockBuilder();
  final SparkRel child = (SparkRel) getInput();

  final Result result = implementor.visitInput(this, 0, child);

  final PhysType physType =
      PhysTypeImpl.of(
          typeFactory, getRowType(), JavaRowFormat.CUSTOM);

  // final RDD<Employee> inputRdd = <<child adapter>>;
  // return inputRdd.flatMap(
  //   new FlatMapFunction<Employee, X>() {
  //          public List<X> call(Employee e) {
  //              if (!(e.empno < 10)) {
  //                  return Collections.emptyList();
  //              }
  //              return Collections.singletonList(
  //                  new X(...)));
  //          }
  //      })


  Type outputJavaType = physType.getJavaRowType();
  final Type rddType =
      Types.of(
          JavaRDD.class, outputJavaType);
  Type inputJavaType = result.physType.getJavaRowType();
  final Expression inputRdd_ =
      builder.append(
          "inputRdd",
          result.block);

  BlockBuilder builder2 = new BlockBuilder();

  final ParameterExpression e_ =
      Expressions.parameter(inputJavaType, "e");
  if (program.getCondition() != null) {
    Expression condition =
        RexToLixTranslator.translateCondition(
            program,
            typeFactory,
            builder2,
            new RexToLixTranslator.InputGetterImpl(
                Collections.singletonList(
                    Pair.of((Expression) e_, result.physType))),
            null, implementor.getConformance());
    builder2.add(
        Expressions.ifThen(
            Expressions.not(condition),
            Expressions.return_(null,
                Expressions.call(
                    BuiltInMethod.COLLECTIONS_EMPTY_LIST.method))));
  }

  final SqlConformance conformance = SqlConformanceEnum.DEFAULT;
  List<Expression> expressions =
      RexToLixTranslator.translateProjects(
          program,
          typeFactory,
          conformance,
          builder2,
          null,
          DataContext.ROOT,
          new RexToLixTranslator.InputGetterImpl(
              Collections.singletonList(
                  Pair.of((Expression) e_, result.physType))),
          null);
  builder2.add(
      Expressions.return_(null,
          Expressions.convert_(
              Expressions.call(
                  BuiltInMethod.COLLECTIONS_SINGLETON_LIST.method,
                  physType.record(expressions)),
              List.class)));

  final BlockStatement callBody = builder2.toBlock();
  builder.add(
      Expressions.return_(
          null,
          Expressions.call(
              inputRdd_,
              SparkMethod.RDD_FLAT_MAP.method,
              Expressions.lambda(
                  SparkRuntime.CalciteFlatMapFunction.class,
                  callBody,
                  e_))));
  return implementor.result(physType, builder.toBlock());
}
 
Example 6
Source File: ExpressionTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testBlockBuilder3() {
/*
    int a = 1;
    int b = a + 2;
    int c = a + 3;
    int d = a + 4;
    int e = {
      int b = a + 3;
      foo(b);
    }
    bar(a, b, c, d, e);
*/
    BlockBuilder builder0 = new BlockBuilder();
    final Expression a = builder0.append("_a", Expressions.constant(1));
    final Expression b =
        builder0.append("_b", Expressions.add(a, Expressions.constant(2)));
    final Expression c =
        builder0.append("_c", Expressions.add(a, Expressions.constant(3)));
    final Expression d =
        builder0.append("_d", Expressions.add(a, Expressions.constant(4)));

    BlockBuilder builder1 = new BlockBuilder();
    final Expression b1 =
        builder1.append("_b", Expressions.add(a, Expressions.constant(3)));
    builder1.add(
        Expressions.statement(
            Expressions.call(ExpressionTest.class, "foo", b1)));
    final Expression e = builder0.append("e", builder1.toBlock());
    builder0.add(
        Expressions.statement(
            Expressions.call(ExpressionTest.class, "bar", a, b, c, d, e)));
    // With the bug in BlockBuilder.append(String, BlockExpression),
    //    bar(1, _b, _c, _d, foo(_d));
    // Correct result is
    //    bar(1, _b, _c, _d, foo(_c));
    // because _c has the same expression (a + 3) as inner b.
    BlockStatement expression = builder0.toBlock();
    assertEquals(
        "{\n"
            + "  final int _b = 1 + 2;\n"
            + "  final int _c = 1 + 3;\n"
            + "  final int _d = 1 + 4;\n"
            + "  final int _b0 = 1 + 3;\n"
            + "  org.apache.calcite.linq4j.test.ExpressionTest.bar(1, _b, _c, _d, org.apache.calcite.linq4j.test.ExpressionTest.foo(_b0));\n"
            + "}\n",
        Expressions.toString(expression));
    expression.accept(new Shuttle());
  }
 
Example 7
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Case statements of the form:
 * {@code CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END}.
 * When {@code a = true}, returns {@code b};
 * when {@code c = true}, returns {@code d};
 * else returns {@code e}.
 *
 * <p>We generate code that looks like:
 *
 * <blockquote><pre>
 *      int case_when_value;
 *      ......code for a......
 *      if (!a_isNull && a_value) {
 *          ......code for b......
 *          case_when_value = res(b_isNull, b_value);
 *      } else {
 *          ......code for c......
 *          if (!c_isNull && c_value) {
 *              ......code for d......
 *              case_when_value = res(d_isNull, d_value);
 *          } else {
 *              ......code for e......
 *              case_when_value = res(e_isNull, e_value);
 *          }
 *      }
 * </pre></blockquote>
 */
private void implementRecursively(final RexToLixTranslator currentTranslator,
    final List<RexNode> operandList, final ParameterExpression valueVariable, int pos) {
  final BlockBuilder currentBlockBuilder = currentTranslator.getBlockBuilder();
  final List<Type> storageTypes = EnumUtils.internalTypes(operandList);
  // [ELSE] clause
  if (pos == operandList.size() - 1) {
    Expression res = implementCallOperand2(operandList.get(pos),
        storageTypes.get(pos), currentTranslator);
    currentBlockBuilder.add(
        Expressions.statement(
            Expressions.assign(valueVariable,
                EnumUtils.convert(res, valueVariable.getType()))));
    return;
  }
  // Condition code: !a_isNull && a_value
  final RexNode testerNode = operandList.get(pos);
  final Result testerResult = implementCallOperand(testerNode,
      storageTypes.get(pos), currentTranslator);
  final Expression tester = Expressions.andAlso(
      Expressions.not(testerResult.isNullVariable),
      testerResult.valueVariable);
  // Code for {if} branch
  final RexNode ifTrueNode = operandList.get(pos + 1);
  final BlockBuilder ifTrueBlockBuilder =
      new BlockBuilder(true, currentBlockBuilder);
  final RexToLixTranslator ifTrueTranslator =
      currentTranslator.setBlock(ifTrueBlockBuilder);
  final Expression ifTrueRes = implementCallOperand2(ifTrueNode,
      storageTypes.get(pos + 1), ifTrueTranslator);
  // Assign the value: case_when_value = ifTrueRes
  ifTrueBlockBuilder.add(
      Expressions.statement(
          Expressions.assign(valueVariable,
              EnumUtils.convert(ifTrueRes, valueVariable.getType()))));
  final BlockStatement ifTrue = ifTrueBlockBuilder.toBlock();
  // There is no [ELSE] clause
  if (pos + 1 == operandList.size() - 1) {
    currentBlockBuilder.add(
        Expressions.ifThen(tester, ifTrue));
    return;
  }
  // Generate code for {else} branch recursively
  final BlockBuilder ifFalseBlockBuilder =
      new BlockBuilder(true, currentBlockBuilder);
  final RexToLixTranslator ifFalseTranslator =
      currentTranslator.setBlock(ifFalseBlockBuilder);
  implementRecursively(ifFalseTranslator, operandList, valueVariable, pos + 2);
  final BlockStatement ifFalse = ifFalseBlockBuilder.toBlock();
  currentBlockBuilder.add(
      Expressions.ifThenElse(tester, ifTrue, ifFalse));
}
 
Example 8
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Expression implementResult(AggContext info,
    AggResultContext result) {
  WinAggResultContext winResult = (WinAggResultContext) result;

  List<RexNode> rexArgs = winResult.rexArguments();

  ParameterExpression res = Expressions.parameter(0, info.returnType(),
      result.currentBlock().newName(isLead ? "lead" : "lag"));

  Expression offset;
  RexToLixTranslator currentRowTranslator =
      winResult.rowTranslator(
          winResult.computeIndex(Expressions.constant(0), SeekType.SET));
  if (rexArgs.size() >= 2) {
    // lead(x, offset) or lead(x, offset, default)
    offset = currentRowTranslator.translate(
        rexArgs.get(1), int.class);
  } else {
    offset = Expressions.constant(1);
  }
  if (!isLead) {
    offset = Expressions.negate(offset);
  }
  Expression dstIndex = winResult.computeIndex(offset, SeekType.SET);

  Expression rowInRange = winResult.rowInPartition(dstIndex);

  BlockBuilder thenBlock = result.nestBlock();
  Expression lagResult = winResult.rowTranslator(dstIndex).translate(
      rexArgs.get(0), res.type);
  thenBlock.add(Expressions.statement(Expressions.assign(res, lagResult)));
  result.exitBlock();
  BlockStatement thenBranch = thenBlock.toBlock();

  Expression defaultValue = rexArgs.size() == 3
      ? currentRowTranslator.translate(rexArgs.get(2), res.type)
      : getDefaultValue(res.type);

  result.currentBlock().add(Expressions.declare(0, res, null));
  result.currentBlock().add(
      Expressions.ifThenElse(rowInRange, thenBranch,
          Expressions.statement(Expressions.assign(res, defaultValue))));
  return res;
}