org.apache.calcite.linq4j.tree.BlockBuilder Java Examples

The following examples show how to use org.apache.calcite.linq4j.tree.BlockBuilder. 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: SparkToEnumerableConverter.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  // Generate:
  //   RDD rdd = ...;
  //   return SparkRuntime.asEnumerable(rdd);
  final BlockBuilder list = new BlockBuilder();
  final SparkRel child = (SparkRel) getInput();
  final PhysType physType =
      PhysTypeImpl.of(implementor.getTypeFactory(),
          getRowType(),
          JavaRowFormat.CUSTOM);
  SparkRel.Implementor sparkImplementor =
      new SparkImplementorImpl(implementor);
  final SparkRel.Result result = child.implementSpark(sparkImplementor);
  final Expression rdd = list.append("rdd", result.block);
  final Expression enumerable =
      list.append(
          "enumerable",
          Expressions.call(
              SparkMethod.AS_ENUMERABLE.method,
              rdd));
  list.add(
      Expressions.return_(null, enumerable));
  return implementor.result(physType, list.toBlock());
}
 
Example #2
Source File: EnumerableMatch.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public Expression field(BlockBuilder list, int index,
    Type storageType) {
  if (this.index == null) {
    return generator.apply(this.row).field(list, index, storageType);
  }

  return Expressions.condition(
      Expressions.greaterThanOrEqual(this.index, Expressions.constant(0)),
      generator.apply(
          EnumUtils.convert(
              Expressions.call(this.passedRows,
                  BuiltInMethod.LIST_GET.method, this.index),
              physType.getJavaRowType()))
          .field(list, index, storageType),
      Expressions.constant(null));
}
 
Example #3
Source File: EnumerableWindow.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Pair<Expression, Expression> getRowCollationKey(
    BlockBuilder builder, PhysType inputPhysType,
    Group group, int windowIdx) {
  if (!(group.isRows
      || (group.upperBound.isUnbounded() && group.lowerBound.isUnbounded()))) {
    Pair<Expression, Expression> pair =
        inputPhysType.generateCollationKey(
            group.collation().getFieldCollations());
    // optimize=false to prevent inlining of object create into for-loops
    return Pair.of(
        builder.append("keySelector" + windowIdx, pair.left, false),
        builder.append("keyComparator" + windowIdx, pair.right, false));
  } else {
    return Pair.of(null, null);
  }
}
 
Example #4
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Translates a {@link RexProgram} to a sequence of expressions and
 * declarations.
 *
 * @param program Program to be translated
 * @param typeFactory Type factory
 * @param conformance SQL conformance
 * @param list List of statements, populated with declarations
 * @param outputPhysType Output type, or null
 * @param root Root expression
 * @param inputGetter Generates expressions for inputs
 * @param correlates Provider of references to the values of correlated
 *                   variables
 * @return Sequence of expressions, optional condition
 */
public static List<Expression> translateProjects(RexProgram program,
    JavaTypeFactory typeFactory, SqlConformance conformance,
    BlockBuilder list, PhysType outputPhysType, Expression root,
    InputGetter inputGetter, Function1<String, InputGetter> correlates) {
  List<Type> storageTypes = null;
  if (outputPhysType != null) {
    final RelDataType rowType = outputPhysType.getRowType();
    storageTypes = new ArrayList<>(rowType.getFieldCount());
    for (int i = 0; i < rowType.getFieldCount(); i++) {
      storageTypes.add(outputPhysType.getJavaFieldType(i));
    }
  }
  return new RexToLixTranslator(program, typeFactory, root, inputGetter,
      list, new RexBuilder(typeFactory), conformance, null)
      .setCorrelates(correlates)
      .translateList(program.getProjectList(), storageTypes);
}
 
Example #5
Source File: ExpressionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testForEach() {
  final BlockBuilder builder = new BlockBuilder();
  final ParameterExpression i_ = Expressions.parameter(int.class, "i");
  final ParameterExpression list_ = Expressions.parameter(List.class, "list");
  builder.add(
      Expressions.forEach(i_, list_,
          Expressions.ifThen(
              Expressions.lessThan(
                  Expressions.constant(1),
                  Expressions.constant(2)),
              Expressions.break_(null))));
  assertThat(Expressions.toString(builder.toBlock()),
      is("{\n"
          + "  for (int i : list) {\n"
          + "    if (1 < 2) {\n"
          + "      break;\n"
          + "    }\n"
          + "  }\n"
          + "}\n"));
}
 
