Java Code Examples for org.apache.calcite.rex.RexCall#getOperands()

The following examples show how to use org.apache.calcite.rex.RexCall#getOperands() . 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: RelMdSize.java    From Bats with Apache License 2.0 6 votes vote down vote up
public Double averageRexSize(RexNode node, List<Double> inputColumnSizes) {
  switch (node.getKind()) {
  case INPUT_REF:
    return inputColumnSizes.get(((RexInputRef) node).getIndex());
  case LITERAL:
    return typeValueSize(node.getType(),
        ((RexLiteral) node).getValueAs(Comparable.class));
  default:
    if (node instanceof RexCall) {
      RexCall call = (RexCall) node;
      for (RexNode operand : call.getOperands()) {
        // It's a reasonable assumption that a function's result will have
        // similar size to its argument of a similar type. For example,
        // UPPER(c) has the same average size as c.
        if (operand.getType().getSqlTypeName()
            == node.getType().getSqlTypeName()) {
          return averageRexSize(operand, inputColumnSizes);
        }
      }
    }
    return averageTypeValueSize(node.getType());
  }
}
 
Example 2
Source File: AggregateJoinTransposeRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void populateEquivalences(Map<Integer, BitSet> equivalence,
    RexNode predicate) {
  switch (predicate.getKind()) {
  case EQUALS:
    RexCall call = (RexCall) predicate;
    final List<RexNode> operands = call.getOperands();
    if (operands.get(0) instanceof RexInputRef) {
      final RexInputRef ref0 = (RexInputRef) operands.get(0);
      if (operands.get(1) instanceof RexInputRef) {
        final RexInputRef ref1 = (RexInputRef) operands.get(1);
        populateEquivalence(equivalence, ref0.getIndex(), ref1.getIndex());
        populateEquivalence(equivalence, ref1.getIndex(), ref0.getIndex());
      }
    }
  }
}
 
Example 3
Source File: JoinCommuteRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
public RexNode go(RexNode rex) {
    if (rex instanceof RexCall) {
        ImmutableList.Builder<RexNode> builder = ImmutableList.builder();
        final RexCall call = (RexCall) rex;
        for (RexNode operand : call.getOperands()) {
            builder.add(go(operand));
        }
        return call.clone(call.getType(), builder.build());
    } else if (rex instanceof RexInputRef) {
        RexInputRef var = (RexInputRef) rex;
        int index = var.getIndex();
        if (index < leftFields.size()) {
            // Field came from left side of join. Move it to the right.
            return rexBuilder.makeInputRef(leftFields.get(index).getType(), rightFields.size() + index);
        }
        index -= leftFields.size();
        if (index < rightFields.size()) {
            // Field came from right side of join. Move it to the left.
            return rexBuilder.makeInputRef(rightFields.get(index).getType(), index);
        }
        throw new AssertionError("Bad field offset: index=" + var.getIndex() + ", leftFieldCount="
                + leftFields.size() + ", rightFieldCount=" + rightFields.size());
    } else {
        return rex;
    }
}
 
Example 4
Source File: AggregateJoinTransposeRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static void populateEquivalences(Map<Integer, BitSet> equivalence,
    RexNode predicate) {
  switch (predicate.getKind()) {
  case EQUALS:
    RexCall call = (RexCall) predicate;
    final List<RexNode> operands = call.getOperands();
    if (operands.get(0) instanceof RexInputRef) {
      final RexInputRef ref0 = (RexInputRef) operands.get(0);
      if (operands.get(1) instanceof RexInputRef) {
        final RexInputRef ref1 = (RexInputRef) operands.get(1);
        populateEquivalence(equivalence, ref0.getIndex(), ref1.getIndex());
        populateEquivalence(equivalence, ref1.getIndex(), ref0.getIndex());
      }
    }
  }
}
 
Example 5
Source File: ReduceDecimalsRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode expand(RexCall call) {
    ImmutableList.Builder<RexNode> opBuilder = ImmutableList.builder();
    for (RexNode operand : call.getOperands()) {
        if (SqlTypeUtil.isNumeric(operand.getType())) {
            opBuilder.add(accessValue(operand));
        } else {
            opBuilder.add(operand);
        }
    }

    RexNode newCall = builder.makeCall(call.getType(), call.getOperator(), opBuilder.build());
    if (SqlTypeUtil.isDecimal(call.getType())) {
        return encodeValue(newCall, call.getType());
    } else {
        return newCall;
    }
}
 
