org.apache.calcite.rex.RexBuilder Java Examples

The following examples show how to use org.apache.calcite.rex.RexBuilder. 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: RelDecorrelator.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RexNode createCaseExpression(RexInputRef nullInputRef, RexLiteral lit, RexNode rexNode) {
    RexNode[] caseOperands = new RexNode[3];

    // Construct a CASE expression to handle the null indicator.
    //
    // This also covers the case where a left correlated sub-query
    // projects fields from outer relation. Since LOJ cannot produce
    // nulls on the LHS, the projection now need to make a nullable LHS
    // reference using a nullability indicator. If this this indicator
    // is null, it means the sub-query does not produce any value. As a
    // result, any RHS ref by this usbquery needs to produce null value.

    // WHEN indicator IS NULL
    caseOperands[0] = rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, RexBuilder.getRexFactory().makeInputRef(
            nullInputRef.getIndex(), typeFactory.createTypeWithNullability(nullInputRef.getType(), true)));

    // THEN CAST(NULL AS newInputTypeNullable)
    caseOperands[1] = rexBuilder.makeCast(typeFactory.createTypeWithNullability(rexNode.getType(), true), lit);

    // ELSE cast (newInput AS newInputTypeNullable) END
    caseOperands[2] = rexBuilder.makeCast(typeFactory.createTypeWithNullability(rexNode.getType(), true),
            rexNode);

    return rexBuilder.makeCall(SqlStdOperatorTable.CASE, caseOperands);
}
 
Example #2
Source File: DrillJoinRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RexNode buildJoinCondition(RelNode convertedLeft, RelNode convertedRight, List<Integer> leftKeys,
    List<Integer> rightKeys, List<Boolean> filterNulls, RexBuilder builder) {
  List<RexNode> equijoinList = Lists.newArrayList();
  final int numLeftFields = convertedLeft.getRowType().getFieldCount();
  List<RelDataTypeField> leftTypes = convertedLeft.getRowType().getFieldList();
  List<RelDataTypeField> rightTypes = convertedRight.getRowType().getFieldList();

  for (int i=0; i < leftKeys.size(); i++) {
    int leftKeyOrdinal = leftKeys.get(i);
    int rightKeyOrdinal = rightKeys.get(i);

    equijoinList.add(builder.makeCall(
         filterNulls.get(i) ? SqlStdOperatorTable.EQUALS : SqlStdOperatorTable.IS_NOT_DISTINCT_FROM,
         builder.makeInputRef(leftTypes.get(leftKeyOrdinal).getType(), leftKeyOrdinal),
         builder.makeInputRef(rightTypes.get(rightKeyOrdinal).getType(), rightKeyOrdinal + numLeftFields)
    ));
  }
  return RexUtil.composeConjunction(builder, equijoinList, false);
}
 
Example #3
Source File: DateRangeRules.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RexLiteral dateTimeLiteral(RexBuilder rexBuilder, Calendar calendar, RexNode operand) {
    final TimestampString ts;
    final int p;
    switch (operand.getType().getSqlTypeName()) {
    case TIMESTAMP:
        ts = TimestampString.fromCalendarFields(calendar);
        p = operand.getType().getPrecision();
        return rexBuilder.makeTimestampLiteral(ts, p);
    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
        ts = TimestampString.fromCalendarFields(calendar);
        final TimeZone tz = TimeZone.getTimeZone(this.timeZone);
        final TimestampString localTs = new TimestampWithTimeZoneString(ts, tz)
                .withTimeZone(DateTimeUtils.UTC_ZONE).getLocalTimestampString();
        p = operand.getType().getPrecision();
        return rexBuilder.makeTimestampWithLocalTimeZoneLiteral(localTs, p);
    case DATE:
        final DateString d = DateString.fromCalendarFields(calendar);
        return rexBuilder.makeDateLiteral(d);
    default:
        throw Util.unexpected(operand.getType().getSqlTypeName());
    }
}
 
Example #4
Source File: RelMdSelectivity.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Double getSelectivity(Join rel, RelMetadataQuery mq, RexNode predicate) {
  if (!rel.isSemiJoin()) {
    return getSelectivity((RelNode) rel, mq, predicate);
  }
  // create a RexNode representing the selectivity of the
  // semijoin filter and pass it to getSelectivity
  RexBuilder rexBuilder = rel.getCluster().getRexBuilder();
  RexNode newPred = RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
  if (predicate != null) {
    newPred =
        rexBuilder.makeCall(
            SqlStdOperatorTable.AND,
            newPred,
            predicate);
  }

  return mq.getSelectivity(rel.getLeft(), newPred);
}
 