Example #6
Source File: InlinerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testInlineInTryCatchStatement() {
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression t = Expressions.parameter(int.class, "t");
  builder.add(Expressions.declare(Modifier.FINAL, t, ONE));
  final ParameterExpression u = Expressions.parameter(int.class, "u");
  builder.add(Expressions.declare(Modifier.FINAL, u, null));
  Statement st = Expressions.statement(
      Expressions.assign(u,
          Expressions.makeBinary(ExpressionType.Add, t, TWO)));
  ParameterExpression e = Expressions.parameter(0, Exception.class, "e");
  CatchBlock cb = Expressions.catch_(e, Expressions.throw_(e));
  builder.add(Expressions.tryCatch(st, cb));
  builder.add(Expressions.return_(null, u));
  assertEquals(
      "{\n"
          + "  final int u;\n"
          + "  try {\n"
          + "    u = 1 + 2;\n"
          + "  } catch (Exception e) {\n"
          + "    throw e;\n"
          + "  }\n"
          + "  return u;\n"
          + "}\n",
      builder.toBlock().toString());
}
 
Example #7
Source File: BlockBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTestCustomOptimizer() {
  BlockBuilder b = new BlockBuilder() {
    @Override protected Shuttle createOptimizeShuttle() {
      return new OptimizeShuttle() {
        @Override public Expression visit(BinaryExpression binary,
            Expression expression0, Expression expression1) {
          if (binary.getNodeType() == ExpressionType.Add
              && ONE.equals(expression0) && TWO.equals(expression1)) {
            return FOUR;
          }
          return super.visit(binary, expression0, expression1);
        }
      };
    }
  };
  b.add(Expressions.return_(null, Expressions.add(ONE, TWO)));
  assertEquals("{\n  return 4;\n}\n", b.toBlock().toString());
}
 
Example #8
Source File: InlinerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testMultiPassOptimization() {
  // int t = u + v;
  // boolean b = t > 1 ? true : true; -- optimized out, thus t can be inlined
  // return b ? t : 2
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression u = Expressions.parameter(int.class, "u");
  final ParameterExpression v = Expressions.parameter(int.class, "v");

  Expression t = builder.append("t", Expressions.add(u, v));
  Expression b = builder.append("b",
      Expressions.condition(Expressions.greaterThan(t, ONE), TRUE, TRUE));

  builder.add(Expressions.return_(null, Expressions.condition(b, t, TWO)));
  assertEquals(
      "{\n"
          + "  return u + v;\n"
          + "}\n",
      Expressions.toString(builder.toBlock()));
}
 
Example #9
Source File: RexImpTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void implementNotNullAdd(AggContext info, AggAddContext add) {
  BlockBuilder accumulatorIsNull = new BlockBuilder();
  accumulatorIsNull.add(
      Expressions.statement(
          Expressions.assign(add.accumulator().get(0), Expressions.new_(ArrayList.class))));
  accumulatorIsNull.add(
      Expressions.statement(
          Expressions.call(add.accumulator().get(0),
              BuiltInMethod.COLLECTION_ADDALL.method, add.arguments().get(0))));

  BlockBuilder accumulatorNotNull = new BlockBuilder();
  accumulatorNotNull.add(
      Expressions.statement(
          Expressions.call(add.accumulator().get(0),
              BuiltInMethod.COLLECTION_RETAIN_ALL.method,
              add.arguments().get(0))
      )
  );

  add.currentBlock().add(
      Expressions.ifThenElse(
          Expressions.equal(add.accumulator().get(0), Expressions.constant(null)),
          accumulatorIsNull.toBlock(),
          accumulatorNotNull.toBlock()));
}
 