Example 6
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * The CASE operator is SQL’s way of handling if/then logic.
 * Different with other {@code RexCall}s, it is not safe to
 * implement its operands first.
 * For example: {@code
 *   select case when s=0 then false
 *          else 100/s > 0 end
 *   from (values (1),(0)) ax(s);
 * }
 */
private Result implementCaseWhen(RexCall call) {
  final Type returnType = typeFactory.getJavaClass(call.getType());
  final ParameterExpression valueVariable =
      Expressions.parameter(returnType,
          list.newName("case_when_value"));
  list.add(Expressions.declare(0, valueVariable, null));
  final List<RexNode> operandList = call.getOperands();
  implementRecursively(this, operandList, valueVariable, 0);
  final Expression isNullExpression = checkNull(valueVariable);
  final ParameterExpression isNullVariable =
      Expressions.parameter(
          Boolean.TYPE, list.newName("case_when_isNull"));
  list.add(Expressions.declare(Modifier.FINAL, isNullVariable, isNullExpression));
  final Result result = new Result(isNullVariable, valueVariable);
  rexResultMap.put(call, result);
  return result;
}
 
Example 7
Source File: SimpleRexRemap.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public PathSegment visitCall(RexCall call) {
    if ("ITEM".equals(call.getOperator().getName())) {
        stackDepth++;
        PathSegment mapOrArray = call.getOperands().get(0).accept(this);
        stackDepth--;
        if (mapOrArray != null) {
            if (call.getOperands().get(1) instanceof RexLiteral) {
                PathSegment newFieldPath = newPath(
                        mapOrArray.cloneWithNewChild(convertLiteral((RexLiteral) call.getOperands().get(1))),
                        call);
                return newFieldPath;
            }
            return mapOrArray;
        }
    } else {
        for (RexNode operand : call.getOperands()) {
            operand.accept(this);
        }
    }
    return null;
}
 
Example 8
Source File: OLAPJoinRel.java    From kylin with Apache License 2.0 6 votes vote down vote up
void translateJoinColumn(RexCall condition, Multimap<TblColRef, TblColRef> joinColumns) {
    SqlKind kind = condition.getOperator().getKind();
    if (kind == SqlKind.AND) {
        for (RexNode operand : condition.getOperands()) {
            RexCall subCond = (RexCall) operand;
            translateJoinColumn(subCond, joinColumns);
        }
    } else if (kind == SqlKind.EQUALS) {
        List<RexNode> operands = condition.getOperands();
        RexInputRef op0 = (RexInputRef) operands.get(0);
        TblColRef col0 = columnRowType.getColumnByIndex(op0.getIndex());
        RexInputRef op1 = (RexInputRef) operands.get(1);
        TblColRef col1 = columnRowType.getColumnByIndex(op1.getIndex());
        // map left => right
        if (op0.getIndex() < columnRowTypeLeftRightCut)
            joinColumns.put(col0, col1);
        else
            joinColumns.put(col1, col0);
    }
}
 
Example 9
Source File: DrillRelMdSelectivity.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static RexInputRef findRexInputRef(final RexNode node) {
  try {
    RexVisitor<Void> visitor =
        new RexVisitorImpl<Void>(true) {
          public Void visitCall(RexCall call) {
            for (RexNode child : call.getOperands()) {
              child.accept(this);
            }
            return super.visitCall(call);
          }

          public Void visitInputRef(RexInputRef inputRef) {
            throw new Util.FoundOne(inputRef);
          }
        };
    node.accept(visitor);
    return null;
  } catch (Util.FoundOne e) {
    Util.swallow(e, null);
    return (RexInputRef) e.getNode();
  }
}
 
Example 10
Source File: FlinkAggregateJoinTransposeRule.java    From flink with Apache License 2.0 6 votes vote down vote up
private static void populateEquivalences(Map<Integer, BitSet> equivalence,
		RexNode predicate) {
	switch (predicate.getKind()) {
		case EQUALS:
			RexCall call = (RexCall) predicate;
			final List<RexNode> operands = call.getOperands();
			if (operands.get(0) instanceof RexInputRef) {
				final RexInputRef ref0 = (RexInputRef) operands.get(0);
				if (operands.get(1) instanceof RexInputRef) {
					final RexInputRef ref1 = (RexInputRef) operands.get(1);
					populateEquivalence(equivalence, ref0.getIndex(), ref1.getIndex());
					populateEquivalence(equivalence, ref1.getIndex(), ref0.getIndex());
				}
			}
	}
}
 