Example #5
Source File: AggregateReduceFunctionsRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RexNode getSumAggregatedRexNode(Aggregate oldAggRel,
    AggregateCall oldCall,
    List<AggregateCall> newCalls,
    Map<AggregateCall, RexNode> aggCallMapping,
    RexBuilder rexBuilder,
    int argOrdinal,
    int filterArg) {
  final AggregateCall aggregateCall =
      AggregateCall.create(SqlStdOperatorTable.SUM,
          oldCall.isDistinct(),
          oldCall.isApproximate(),
          ImmutableIntList.of(argOrdinal),
          filterArg,
          oldCall.collation,
          oldAggRel.getGroupCount(),
          oldAggRel.getInput(),
          null,
          null);
  return rexBuilder.addAggCall(aggregateCall,
      oldAggRel.getGroupCount(),
      oldAggRel.indicator,
      newCalls,
      aggCallMapping,
      ImmutableList.of(aggregateCall.getType()));
}
 
Example #6
Source File: RelOptUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static boolean containsGet(RexNode node) {
  try {
    node.accept(
        new RexVisitorImpl<Void>(true) {
          @Override public Void visitCall(RexCall call) {
            if (call.getOperator() == RexBuilder.GET_OPERATOR) {
              throw Util.FoundOne.NULL;
            }
            return super.visitCall(call);
          }
        });
    return false;
  } catch (Util.FoundOne e) {
    return true;
  }
}
 
Example #7
Source File: AuxiliaryConverter.java    From flink with Apache License 2.0 6 votes vote down vote up
public RexNode convert(RexBuilder rexBuilder, RexNode groupCall,
			RexNode e) {
			return rexBuilder.makeCall(this.f, e);
			// FLINK QUICK FIX
			// we do not use this logic right now
//      switch (f.getKind()) {
//      case TUMBLE_START:
//      case HOP_START:
//      case SESSION_START:
//      case SESSION_END: // TODO: ?
//        return e;
//      case TUMBLE_END:
//        return rexBuilder.makeCall(
//            SqlStdOperatorTable.PLUS, e,
//            ((RexCall) groupCall).operands.get(1));
//      case HOP_END:
//        return rexBuilder.makeCall(
//            SqlStdOperatorTable.PLUS, e,
//            ((RexCall) groupCall).operands.get(2));
//      default:
//        throw new AssertionError("unknown: " + f);
//      }
		}
 
Example #8
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static RexNode divide(RexBuilder rexBuilder, RexNode res,
    BigDecimal val) {
  if (val.equals(BigDecimal.ONE)) {
    return res;
  }
  // If val is between 0 and 1, rather than divide by val, multiply by its
  // reciprocal. For example, rather than divide by 0.001 multiply by 1000.
  if (val.compareTo(BigDecimal.ONE) < 0
      && val.signum() == 1) {
    try {
      final BigDecimal reciprocal =
          BigDecimal.ONE.divide(val, RoundingMode.UNNECESSARY);
      return multiply(rexBuilder, res,
          rexBuilder.makeExactLiteral(reciprocal));
    } catch (ArithmeticException e) {
      // ignore - reciprocal is not an integer
    }
  }
  return divideInt(rexBuilder, res, rexBuilder.makeExactLiteral(val));
}
 
Example #9
Source File: DateRangeRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Filter filter = call.rel(0);
  final RexBuilder rexBuilder = filter.getCluster().getRexBuilder();
  final String timeZone = filter.getCluster().getPlanner().getContext()
      .unwrap(CalciteConnectionConfig.class).timeZone();
  final RexNode condition =
      replaceTimeUnits(rexBuilder, filter.getCondition(), timeZone);
  if (condition.equals(filter.getCondition())) {
    return;
  }
  final RelBuilder relBuilder =
      relBuilderFactory.create(filter.getCluster(), null);
  relBuilder.push(filter.getInput())
      .filter(condition);
  call.transformTo(relBuilder.build());
}
 
Example #10
Source File: RelOptUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Ands two sets of join filters together, either of which can be null.
 *
 * @param rexBuilder rexBuilder to create AND expression
 * @param left       filter on the left that the right will be AND'd to
 * @param right      filter on the right
 * @return AND'd filter
 *
 * @see org.apache.calcite.rex.RexUtil#composeConjunction
 */