Example #10
Source File: EnumerableMatch.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public Expression field(BlockBuilder list, int index,
    Type storageType) {
  final ParameterExpression row =
      Expressions.parameter(physType.getJavaRowType());
  final ParameterExpression tmp =
      Expressions.parameter(Object.class);
  list.add(
      Expressions.declare(0, tmp,
          Expressions.call(this.row, BuiltInMethod.MEMORY_GET1.method,
              offset)));
  list.add(
      Expressions.declare(0, row,
          Expressions.convert_(tmp, physType.getJavaRowType())));

  // Add return statement if here is a null!
  list.add(
      Expressions.ifThen(
          Expressions.equal(tmp, Expressions.constant(null)),
          Expressions.return_(null, Expressions.constant(false))));

  return generator.apply(row).field(list, index, storageType);
}
 
Example #11
Source File: EnumerableTableFunctionScan.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Result defaultTableFunctionImplement(
    EnumerableRelImplementor implementor, Prefer pref) {
  BlockBuilder bb = new BlockBuilder();
  // Non-array user-specified types are not supported yet
  final JavaRowFormat format;
  if (getElementType() == null) {
    format = JavaRowFormat.ARRAY;
  } else if (rowType.getFieldCount() == 1 && isQueryable()) {
    format = JavaRowFormat.SCALAR;
  } else if (getElementType() instanceof Class
      && Object[].class.isAssignableFrom((Class) getElementType())) {
    format = JavaRowFormat.ARRAY;
  } else {
    format = JavaRowFormat.CUSTOM;
  }
  final PhysType physType =
      PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
          false);
  RexToLixTranslator t = RexToLixTranslator.forAggregation(
      (JavaTypeFactory) getCluster().getTypeFactory(), bb, null,
      implementor.getConformance());
  t = t.setCorrelates(implementor.allCorrelateVariables);
  bb.add(Expressions.return_(null, t.translate(getCall())));
  return implementor.result(physType, bb.toBlock());
}
 
Example #12
Source File: InlinerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testAssignInConditionMultipleUsageNonOptimized() {
  // int t = 2;
  // return (t = 1) != a ? 1 : c
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression t = Expressions.parameter(int.class, "t");

  builder.add(Expressions.declare(0, t, TWO));

  Expression v = builder.append("v",
      Expressions.makeTernary(ExpressionType.Conditional,
          Expressions.makeBinary(ExpressionType.NotEqual,
              Expressions.assign(t, Expressions.constant(1)),
              Expressions.parameter(int.class, "a")),
          t,
          Expressions.parameter(int.class, "c")));
  builder.add(Expressions.return_(null, v));
  assertEquals(
      "{\n"
          + "  int t = 2;\n"
          + "  return (t = 1) != a ? t : c;\n"
          + "}\n",
      Expressions.toString(builder.toBlock()));
}
 
Example #13
Source File: InlinerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
void checkAssignInConditionOptimizedOut(int modifiers, String s) {
  // int t;
  // return (t = 1) != a ? b : c
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression t =
      Expressions.parameter(int.class, "t");

  builder.add(Expressions.declare(modifiers, t, null));

  Expression v = builder.append("v",
      Expressions.makeTernary(ExpressionType.Conditional,
          Expressions.makeBinary(ExpressionType.NotEqual,
              Expressions.assign(t, Expressions.constant(1)),
              Expressions.parameter(int.class, "a")),
          Expressions.parameter(int.class, "b"),
          Expressions.parameter(int.class, "c")));
  builder.add(Expressions.return_(null, v));
  assertThat(Expressions.toString(builder.toBlock()),
      CoreMatchers.equalTo(s));
}
 
Example #14
Source File: NestedBlockBuilderImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Uses given block as the new code context and the map of nullability.
 * The current block will be restored after {@link #exitBlock()} call.
 * @param block new code block
 * @param nullables map of expression to its nullability state
 * @see #exitBlock()
 */
public final void nestBlock(BlockBuilder block,
    Map<RexNode, Boolean> nullables) {
  blocks.add(block);
  Map<RexNode, Boolean> prev = this.nullables.isEmpty()
      ? Collections.emptyMap()
      : this.nullables.get(this.nullables.size() - 1);
  Map<RexNode, Boolean> next;
  if (nullables == null || nullables.isEmpty()) {
    next = prev;
  } else {
    next = new HashMap<>(nullables);
    next.putAll(prev);
    next = Collections.unmodifiableMap(next);
  }
  this.nullables.add(next);
}
 
Example #15
Source File: EnumerableInterpreter.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final JavaTypeFactory typeFactory = implementor.getTypeFactory();
  final BlockBuilder builder = new BlockBuilder();
  final PhysType physType =
      PhysTypeImpl.of(typeFactory, getRowType(), JavaRowFormat.ARRAY);
  final Expression interpreter_ = builder.append("interpreter",
      Expressions.new_(Interpreter.class,
          implementor.getRootExpression(),
          implementor.stash(getInput(), RelNode.class)));
  final Expression sliced_ =
      getRowType().getFieldCount() == 1
          ? Expressions.call(BuiltInMethod.SLICE0.method, interpreter_)
          : interpreter_;
  builder.add(sliced_);
  return implementor.result(physType, builder.toBlock());
}
 
