org.apache.calcite.rex.RexCall Java Examples

The following examples show how to use org.apache.calcite.rex.RexCall. 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: IndexableExprMarker.java    From Bats with Apache License 2.0 6 votes vote down vote up
public boolean operandsAreIndexable(RexCall call) {
    SqlKind kind = call.getKind();
    boolean kindIsRight = (SqlKind.COMPARISON.contains(kind) || kind == SqlKind.LIKE || kind == SqlKind.SIMILAR);

    if (!kindIsRight) {
        return false;
    }

    int inputReference = 0;
    for (RexNode operand : call.getOperands()) {
        // if for this operator, there are two operands and more have inputRef, which means it is something like:
        // a.b = a.c, instead of a.b ='hello', so this cannot apply index
        if (containInputRef(operand)) {
            inputReference++;
            if (inputReference >= 2) {
                return false;
            }
        }
    }
    return true;
}
 
Example #2
Source File: CoveringIndexPlanGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
private void rewriteConditionForProjectInternal(RexNode condition, List<RexNode> projects,
        Map<RexNode, RexNode> mapping) {
    if (condition instanceof RexCall) {
        if ("ITEM".equals(((RexCall) condition).getOperator().getName().toUpperCase())) {
            int index = 0;
            for (RexNode project : projects) {
                if (project.toString().equals(condition.toString())) {
                    // Map it to the corresponding RexInputRef for the project
                    mapping.put(condition, RexBuilder.getRexFactory().makeInputRef(index, project.getType()));
                }
                ++index;
            }
        } else {
            for (RexNode child : ((RexCall) condition).getOperands()) {
                rewriteConditionForProjectInternal(child, projects, mapping);
            }
        }
    }
}
 
Example #3
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 #4
Source File: RelDecorrelator.java    From flink with Apache License 2.0 6 votes vote down vote up
private boolean references(RexNode e, CorRef correlation) {
  switch (e.getKind()) {
  case CAST:
    final RexNode operand = ((RexCall) e).getOperands().get(0);
    if (isWidening(e.getType(), operand.getType())) {
      return references(operand, correlation);
    }
    return false;
  case FIELD_ACCESS:
    final RexFieldAccess f = (RexFieldAccess) e;
    if (f.getField().getIndex() == correlation.field
        && f.getReferenceExpr() instanceof RexCorrelVariable) {
      if (((RexCorrelVariable) f.getReferenceExpr()).id == correlation.corr) {
        return true;
      }
    }
    // fall through
  default:
    return false;
  }
}
 
Example #5
Source File: PushProjector.java    From Bats with Apache License 2.0 6 votes vote down vote up
public RexNode visitCall(RexCall call) {
  // if the expression corresponds to one that needs to be preserved,
  // convert it to a field reference; otherwise, convert the entire
  // expression
  int match =
      findExprInLists(
          call,
          preserveLeft,
          firstLeftRef,
          preserveRight,
          firstRightRef);
  if (match >= 0) {
    return rexBuilder.makeInputRef(
        destFields.get(match).getType(),
        match);
  }
  return super.visitCall(call);
}
 
Example #6
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 #7
Source File: ReduceDecimalsRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RexNode expandPlusMinus(RexCall call, List<RexNode> operands) {
  RelDataType outType = call.getType();
  int outScale = outType.getScale();
  return encodeValue(
      builder.makeCall(
          call.getOperator(),
          ensureScale(
              accessValue(operands.get(0)),
              scaleA,
              outScale),
          ensureScale(
              accessValue(operands.get(1)),
              scaleB,
              outScale)),
      outType);
}
 