public static RexNode andJoinFilters(
    RexBuilder rexBuilder,
    RexNode left,
    RexNode right) {
  // don't bother AND'ing in expressions that always evaluate to
  // true
  if ((left != null) && !left.isAlwaysTrue()) {
    if ((right != null) && !right.isAlwaysTrue()) {
      left =
          rexBuilder.makeCall(
              SqlStdOperatorTable.AND,
              left,
              right);
    }
  } else {
    left = right;
  }

  // Joins must have some filter
  if (left == null) {
    left = rexBuilder.makeLiteral(true);
  }
  return left;
}
 
Example #11
Source File: SubstitutionVisitor.java    From Bats with Apache License 2.0 6 votes vote down vote up
protected MutableRel invert(MutableRel model, MutableRel input, MutableProject project) {
    LOGGER.trace("SubstitutionVisitor: invert:\nmodel: {}\ninput: {}\nproject: {}\n", model, input, project);
    if (project.projects.size() < model.rowType.getFieldCount()) {
        throw MatchFailed.INSTANCE;
    }
    final List<RexNode> exprList = new ArrayList<>();
    final RexBuilder rexBuilder = model.cluster.getRexBuilder();
    for (RelDataTypeField field : model.rowType.getFieldList()) {
        exprList.add(rexBuilder.makeZeroLiteral(field.getType()));
    }
    for (Ord<RexNode> expr : Ord.zip(project.projects)) {
        if (expr.e instanceof RexInputRef) {
            final int target = ((RexInputRef) expr.e).getIndex();
            exprList.set(target,
                    rexBuilder.ensureType(expr.e.getType(), RexInputRef.of(expr.i, input.rowType), false));
        } else {
            throw MatchFailed.INSTANCE;
        }
    }
    return MutableProject.of(model.rowType, input, exprList);
}
 
Example #12
Source File: SqlSplittableAggFunction.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>{@code COUNT(*)}, and {@code COUNT} applied to all NOT NULL arguments,
 * become {@code 1}; otherwise
 * {@code CASE WHEN arg0 IS NOT NULL THEN 1 ELSE 0 END}.
 */
public RexNode singleton(RexBuilder rexBuilder, RelDataType inputRowType,
    AggregateCall aggregateCall) {
  final List<RexNode> predicates = new ArrayList<>();
  for (Integer arg : aggregateCall.getArgList()) {
    final RelDataType type = inputRowType.getFieldList().get(arg).getType();
    if (type.isNullable()) {
      predicates.add(
          rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL,
              rexBuilder.makeInputRef(type, arg)));
    }
  }
  final RexNode predicate =
      RexUtil.composeConjunction(rexBuilder, predicates, true);
  if (predicate == null) {
    return rexBuilder.makeExactLiteral(BigDecimal.ONE);
  } else {
    return rexBuilder.makeCall(SqlStdOperatorTable.CASE, predicate,
        rexBuilder.makeExactLiteral(BigDecimal.ONE),
        rexBuilder.makeExactLiteral(BigDecimal.ZERO));
  }
}
 
Example #13
Source File: RelOptPredicateList.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a RelOptPredicateList for a join.
 *
 * @param rexBuilder Rex builder
 * @param pulledUpPredicates Predicates that apply to the rows returned by the
 * relational expression
 * @param leftInferredPredicates Predicates that were inferred from the right
 *                               input
 * @param rightInferredPredicates Predicates that were inferred from the left
 *                                input
 */
public static RelOptPredicateList of(RexBuilder rexBuilder,
    Iterable<RexNode> pulledUpPredicates,
    Iterable<RexNode> leftInferredPredicates,
    Iterable<RexNode> rightInferredPredicates) {
  final ImmutableList<RexNode> pulledUpPredicatesList =
      ImmutableList.copyOf(pulledUpPredicates);
  final ImmutableList<RexNode> leftInferredPredicateList =
      ImmutableList.copyOf(leftInferredPredicates);
  final ImmutableList<RexNode> rightInferredPredicatesList =
      ImmutableList.copyOf(rightInferredPredicates);
  if (pulledUpPredicatesList.isEmpty()
      && leftInferredPredicateList.isEmpty()
      && rightInferredPredicatesList.isEmpty()) {
    return EMPTY;
  }
  final ImmutableMap<RexNode, RexNode> constantMap =
      RexUtil.predicateConstants(RexNode.class, rexBuilder,
          pulledUpPredicatesList);
  return new RelOptPredicateList(pulledUpPredicatesList,
      leftInferredPredicateList, rightInferredPredicatesList, constantMap);
}
 