Example #16
Source File: EnumerableTableFunctionScan.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Result tvfImplementorBasedImplement(
    EnumerableRelImplementor implementor, Prefer pref) {
  final JavaTypeFactory typeFactory = implementor.getTypeFactory();
  final BlockBuilder builder = new BlockBuilder();
  final EnumerableRel child = (EnumerableRel) getInputs().get(0);
  final Result result =
      implementor.visitChild(this, 0, child, pref);
  final PhysType physType = PhysTypeImpl.of(
      typeFactory, getRowType(), pref.prefer(result.format));
  final Expression inputEnumerable = builder.append(
      "_input", result.block, false);
  final SqlConformance conformance =
      (SqlConformance) implementor.map.getOrDefault("_conformance",
          SqlConformanceEnum.DEFAULT);

  builder.add(
      RexToLixTranslator.translateTableFunction(
          typeFactory,
          conformance,
          builder,
          DataContext.ROOT,
          (RexCall) getCall(),
          inputEnumerable,
          result.physType,
          physType
      )
  );

  return implementor.result(physType, builder.toBlock());
}
 
Example #17
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 #18
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Expression field(BlockBuilder list, int index, Type storageType) {
  int offset = 0;
  for (Pair<Expression, PhysType> input : inputs) {
    final PhysType physType = input.right;
    int fieldCount = physType.getRowType().getFieldCount();
    if (index >= offset + fieldCount) {
      offset += fieldCount;
      continue;
    }
    final Expression left = list.append("current", input.left);
    return physType.fieldReference(left, index - offset, storageType);
  }
  throw new IllegalArgumentException("Unable to find field #" + index);
}
 
Example #19
Source File: EnumerableCollect.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final BlockBuilder builder = new BlockBuilder();
  final EnumerableRel child = (EnumerableRel) getInput();
  // REVIEW zabetak January 7, 2019: Even if we ask the implementor to provide a result
  // where records are represented as arrays (Prefer.ARRAY) this may not be respected.
  final Result result = implementor.visitChild(this, 0, child, Prefer.ARRAY);
  final PhysType physType =
      PhysTypeImpl.of(
          implementor.getTypeFactory(),
          getRowType(),
          JavaRowFormat.LIST);

  // final Enumerable child = <<child adapter>>;
  // final Enumerable<Object[]> converted = child.select(<<conversion code>>);
  // final List<Object[]> list = converted.toList();
  Expression child_ =
      builder.append(
          "child", result.block);
  // In the internal representation of multisets , every element must be a record. In case the
  // result above is a scalar type we have to wrap it around a physical type capable of
  // representing records. For this reason the following conversion is necessary.
  // REVIEW zabetak January 7, 2019: If we can ensure that the input to this operator
  // has the correct physical type (e.g., respecting the Prefer.ARRAY above) then this conversion
  // can be removed.
  Expression conv_ =
      builder.append(
          "converted", result.physType.convertTo(child_, JavaRowFormat.ARRAY));
  Expression list_ =
      builder.append("list",
          Expressions.call(conv_,
              BuiltInMethod.ENUMERABLE_TO_LIST.method));

  builder.add(
      Expressions.return_(null,
          Expressions.call(
              BuiltInMethod.SINGLETON_ENUMERABLE.method, list_)));
  return implementor.result(physType, builder.toBlock());
}
 
Example #20
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static Expression translateTableFunction(JavaTypeFactory typeFactory,
    SqlConformance conformance, BlockBuilder blockBuilder,
    Expression root, RexCall rexCall, Expression inputEnumerable,
    PhysType inputPhysType, PhysType outputPhysType) {
  return new RexToLixTranslator(null, typeFactory, root, null,
      blockBuilder, new RexBuilder(typeFactory), conformance, null)
      .translateTableFunction(rexCall, inputEnumerable, inputPhysType, outputPhysType);
}
 