Example 11
Source File: SolrFilter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Translates a call to a binary operator, reversing arguments if necessary.
 */
private Pair<String, RexLiteral> translateBinary(RexCall call) {
  List<RexNode> operands = call.getOperands();
  if (operands.size() != 2) {
    throw new AssertionError("Invalid number of arguments - " + operands.size());
  }
  final RexNode left = operands.get(0);
  final RexNode right = operands.get(1);
  final Pair<String, RexLiteral> a = translateBinary2(left, right);
  if (a != null) {
    return a;
  }
  final Pair<String, RexLiteral> b = translateBinary2(right, left);
  if (b != null) {
    return b;
  }
  throw new AssertionError("cannot translate call " + call);
}
 
Example 12
Source File: RewriteAsBinaryOperators.java    From Bats with Apache License 2.0 5 votes vote down vote up
private List<RexNode> visitChildren(RexCall call) {
  List<RexNode> children = Lists.newArrayList();
  for (RexNode child : call.getOperands()) {
    children.add(child.accept(this));
  }
  return ImmutableList.copyOf(children);
}
 
Example 13
Source File: RexUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static CompareTupleFilter.CompareResultType getCompareResultType(RexCall whenCall) {
    List<RexNode> operands = whenCall.getOperands();
    if (SqlKind.EQUALS == whenCall.getKind() && operands != null && operands.size() == 2) {
        if (operands.get(0).equals(operands.get(1))) {
            return CompareTupleFilter.CompareResultType.AlwaysTrue;
        }

        if (isConstant(operands.get(0)) && isConstant(operands.get(1))) {
            return CompareTupleFilter.CompareResultType.AlwaysFalse;
        }
    }
    return CompareTupleFilter.CompareResultType.Unknown;
}
 
Example 14
Source File: TupleExpressionVisitor.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public TupleExpression visitFirstRexInputRef(RexCall call) {
    for (RexNode operand : call.getOperands()) {
        if (operand instanceof RexInputRef) {
            return visitInputRef((RexInputRef) operand);
        }
        if (operand instanceof RexCall) {
            TupleExpression r = visitFirstRexInputRef((RexCall) operand);
            if (r != null)
                return r;
        }
    }
    return null;
}
 
Example 15
Source File: RexImplicationChecker.java    From Bats with Apache License 2.0 5 votes vote down vote up
private void updateBinaryOpUsage(RexCall call) {
  final List<RexNode> operands = call.getOperands();
  RexNode first = removeCast(operands.get(0));
  RexNode second = removeCast(operands.get(1));

  if (first.isA(SqlKind.INPUT_REF)
      && second.isA(SqlKind.LITERAL)) {
    updateUsage(call.getOperator(), (RexInputRef) first, second);
  }

  if (first.isA(SqlKind.LITERAL)
      && second.isA(SqlKind.INPUT_REF)) {
    updateUsage(reverse(call.getOperator()), (RexInputRef) second, first);
  }
}
 
Example 16
Source File: RexImplicationChecker.java    From Bats with Apache License 2.0 5 votes vote down vote up
private void updateUnaryOpUsage(RexCall call) {
  final List<RexNode> operands = call.getOperands();
  RexNode first = removeCast(operands.get(0));

  if (first.isA(SqlKind.INPUT_REF)) {
    updateUsage(call.getOperator(), (RexInputRef) first, null);
  }
}
 
Example 17
Source File: PredicateAnalyzer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public Expression visitCall(RexCall call) {

  SqlSyntax syntax = call.getOperator().getSyntax();
  if (!supportedRexCall(call)) {
    throw new PredicateAnalyzerException(format("Unsupported call: [%s]", call));
  }

  switch (syntax) {
    case BINARY:
      return binary(call);
    case POSTFIX:
      return postfix(call);
    case SPECIAL:
      switch (call.getKind()) {
        case CAST:
          return cast(call);
        case LIKE:
          return binary(call);
        default:
          throw new PredicateAnalyzerException(format("Unsupported call: [%s]", call));
      }
    case FUNCTION:
      if (call.getOperator().getName().equalsIgnoreCase("CONTAINS")) {
        List<Expression> operands = Lists.newArrayList();
        for (RexNode node : call.getOperands()) {
          final Expression nodeExpr = node.accept(this);
          operands.add(nodeExpr);
        }
        String query = convertQueryString(operands.subList(0, operands.size() - 1), operands.get(operands.size() - 1));
        return QueryExpression.create(new NamedFieldExpression(null)).queryString(query);
      }
    default:
      throw new PredicateAnalyzerException(format("Unsupported syntax [%s] for call: [%s]", syntax, call));
  }
}
 