Example #14
Source File: FilterMergeCrule.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Filter topFilter = call.rel(0);
  final Filter bottomFilter = call.rel(1);

  // use RexPrograms to merge the two FilterRels into a single program
  // so we can convert the two LogicalFilter conditions to directly
  // reference the bottom LogicalFilter's child
  RexBuilder rexBuilder = topFilter.getCluster().getRexBuilder();
  RexProgram bottomProgram = createProgram(bottomFilter);
  RexProgram topProgram = createProgram(topFilter);

  RexProgram mergedProgram = RexProgramBuilder.mergePrograms(topProgram, bottomProgram, rexBuilder);

  RexNode newCondition = mergedProgram.expandLocalRef(mergedProgram.getCondition());

  final RelBuilder relBuilder = call.builder();
  relBuilder.push(bottomFilter.getInput()).filter(newCondition);

  call.transformTo(relBuilder.build());
}
 
Example #15
Source File: MaterializedViewSubstitutionVisitor.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static List<RexNode> transformRex(List<RexNode> nodes, final List<RelDataTypeField> oldFields,
        final List<RelDataTypeField> newFields) {
    RexShuttle shuttle = new RexShuttle() {
        @Override
        public RexNode visitInputRef(RexInputRef ref) {
            RelDataTypeField f = oldFields.get(ref.getIndex());
            for (int index = 0; index < newFields.size(); index++) {
                RelDataTypeField newf = newFields.get(index);
                if (f.getKey().equals(newf.getKey()) && f.getValue() == newf.getValue()) {
                    return RexBuilder.getRexFactory().makeInputRef(index, f.getValue());
                }
            }
            throw MatchFailed.INSTANCE;
        }
    };
    return shuttle.apply(nodes);
}
 
Example #16
Source File: FlattenConvertlet.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  SqlFlattenOperator operator = (SqlFlattenOperator) call.getOperator();
  final List<RexNode> exprs = new LinkedList<>();

  for (SqlNode node : call.getOperandList()) {
    exprs.add(cx.convertExpression(node));
  }

  SqlFlattenOperator indexedOperator = operator.withIndex(((SqlValidatorImpl)cx.getValidator()).nextFlattenIndex());
  final RexBuilder rexBuilder = cx.getRexBuilder();
  // Since we don't have any way of knowing if the output of the flatten is nullable, we should always assume it is.
  // This is especially important when accelerating a count(column) query, because the normalizer will convert it to
  // a count(1) if it thinks this column is non-nullable, and then remove the flatten altogether. This is actually a
  // problem with the fact that flatten is not really a project operator (because it can output more than one row per input).
  RelDataType type = rexBuilder
    .getTypeFactory()
    .createTypeWithNullability(
      rexBuilder
        .getTypeFactory()
        .createSqlType(SqlTypeName.ANY),
      true
    );
  return rexBuilder.makeCall(type, indexedOperator, exprs);

}
 
Example #17
Source File: AuxiliaryConverter.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode convert(RexBuilder rexBuilder, RexNode groupCall, RexNode e) {
    switch (f.getKind()) {
    case TUMBLE_START:
    case HOP_START:
    case SESSION_START:
    case SESSION_END: // TODO: ?
        return e;
    case TUMBLE_END:
        return rexBuilder.makeCall(SqlStdOperatorTable.PLUS, e, ((RexCall) groupCall).getOperands().get(1));
    case HOP_END:
        return rexBuilder.makeCall(SqlStdOperatorTable.PLUS, e, ((RexCall) groupCall).getOperands().get(2));
    default:
        throw new AssertionError("unknown: " + f);
    }
}
 
Example #18
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RexToLixTranslator(RexProgram program,
    JavaTypeFactory typeFactory,
    Expression root,
    InputGetter inputGetter,
    BlockBuilder list,
    RexBuilder builder,
    SqlConformance conformance,
    Function1<String, InputGetter> correlates) {
  this.program = program; // may be null
  this.typeFactory = Objects.requireNonNull(typeFactory);
  this.conformance = Objects.requireNonNull(conformance);
  this.root = Objects.requireNonNull(root);
  this.inputGetter = inputGetter;
  this.list = Objects.requireNonNull(list);
  this.builder = Objects.requireNonNull(builder);
  this.correlates = correlates; // may be null
}
 