Example #21
Source File: EnumerableRelImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void registerCorrelVariable(final String name,
    final ParameterExpression pe,
    final BlockBuilder corrBlock, final PhysType physType) {
  corrVars.put(name, (list, index, storageType) -> {
    Expression fieldReference =
        physType.fieldReference(pe, index, storageType);
    return corrBlock.append(name + "_" + index, fieldReference);
  });
}
 
Example #22
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 #23
Source File: EnumerableLimit.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final BlockBuilder builder = new BlockBuilder();
  final EnumerableRel child = (EnumerableRel) getInput();
  final Result result = implementor.visitChild(this, 0, child, pref);
  final PhysType physType =
      PhysTypeImpl.of(
          implementor.getTypeFactory(),
          getRowType(),
          result.format);

  Expression v = builder.append("child", result.block);
  if (offset != null) {
    v = builder.append(
        "offset",
        Expressions.call(
            v,
            BuiltInMethod.SKIP.method,
            getExpression(offset)));
  }
  if (fetch != null) {
    v = builder.append(
        "fetch",
        Expressions.call(
            v,
            BuiltInMethod.TAKE.method,
            getExpression(fetch)));
  }

  builder.add(
      Expressions.return_(
          null,
          v));
  return implementor.result(physType, builder.toBlock());
}
 
Example #24
Source File: WinAggResultContextImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("Guava")
@Deprecated // to be removed before 2.0
public WinAggResultContextImpl(BlockBuilder block,
    List<Expression> accumulator,
    com.google.common.base.Function<BlockBuilder, WinAggFrameResultContext> frameContextBuilder) {
  this(block, accumulator,
      (Function<BlockBuilder, WinAggFrameResultContext>) frameContextBuilder::apply);
}
 
Example #25
Source File: EnumerableSort.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final BlockBuilder builder = new BlockBuilder();
  final EnumerableRel child = (EnumerableRel) getInput();
  final Result result = implementor.visitChild(this, 0, child, pref);
  final PhysType physType =
      PhysTypeImpl.of(
          implementor.getTypeFactory(),
          getRowType(),
          result.format);
  Expression childExp =
      builder.append("child", result.block);

  PhysType inputPhysType = result.physType;
  final Pair<Expression, Expression> pair =
      inputPhysType.generateCollationKey(
          collation.getFieldCollations());

  builder.add(
      Expressions.return_(null,
          Expressions.call(childExp,
              BuiltInMethod.ORDER_BY.method,
              Expressions.list(
                  builder.append("keySelector", pair.left))
                  .appendIfNotNull(
                      builder.appendIfNotNull("comparator", pair.right)))));
  return implementor.result(physType, builder.toBlock());
}
 
Example #26
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RexToLixTranslator setBlock(BlockBuilder block) {
  if (block == list) {
    return this;
  }
  return new RexToLixTranslator(program, typeFactory, root, inputGetter,
      block, builder, conformance, correlates);
}
 
Example #27
Source File: EnumerableRepeatUnion.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

    // return repeatUnion(<seedExp>, <iterativeExp>, iterationLimit, all, <comparer>);

    BlockBuilder builder = new BlockBuilder();
    RelNode seed = getSeedRel();
    RelNode iteration = getIterativeRel();

    Result seedResult = implementor.visitChild(this, 0, (EnumerableRel) seed, pref);
    Result iterationResult = implementor.visitChild(this, 1, (EnumerableRel) iteration, pref);

    Expression seedExp = builder.append("seed", seedResult.block);
    Expression iterativeExp = builder.append("iteration", iterationResult.block);

    PhysType physType = PhysTypeImpl.of(
        implementor.getTypeFactory(),
        getRowType(),
        pref.prefer(seedResult.format));

    Expression unionExp = Expressions.call(
        BuiltInMethod.REPEAT_UNION.method,
        seedExp,
        iterativeExp,
        Expressions.constant(iterationLimit, int.class),
        Expressions.constant(all, boolean.class),
        Util.first(physType.comparer(), Expressions.call(BuiltInMethod.IDENTITY_COMPARER.method)));
    builder.add(unionExp);

    return implementor.result(physType, builder.toBlock());
  }
 