Example #8
Source File: RexVisitorComplexExprSplitter.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode visitCall(RexCall call) {

    String functionName = call.getOperator().getName();

    List<RexNode> newOps = new ArrayList<>();
    for (RexNode operand : call.getOperands()) {
        newOps.add(operand.accept(this));
    }
    if (funcReg.isFunctionComplexOutput(functionName)) {
        RexBuilder builder = new RexBuilder(factory);
        RexNode ret = builder.makeInputRef(new RelDataTypeDrillImpl(new RelDataTypeHolder(), factory),
                lastUsedIndex);
        lastUsedIndex++;
        complexExprs.add(call.clone(new RelDataTypeDrillImpl(new RelDataTypeHolder(), factory), newOps));
        return ret;
    }
    return call.clone(call.getType(), newOps);
}
 
Example #9
Source File: PigRelExVisitor.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void visit(UserFuncExpression op) throws FrontendException {
  if (op.getFuncSpec().getClassName().equals("org.apache.pig.impl.builtin.IdentityColumn")) {
    // Skip this Pig dummy function
    return;
  }
  final int numAgrs = optSize(op.getPlan().getSuccessors(op))
      + optSize(op.getPlan().getSoftLinkSuccessors(op));

  final RelDataType returnType = PigTypes.convertSchemaField(op.getFieldSchema());
  stack.push(
      PigRelUdfConverter.convertPigFunction(
          builder, op.getFuncSpec(), buildOperands(numAgrs), returnType));

  String className = op.getFuncSpec().getClassName();
  SqlOperator sqlOp = ((RexCall) stack.peek()).getOperator();
  if (sqlOp instanceof SqlUserDefinedFunction) {
    ScalarFunctionImpl sqlFunc =
        (ScalarFunctionImpl) ((SqlUserDefinedFunction) sqlOp).getFunction();
    // "Exec" method can be implemented from the parent class.
    className = sqlFunc.method.getDeclaringClass().getName();
  }
  builder.registerPigUDF(className, op.getFuncSpec());
}
 
Example #10
Source File: ReduceDecimalsRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RexNode expandTimes(RexCall call, List<RexNode> operands) {
    // Multiplying the internal values of the two arguments leads to
    // a number with scale = scaleA + scaleB. If the result type has
    // a lower scale, then the number should be scaled down.
    int divisor = scaleA + scaleB - call.getType().getScale();

    if (builder.getTypeFactory().useDoubleMultiplication(typeA, typeB)) {
        // Approximate implementation:
        // cast (a as double) * cast (b as double)
        // / 10^divisor
        RexNode division = makeDivide(
                makeMultiply(ensureType(real8, accessValue(operands.get(0))),
                        ensureType(real8, accessValue(operands.get(1)))),
                makeApproxLiteral(BigDecimal.TEN.pow(divisor)));
        return encodeValue(division, call.getType(), true);
    } else {
        // Exact implementation: scaleDown(a * b)
        return encodeValue(scaleDown(builder.makeCall(call.getOperator(), accessValue(operands.get(0)),
                accessValue(operands.get(1))), divisor), call.getType());
    }
}
 
Example #11
Source File: OLAPJoinRel.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
protected JoinDesc buildJoin(RexCall condition) {
    Multimap<TblColRef, TblColRef> joinColumns = HashMultimap.create();
    translateJoinColumn(condition, joinColumns);

    List<String> pks = new ArrayList<String>();
    List<TblColRef> pkCols = new ArrayList<TblColRef>();
    List<String> fks = new ArrayList<String>();
    List<TblColRef> fkCols = new ArrayList<TblColRef>();
    for (Map.Entry<TblColRef, TblColRef> columnPair : joinColumns.entries()) {
        TblColRef fromCol = columnPair.getKey();
        TblColRef toCol = columnPair.getValue();
        fks.add(fromCol.getName());
        fkCols.add(fromCol);
        pks.add(toCol.getName());
        pkCols.add(toCol);
    }

    JoinDesc join = new JoinDesc();
    join.setForeignKey(fks.toArray(COLUMN_ARRAY_MARKER));
    join.setForeignKeyColumns(fkCols.toArray(new TblColRef[fkCols.size()]));
    join.setPrimaryKey(pks.toArray(COLUMN_ARRAY_MARKER));
    join.setPrimaryKeyColumns(pkCols.toArray(new TblColRef[pkCols.size()]));
    join.sortByFK();
    return join;
}
 