Example #19
Source File: TestDremioPlanners.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void checkCancelFlag(RelOptPlanner planner) {
  expectedException.expect(UserException.class);
  expectedException.expectMessage("Query was cancelled because planning time exceeded");
  RelOptCluster cluster = RelOptCluster.create(planner, new RexBuilder(SqlTypeFactoryImpl.INSTANCE));
  RelNode root = new NoneRel(cluster);
  planner.setRoot(root);
  planner.findBestExp();
}
 
Example #20
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPADD(unit, count, timestamp)
  //  => timestamp + count * INTERVAL '1' UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  RexNode interval2Add;
  SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
  RexNode op1 = cx.convertExpression(call.operand(1));
  switch (unit) {
  case MICROSECOND:
  case NANOSECOND:
    interval2Add =
        divide(rexBuilder,
            multiply(rexBuilder,
                rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
            BigDecimal.ONE.divide(unit.multiplier,
                RoundingMode.UNNECESSARY));
    break;
  default:
    interval2Add = multiply(rexBuilder,
        rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
  }

  return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
      cx.convertExpression(call.operand(2)), interval2Add);
}
 
Example #21
Source File: RelMdPredicates.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Infers predicates for an Aggregate.
 *
 * <p>Pulls up predicates that only contains references to columns in the
 * GroupSet. For e.g.
 *
 * <blockquote><pre>
 * inputPullUpExprs : { a &gt; 7, b + c &lt; 10, a + e = 9}
 * groupSet         : { a, b}
 * pulledUpExprs    : { a &gt; 7}
 * </pre></blockquote>
 */
public RelOptPredicateList getPredicates(Aggregate agg, RelMetadataQuery mq) {
  final RelNode input = agg.getInput();
  final RexBuilder rexBuilder = agg.getCluster().getRexBuilder();
  final RelOptPredicateList inputInfo = mq.getPulledUpPredicates(input);
  final List<RexNode> aggPullUpPredicates = new ArrayList<>();

  ImmutableBitSet groupKeys = agg.getGroupSet();
  if (groupKeys.isEmpty()) {
    // "GROUP BY ()" can convert an empty relation to a non-empty relation, so
    // it is not valid to pull up predicates. In particular, consider the
    // predicate "false": it is valid on all input rows (trivially - there are
    // no rows!) but not on the output (there is one row).
    return RelOptPredicateList.EMPTY;
  }
  Mapping m = Mappings.create(MappingType.PARTIAL_FUNCTION,
      input.getRowType().getFieldCount(), agg.getRowType().getFieldCount());

  int i = 0;
  for (int j : groupKeys) {
    m.set(j, i++);
  }

  for (RexNode r : inputInfo.pulledUpPredicates) {
    ImmutableBitSet rCols = RelOptUtil.InputFinder.bits(r);
    if (groupKeys.contains(rCols)) {
      r = r.accept(new RexPermuteInputsShuttle(m, input));
      aggPullUpPredicates.add(r);
    }
  }
  return RelOptPredicateList.of(rexBuilder, aggPullUpPredicates);
}
 
Example #22
Source File: SubstitutionVisitor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static RexNode splitOr(final RexBuilder rexBuilder, RexNode condition, RexNode target) {
    List<RexNode> conditions = RelOptUtil.disjunctions(condition);
    int conditionsLength = conditions.size();
    int targetsLength = 0;
    for (RexNode e : RelOptUtil.disjunctions(target)) {
        removeAll(conditions, e);
        targetsLength++;
    }
    if (conditions.isEmpty() && conditionsLength == targetsLength) {
        return rexBuilder.makeLiteral(true);
    } else if (conditions.isEmpty()) {
        return condition;
    }
    return null;
}
 
Example #23
Source File: RelOptUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static RexNode shiftFilter(int start, int end, int offset, RexBuilder rexBuilder,
        List<RelDataTypeField> joinFields, int nTotalFields, List<RelDataTypeField> rightFields, RexNode filter) {
    int[] adjustments = new int[nTotalFields];
    for (int i = start; i < end; i++) {
        adjustments[i] = offset;
    }
    return filter.accept(new RexInputConverter(rexBuilder, joinFields, rightFields, adjustments));
}
 
Example #24
Source File: DateRangeRules.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void onMatch(RelOptRuleCall call) {
    final Filter filter = call.rel(0);
    final RexBuilder rexBuilder = filter.getCluster().getRexBuilder();
    final String timeZone = filter.getCluster().getPlanner().getContext().unwrap(CalciteConnectionConfig.class)
            .timeZone();
    final RexNode condition = replaceTimeUnits(rexBuilder, filter.getCondition(), timeZone);
    if (condition.equals(filter.getCondition())) {
        return;
    }
    final RelBuilder relBuilder = relBuilderFactory.create(filter.getCluster(), null);
    relBuilder.push(filter.getInput()).filter(condition);
    call.transformTo(relBuilder.build());
}
 