Example #28
Source File: EnumUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns a predicate expression based on a join condition. **/
static Expression generatePredicate(
    EnumerableRelImplementor implementor,
    RexBuilder rexBuilder,
    RelNode left,
    RelNode right,
    PhysType leftPhysType,
    PhysType rightPhysType,
    RexNode condition) {
  final BlockBuilder builder = new BlockBuilder();
  final ParameterExpression left_ =
      Expressions.parameter(leftPhysType.getJavaRowType(), "left");
  final ParameterExpression right_ =
      Expressions.parameter(rightPhysType.getJavaRowType(), "right");
  final RexProgramBuilder program =
      new RexProgramBuilder(
          implementor.getTypeFactory().builder()
              .addAll(left.getRowType().getFieldList())
              .addAll(right.getRowType().getFieldList())
              .build(),
          rexBuilder);
  program.addCondition(condition);
  builder.add(
      Expressions.return_(null,
          RexToLixTranslator.translateCondition(program.getProgram(),
              implementor.getTypeFactory(),
              builder,
              new RexToLixTranslator.InputGetterImpl(
                  ImmutableList.of(Pair.of(left_, leftPhysType),
                      Pair.of(right_, rightPhysType))),
              implementor.allCorrelateVariables,
              implementor.getConformance())));
  return Expressions.lambda(Predicate2.class, builder.toBlock(), left_, right_);
}
 
Example #29
Source File: EnumerableAggregateBase.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected void declareParentAccumulator(List<Expression> initExpressions,
    BlockBuilder initBlock, PhysType accPhysType) {
  if (accPhysType.getJavaRowType()
      instanceof JavaTypeFactoryImpl.SyntheticRecordType) {
    // We have to initialize the SyntheticRecordType instance this way, to
    // avoid using a class constructor with too many parameters.
    final JavaTypeFactoryImpl.SyntheticRecordType synType =
        (JavaTypeFactoryImpl.SyntheticRecordType)
            accPhysType.getJavaRowType();
    final ParameterExpression record0_ =
        Expressions.parameter(accPhysType.getJavaRowType(), "record0");
    initBlock.add(Expressions.declare(0, record0_, null));
    initBlock.add(
        Expressions.statement(
            Expressions.assign(record0_,
                Expressions.new_(accPhysType.getJavaRowType()))));
    List<Types.RecordField> fieldList = synType.getRecordFields();
    for (int i = 0; i < initExpressions.size(); i++) {
      Expression right = initExpressions.get(i);
      initBlock.add(
          Expressions.statement(
              Expressions.assign(
                  Expressions.field(record0_, fieldList.get(i)), right)));
    }
    initBlock.add(record0_);
  } else {
    initBlock.add(accPhysType.record(initExpressions));
  }
}
 
Example #30
Source File: EnumerableWindow.java    From calcite with Apache License 2.0 5 votes vote down vote up
private boolean implementResult(List<AggImpState> aggs,
    final BlockBuilder builder,
    final Function<BlockBuilder, WinAggFrameResultContext> frame,
    final Function<AggImpState, List<RexNode>> rexArguments,
    boolean cachedBlock) {
  boolean nonEmpty = false;
  for (final AggImpState agg : aggs) {
    boolean needCache = true;
    if (agg.implementor instanceof WinAggImplementor) {
      WinAggImplementor imp = (WinAggImplementor) agg.implementor;
      needCache = imp.needCacheWhenFrameIntact();
    }
    if (needCache ^ cachedBlock) {
      // Regular aggregates do not change when the windowing frame keeps
      // the same. Ths
      continue;
    }
    nonEmpty = true;
    Expression res = agg.implementor.implementResult(agg.context,
        new WinAggResultContextImpl(builder, agg.state, frame) {
          public List<RexNode> rexArguments() {
            return rexArguments.apply(agg);
          }
        });
    // Several count(a) and count(b) might share the result
    Expression aggRes = builder.append("a" + agg.aggIdx + "res",
        EnumUtils.convert(res, agg.result.getType()));
    builder.add(
        Expressions.statement(Expressions.assign(agg.result, aggRes)));
  }
  return nonEmpty;
}