Example #12
Source File: DrillRelOptUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Find whether the given project rel has unknown output schema. This would happen if the
 * project has CONVERT_FROMJSON which can only derive the schema after evaluation is performed
 * @param project : The project rel
 * @return : Return true if the project output schema is unknown. Otherwise, false.
 */
public static boolean isProjectOutputSchemaUnknown(Project project) {
    try {
        RexVisitor<Void> visitor = new RexVisitorImpl<Void>(true) {
            @Override
            public Void visitCall(RexCall call) {
                if ("convert_fromjson".equals(call.getOperator().getName().toLowerCase())) {
                    throw new Util.FoundOne(call); /* throw exception to interrupt tree walk (this is similar to
                                                   other utility methods in RexUtil.java */
                }
                return super.visitCall(call);
            }
        };
        for (RexNode rex : project.getProjects()) {
            rex.accept(visitor);
        }
    } catch (Util.FoundOne e) {
        Util.swallow(e, null);
        return true;
    }
    return false;
}
 
Example #13
Source File: PredicateAnalyzer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode visitCall(RexCall call) {
  if (call.getOperator().getKind() == SqlKind.NOT) {
    RexNode child = call.getOperands().get(0);
    if (child.getKind() == SqlKind.LIKE) {
      List<RexNode> operands = FluentIterable.from(((RexCall) child).getOperands()).transform(new Function<RexNode, RexNode>() {
        @Override
        public RexNode apply(RexNode rexNode) {
          return rexNode.accept(NotLikeConverter.this);
        }
      }).toList();
      return rexBuilder.makeCall(SqlStdOperatorTable.NOT_LIKE, operands);
    }
  }
  return super.visitCall(call);
}
 
Example #14
Source File: CassandraFilter.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Translate a binary relation. */
private String translateMatch2(RexNode node) {
  // We currently only use equality, but inequalities on clustering keys
  // should be possible in the future
  switch (node.getKind()) {
  case EQUALS:
    return translateBinary("=", "=", (RexCall) node);
  case LESS_THAN:
    return translateBinary("<", ">", (RexCall) node);
  case LESS_THAN_OR_EQUAL:
    return translateBinary("<=", ">=", (RexCall) node);
  case GREATER_THAN:
    return translateBinary(">", "<", (RexCall) node);
  case GREATER_THAN_OR_EQUAL:
    return translateBinary(">=", "<=", (RexCall) node);
  default:
    throw new AssertionError("cannot translate " + node);
  }
}
 
Example #15
Source File: PigJoin.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a Pig JOIN statement in the form of
 * <pre>
 * {@code
 * A = JOIN A BY f1 LEFT OUTER, B BY f2;
 * }
 * </pre>
 * Only supports simple equi-joins with single column on both sides of
 * <code>=</code>.
 */
private String getPigJoinStatement(Implementor implementor) {
  if (!getCondition().isA(SqlKind.EQUALS)) {
    throw new IllegalArgumentException("Only equi-join are supported");
  }
  List<RexNode> operands = ((RexCall) getCondition()).getOperands();
  if (operands.size() != 2) {
    throw new IllegalArgumentException("Only equi-join are supported");
  }
  List<Integer> leftKeys = new ArrayList<>(1);
  List<Integer> rightKeys = new ArrayList<>(1);
  List<Boolean> filterNulls = new ArrayList<>(1);
  RelOptUtil.splitJoinCondition(getLeft(), getRight(), getCondition(), leftKeys, rightKeys,
      filterNulls);

  String leftRelAlias = implementor.getPigRelationAlias((PigRel) getLeft());
  String rightRelAlias = implementor.getPigRelationAlias((PigRel) getRight());
  String leftJoinFieldName = implementor.getFieldName((PigRel) getLeft(), leftKeys.get(0));
  String rightJoinFieldName = implementor.getFieldName((PigRel) getRight(), rightKeys.get(0));

  return implementor.getPigRelationAlias((PigRel) getLeft()) + " = JOIN " + leftRelAlias + " BY "
      + leftJoinFieldName + ' ' + getPigJoinType() + ", " + rightRelAlias + " BY "
      + rightJoinFieldName + ';';
}
 