Example #25
Source File: SqlNodeToRexConverterImpl.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexLiteral convertInterval(
    SqlRexContext cx,
    SqlIntervalQualifier intervalQualifier) {
  RexBuilder rexBuilder = cx.getRexBuilder();

  return rexBuilder.makeIntervalLiteral(intervalQualifier);
}
 
Example #26
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 #27
Source File: RelDecorrelator.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public RexNode visitFieldAccess(RexFieldAccess fieldAccess) {
    int newInputOutputOffset = 0;
    for (RelNode input : currentRel.getInputs()) {
        final Frame frame = map.get(input);

        if (frame != null) {
            // try to find in this input rel the position of corVar
            final CorRef corRef = cm.mapFieldAccessToCorRef.get(fieldAccess);

            if (corRef != null) {
                Integer newInputPos = frame.corDefOutputs.get(corRef.def());
                if (newInputPos != null) {
                    // This input does produce the corVar referenced.
                    return RexBuilder.getRexFactory().makeInputRef(newInputPos + newInputOutputOffset,
                            frame.r.getRowType().getFieldList().get(newInputPos).getType());
                }
            }

            // this input does not produce the corVar needed
            newInputOutputOffset += frame.r.getRowType().getFieldCount();
        } else {
            // this input is not rewritten
            newInputOutputOffset += input.getRowType().getFieldCount();
        }
    }
    return fieldAccess;
}
 
Example #28
Source File: FieldsReWriterUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public RexNode visitCall(final RexCall call) {
    Integer index = mapper.get(call);
    if (index != null) {
        return RexBuilder.getRexFactory().makeInputRef(index, call.getType());
    }
    return super.visitCall(call);
}
 
Example #29
Source File: HiveRexExecutorImpl.java    From marble with Apache License 2.0 5 votes vote down vote up
private String compile(RexBuilder rexBuilder, List<RexNode> constExps,
    RexToLixTranslator.InputGetter getter, RelDataType rowType) {
  final RexProgramBuilder programBuilder =
      new RexProgramBuilder(rowType, rexBuilder);
  for (RexNode node : constExps) {
    programBuilder.addProject(
        node, "c" + programBuilder.getProjectList().size());
  }
  final JavaTypeFactoryImpl javaTypeFactory =
      new JavaTypeFactoryImpl(rexBuilder.getTypeFactory().getTypeSystem());
  final BlockBuilder blockBuilder = new BlockBuilder();
  final ParameterExpression root0_ =
      Expressions.parameter(Object.class, "root0");
  final ParameterExpression root_ = DataContext.ROOT;
  blockBuilder.add(
      Expressions.declare(
          Modifier.FINAL, root_,
          Expressions.convert_(root0_, DataContext.class)));
  final SqlConformance conformance = SqlConformanceEnum.HIVE;
  final RexProgram program = programBuilder.getProgram();
  final List<Expression> expressions =
      RexToLixTranslator.translateProjects(program, javaTypeFactory,
          conformance, blockBuilder, null, root_, getter, null);
  blockBuilder.add(
      Expressions.return_(null,
          Expressions.newArrayInit(Object[].class, expressions)));
  final MethodDeclaration methodDecl =
      Expressions.methodDecl(Modifier.PUBLIC, Object[].class,
          BuiltInMethod.FUNCTION1_APPLY.method.getName(),
          ImmutableList.of(root0_), blockBuilder.toBlock());
  String code = Expressions.toString(methodDecl);
  if (CalcitePrepareImpl.DEBUG) {
    Util.debugCode(System.out, code);
  }
  return code;
}
 
Example #30
Source File: RelDecorrelator.java    From flink with Apache License 2.0 5 votes vote down vote up
RemoveCorrelationRexShuttle(
    RexBuilder rexBuilder,
    boolean projectPulledAboveLeftCorrelator,
    RexInputRef nullIndicator,
    Set<Integer> isCount) {
  this.projectPulledAboveLeftCorrelator =
      projectPulledAboveLeftCorrelator;
  this.nullIndicator = nullIndicator; // may be null
  this.isCount = ImmutableSet.copyOf(isCount);
  this.rexBuilder = rexBuilder;
  this.typeFactory = rexBuilder.getTypeFactory();
}