Example 18
Source File: ReduceExpressionsRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
private void reduceCasts(RexCall outerCast) {
  List<RexNode> operands = outerCast.getOperands();
  if (operands.size() != 1) {
    return;
  }
  RelDataType outerCastType = outerCast.getType();
  RelDataType operandType = operands.get(0).getType();
  if (operandType.equals(outerCastType)) {
    removableCasts.add(outerCast);
    return;
  }

  // See if the reduction
  // CAST((CAST x AS type) AS type NOT NULL)
  // -> CAST(x AS type NOT NULL)
  // applies.  TODO jvs 15-Dec-2008:  consider
  // similar cases for precision changes.
  if (!(operands.get(0) instanceof RexCall)) {
    return;
  }
  RexCall innerCast = (RexCall) operands.get(0);
  if (innerCast.getOperator() != SqlStdOperatorTable.CAST) {
    return;
  }
  if (innerCast.getOperands().size() != 1) {
    return;
  }
  RelDataType outerTypeNullable =
      typeFactory.createTypeWithNullability(outerCastType, true);
  RelDataType innerTypeNullable =
      typeFactory.createTypeWithNullability(operandType, true);
  if (outerTypeNullable != innerTypeNullable) {
    return;
  }
  if (operandType.isNullable()) {
    removableCasts.add(innerCast);
  }
}
 
Example 19
Source File: RewriteCombineBinaryOperators.java    From Bats with Apache License 2.0 5 votes vote down vote up
private List<RexNode> visitChildren(RexCall call) {
  List<RexNode> children = Lists.newArrayList();
  for (RexNode child : call.getOperands()) {
    children.add(child.accept(this));
  }
  return ImmutableList.copyOf(children);
}
 
Example 20
Source File: ReduceExpressionsRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Pushes predicates into a CASE.
 *
 * <p>We have a loose definition of 'predicate': any boolean expression will
 * do, except CASE. For example '(CASE ...) = 5' or '(CASE ...) IS NULL'.
 */
public static RexCall pushPredicateIntoCase(RexCall call) {
  if (call.getType().getSqlTypeName() != SqlTypeName.BOOLEAN) {
    return call;
  }
  switch (call.getKind()) {
  case CASE:
  case AND:
  case OR:
    return call; // don't push CASE into CASE!
  case EQUALS: {
    // checks that the EQUALS operands may be splitted and
    // doesn't push EQUALS into CASE
    List<RexNode> equalsOperands = call.getOperands();
    ImmutableBitSet left = RelOptUtil.InputFinder.bits(equalsOperands.get(0));
    ImmutableBitSet right = RelOptUtil.InputFinder.bits(equalsOperands.get(1));
    if (!left.isEmpty() && !right.isEmpty() && left.intersect(right).isEmpty()) {
      return call;
    }
  }
  }
  int caseOrdinal = -1;
  final List<RexNode> operands = call.getOperands();
  for (int i = 0; i < operands.size(); i++) {
    RexNode operand = operands.get(i);
    if (operand.getKind() == SqlKind.CASE) {
      caseOrdinal = i;
    }
  }
  if (caseOrdinal < 0) {
    return call;
  }
  // Convert
  //   f(CASE WHEN p1 THEN v1 ... END, arg)
  // to
  //   CASE WHEN p1 THEN f(v1, arg) ... END
  final RexCall case_ = (RexCall) operands.get(caseOrdinal);
  final List<RexNode> nodes = new ArrayList<>();
  for (int i = 0; i < case_.getOperands().size(); i++) {
    RexNode node = case_.getOperands().get(i);
    if (!RexUtil.isCasePredicate(case_, i)) {
      node = substitute(call, caseOrdinal, node);
    }
    nodes.add(node);
  }
  return case_.clone(call.getType(), nodes);
}