Example #16
Source File: RexVisitorComplexExprSplitter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode visitCall(RexCall call) {

  String functionName = call.getOperator().getName();

  List<RexNode> newOps = new ArrayList<>();
  for (RexNode operand : call.operands) {
    newOps.add(operand.accept(this));
  }
  if (funcReg.isFunctionComplexOutput(functionName)) {
    RexNode ret = builder.makeInputRef( factory.createTypeWithNullability(factory.createSqlType(SqlTypeName.ANY), true), lastUsedIndex);
    lastUsedIndex++;
    complexExprs.add(call.clone(factory.createTypeWithNullability(factory.createSqlType(SqlTypeName.ANY), true), newOps));
    return ret;
  }
  return call.clone(call.getType(), newOps);
}
 
Example #17
Source File: DruidJsonFilter.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Nullable
private static DruidJsonFilter toIsNullKindDruidFilter(RexNode rexNode, RelDataType rowType,
    DruidQuery druidQuery) {
  if (rexNode.getKind() != SqlKind.IS_NULL && rexNode.getKind() != SqlKind.IS_NOT_NULL) {
    throw new AssertionError(
        DruidQuery.format("Expecting IS_NULL or IS_NOT_NULL but got [%s]", rexNode.getKind()));
  }
  final RexCall rexCall = (RexCall) rexNode;
  final RexNode refNode = rexCall.getOperands().get(0);
  Pair<String, ExtractionFunction> druidColumn = DruidQuery
      .toDruidColumn(refNode, rowType, druidQuery);
  final String columnName = druidColumn.left;
  final ExtractionFunction extractionFunction = druidColumn.right;
  if (columnName == null) {
    return null;
  }
  if (rexNode.getKind() == SqlKind.IS_NOT_NULL) {
    return toNotDruidFilter(new JsonSelector(columnName, null, extractionFunction));
  }
  return new JsonSelector(columnName, null, extractionFunction);
}
 
Example #18
Source File: PredicateAnalyzer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * If one operand in a binary operator is a DateTime type, but the other isn't, we should not push down the predicate
 * @param call
 */
public static void checkForIncompatibleDateTimeOperands(RexCall call) {
  RelDataType op1 = call.getOperands().get(0).getType();
  RelDataType op2 = call.getOperands().get(1).getType();
  if (
      (SqlTypeFamily.DATETIME.contains(op1) && !SqlTypeFamily.DATETIME.contains(op2)) ||
      (SqlTypeFamily.DATETIME.contains(op2) && !SqlTypeFamily.DATETIME.contains(op1)) ||
      (SqlTypeFamily.DATE.contains(op1) && !SqlTypeFamily.DATE.contains(op2)) ||
      (SqlTypeFamily.DATE.contains(op2) && !SqlTypeFamily.DATE.contains(op1)) ||
      (SqlTypeFamily.TIMESTAMP.contains(op1) && !SqlTypeFamily.TIMESTAMP.contains(op2)) ||
      (SqlTypeFamily.TIMESTAMP.contains(op2) && !SqlTypeFamily.TIMESTAMP.contains(op1)) ||
      (SqlTypeFamily.TIME.contains(op1) && !SqlTypeFamily.TIME.contains(op2)) ||
      (SqlTypeFamily.TIME.contains(op2) && !SqlTypeFamily.TIME.contains(op1)))
  {
    throw new PredicateAnalyzerException("Cannot handle " + call.getKind() + " expression for _id field, " + call);
  }
}
 
Example #19
Source File: RelBuilder.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static RelFieldCollation collation(RexNode node, RelFieldCollation.Direction direction,
        RelFieldCollation.NullDirection nullDirection, List<RexNode> extraNodes) {
    switch (node.getKind()) {
    case INPUT_REF:
        return new RelFieldCollation(((RexInputRef) node).getIndex(), direction,
                Util.first(nullDirection, direction.defaultNullDirection()));
    case DESCENDING:
        return collation(((RexCall) node).getOperands().get(0), RelFieldCollation.Direction.DESCENDING,
                nullDirection, extraNodes);
    case NULLS_FIRST:
        return collation(((RexCall) node).getOperands().get(0), direction, RelFieldCollation.NullDirection.FIRST,
                extraNodes);
    case NULLS_LAST:
        return collation(((RexCall) node).getOperands().get(0), direction, RelFieldCollation.NullDirection.LAST,
                extraNodes);
    default:
        final int fieldIndex = extraNodes.size();
        extraNodes.add(node);
        return new RelFieldCollation(fieldIndex, direction,
                Util.first(nullDirection, direction.defaultNullDirection()));
    }
}
 
Example #20
Source File: ReduceDecimalsRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RexNode expandDivide(RexCall call, List<RexNode> operands) {
  RelDataType outType = call.getType();
  RexNode dividend =
      builder.makeCall(
          call.getOperator(),
          ensureType(
              real8,
              accessValue(operands.get(0))),
          ensureType(
              real8,
              accessValue(operands.get(1))));
  int scaleDifference = outType.getScale() - scaleA + scaleB;
  RexNode rescale =
      builder.makeCall(
          SqlStdOperatorTable.MULTIPLY,
          dividend,
          makeApproxScaleFactor(scaleDifference));
  return encodeValue(rescale, outType);
}
 
Example #21
Source File: SplitUpComplexExpressions.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 *  Find the list of expressions where Complex type function is at top level.
 */
private List<RexNode> findTopComplexFunc(List<RexNode> exprs) {
  final List<RexNode> topComplexFuncs = new ArrayList<>();

  for (RexNode exp : exprs) {
    if (exp instanceof RexCall) {
      RexCall call = (RexCall) exp;
      String functionName = call.getOperator().getName();

      if (funcReg.isFunctionComplexOutput(functionName) ) {
        topComplexFuncs.add(exp);
      }
    }
  }

  return topComplexFuncs;
}
 
Example #22
Source File: TestFilterFinder.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void halfTree(){
  final RexNode node =
      builder.makeCall(SqlStdOperatorTable.AND,
      builder.makeCall(SqlStdOperatorTable.EQUALS,
          builder.makeInputRef(factory.createSqlType(SqlTypeName.BIGINT), 0),
          builder.makeBigintLiteral(BigDecimal.ONE)
          ),
      builder.makeApproxLiteral(BigDecimal.ONE)
      );

  FindSimpleFilters finder = new FindSimpleFilters(builder);
  StateHolder holder = node.accept(finder);
  ImmutableList<RexCall> conditions = holder.getConditions();

  assertEquals(1, conditions.size());
  assertEquals(SqlKind.EQUALS, conditions.get(0).getKind());
  assertEquals(SqlKind.LITERAL, holder.getNode().getKind());
  assertTrue(holder.hasRemainingExpression());
}
 
Example #23
Source File: RelMdUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Returns default estimates for selectivities, in the absence of stats.
 *
 * @param predicate      predicate for which selectivity will be computed;
 *                       null means true, so gives selectity of 1.0
 * @param artificialOnly return only the selectivity contribution from
 *                       artificial nodes
 * @return estimated selectivity
 */
public static double guessSelectivity(
    RexNode predicate,
    boolean artificialOnly) {
  double sel = 1.0;
  if ((predicate == null) || predicate.isAlwaysTrue()) {
    return sel;
  }

  double artificialSel = 1.0;

  for (RexNode pred : RelOptUtil.conjunctions(predicate)) {
    if (pred.getKind() == SqlKind.IS_NOT_NULL) {
      sel *= .9;
    } else if (
        (pred instanceof RexCall)
            && (((RexCall) pred).getOperator()
            == RelMdUtil.ARTIFICIAL_SELECTIVITY_FUNC)) {
      artificialSel *= RelMdUtil.getSelectivityValue(pred);
    } else if (pred.isA(SqlKind.EQUALS)) {
      sel *= .15;
    } else if (pred.isA(SqlKind.COMPARISON)) {
      sel *= .5;
    } else {
      sel *= .25;
    }
  }

  if (artificialOnly) {
    return artificialSel;
  } else {
    return sel * artificialSel;
  }
}
 
Example #24
Source File: RelOptUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static RexCall doCollapseExpandedIsNotDistinctFromCaseExpr(final RexCall call,
    final RexBuilder rexBuilder) {
  if (call.getKind() != SqlKind.CASE || call.getOperands().size() != 5) {
    return call;
  }

  final RexNode op0 = call.getOperands().get(0);
  final RexNode op1 = call.getOperands().get(1);
  final RexNode op2 = call.getOperands().get(2);
  final RexNode op3 = call.getOperands().get(3);
  final RexNode op4 = call.getOperands().get(4);

  if (!(op0 instanceof RexCall) || !(op1 instanceof RexCall) || !(op2 instanceof RexCall)
      || !(op3 instanceof RexCall) || !(op4 instanceof RexCall)) {
    return call;
  }

  RexCall ifCall = (RexCall) op0;
  RexCall thenCall = (RexCall) op1;
  RexCall elseIfCall = (RexCall) op2;
  RexCall elseIfThenCall = (RexCall) op3;
  RexCall elseCall = (RexCall) op4;

  if (ifCall.getKind() != SqlKind.IS_NULL
      || thenCall.getKind() != SqlKind.IS_NULL
      || elseIfCall.getKind() != SqlKind.IS_NULL
      || elseIfThenCall.getKind() != SqlKind.IS_NULL
      || elseCall.getKind() != SqlKind.EQUALS) {
    return call;
  }

  if (!ifCall.equals(elseIfThenCall)
      || !thenCall.equals(elseIfCall)) {
    return call;
  }

  return doCollapseExpandedIsNotDistinctFrom(rexBuilder, call, ifCall, elseIfCall, elseCall);
}
 
Example #25
Source File: RelMdPredicates.java    From Bats with Apache License 2.0 5 votes vote down vote up
private boolean isAlwaysTrue(RexNode predicate) {
  if (predicate instanceof RexCall) {
    RexCall c = (RexCall) predicate;
    if (c.getOperator().getKind() == SqlKind.EQUALS) {
      int lPos = pos(c.getOperands().get(0));
      int rPos = pos(c.getOperands().get(1));
      return lPos != -1 && lPos == rPos;
    }
  }
  return predicate.isAlwaysTrue();
}
 
Example #26
Source File: GeodeFilter.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Translate a binary relation.
 */
private String translateMatch2(RexNode node) {
  // We currently only use equality, but inequalities on clustering keys
  // should be possible in the future
  RexNode child;
  switch (node.getKind()) {
  case EQUALS:
    return translateBinary("=", "=", (RexCall) node);
  case LESS_THAN:
    return translateBinary("<", ">", (RexCall) node);
  case LESS_THAN_OR_EQUAL:
    return translateBinary("<=", ">=", (RexCall) node);
  case GREATER_THAN:
    return translateBinary(">", "<", (RexCall) node);
  case GREATER_THAN_OR_EQUAL:
    return translateBinary(">=", "<=", (RexCall) node);
  case INPUT_REF:
    return translateBinary2("=", node, rexBuilder.makeLiteral(true));
  case NOT:
    child = ((RexCall) node).getOperands().get(0);
    if (child.getKind() == SqlKind.CAST) {
      child = ((RexCall) child).getOperands().get(0);
    }
    if (child.getKind() == SqlKind.INPUT_REF) {
      return translateBinary2("=", child, rexBuilder.makeLiteral(false));
    }
    break;
  case CAST:
    return translateMatch2(((RexCall) node).getOperands().get(0));
  default:
    break;
  }
  throw new AssertionError("Cannot translate " + node + ", kind=" + node.getKind());
}
 
Example #27
Source File: SolrFilter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private String translateComparison(RexNode node) {
  Pair<String, RexLiteral> binaryTranslated = null;
  if (((RexCall) node).getOperands().size() == 2) {
    binaryTranslated = translateBinary((RexCall) node);
  }

  switch (node.getKind()) {
    case NOT:
      return "-" + translateComparison(((RexCall) node).getOperands().get(0));
    case EQUALS:
      String terms = binaryTranslated.getValue().toString().trim();
      terms = terms.replace("'","");
      if (!terms.startsWith("(") && !terms.startsWith("[") && !terms.startsWith("{")) {
        terms = "\"" + terms + "\"";
      }

      String clause = binaryTranslated.getKey() + ":" + terms;
      this.negativeQuery = false;
      return clause;
    case NOT_EQUALS:
      return "-(" + binaryTranslated.getKey() + ":" + binaryTranslated.getValue() + ")";
    case LESS_THAN:
      this.negativeQuery = false;
      return "(" + binaryTranslated.getKey() + ": [ * TO " + binaryTranslated.getValue() + " })";
    case LESS_THAN_OR_EQUAL:
      this.negativeQuery = false;
      return "(" + binaryTranslated.getKey() + ": [ * TO " + binaryTranslated.getValue() + " ])";
    case GREATER_THAN:
      this.negativeQuery = false;
      return "(" + binaryTranslated.getKey() + ": { " + binaryTranslated.getValue() + " TO * ])";
    case GREATER_THAN_OR_EQUAL:
      this.negativeQuery = false;
      return "(" + binaryTranslated.getKey() + ": [ " + binaryTranslated.getValue() + " TO * ])";
    default:
      throw new AssertionError("cannot translate " + node);
  }
}
 
Example #28
Source File: VisitorDataContext.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static DataContext of(RelDataType rowType, RexNode rex) {
  final int size = rowType.getFieldList().size();
  final Object[] values = new Object[size];
  final List<RexNode> operands = ((RexCall) rex).getOperands();
  final RexNode firstOperand = operands.get(0);
  final RexNode secondOperand = operands.get(1);
  final Pair<Integer, ?> value = getValue(firstOperand, secondOperand);
  if (value != null) {
    int index = value.getKey();
    values[index] = value.getValue();
    return new VisitorDataContext(values);
  } else {
    return null;
  }
}
 
Example #29
Source File: DateRangeRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
boolean isExtractCall(RexNode e) {
  switch (e.getKind()) {
  case EXTRACT:
    final RexCall call = (RexCall) e;
    final RexLiteral flag = (RexLiteral) call.operands.get(0);
    final TimeUnitRange timeUnit = (TimeUnitRange) flag.getValue();
    return timeUnit == this.timeUnit;
  default:
    return false;
  }
}
 
Example #30
Source File: MongoRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns 'string' if it is a call to item['string'], null otherwise. */
static String isItem(RexCall call) {
  if (call.getOperator() != SqlStdOperatorTable.ITEM) {
    return null;
  }
  final RexNode op0 = call.operands.get(0);
  final RexNode op1 = call.operands.get(1);
  if (op0 instanceof RexInputRef
      && ((RexInputRef) op0).getIndex() == 0
      && op1 instanceof RexLiteral
      && ((RexLiteral) op1).getValue2() instanceof String) {
    return (String) ((RexLiteral) op1).getValue2();
  }
  return null;
}