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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
Source File: RexToTestCodeShuttle.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public String visitCall(RexCall call) {
  SqlOperator operator = call.getOperator();
  String method = OP_METHODS.get(operator);

  StringBuilder sb = new StringBuilder();
  if (method != null) {
    sb.append(method);
    sb.append('(');
  } else {
    sb.append("rexBuilder.makeCall(");
    sb.append("SqlStdOperatorTable.");
    sb.append(operator.getName().replace(' ', '_'));
    sb.append(", ");
  }
  List<RexNode> operands = call.getOperands();
  for (int i = 0; i < operands.size(); i++) {
    RexNode operand = operands.get(i);
    if (i > 0) {
      sb.append(", ");
    }
    sb.append(operand.accept(this));
  }
  if (operator.kind == SqlKind.CAST) {
    sb.append(", t");
    appendSqlType(sb, call.getType());
    sb.append('(');
    if (call.getType().isNullable()) {
      sb.append("true");
    }
    sb.append(')');
  }
  sb.append(')');
  return sb.toString();
}
 
Example #24
Source File: RelOptUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Decomposes a predicate into a list of expressions that are AND'ed
 * together.
 *
 * @param rexPredicate predicate to be analyzed
 * @param rexList      list of decomposed RexNodes
 */
public static void decomposeConjunction(
    RexNode rexPredicate,
    List<RexNode> rexList) {
  if (rexPredicate == null || rexPredicate.isAlwaysTrue()) {
    return;
  }
  if (rexPredicate.isA(SqlKind.AND)) {
    for (RexNode operand : ((RexCall) rexPredicate).getOperands()) {
      decomposeConjunction(operand, rexList);
    }
  } else {
    rexList.add(rexPredicate);
  }
}
 
Example #25
Source File: RexImplicationChecker.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static RexNode removeCast(RexNode inputRef) {
  if (inputRef instanceof RexCall) {
    final RexCall castedRef = (RexCall) inputRef;
    final SqlOperator operator = castedRef.getOperator();
    if (operator instanceof SqlCastFunction) {
      inputRef = castedRef.getOperands().get(0);
    }
  }
  return inputRef;
}
 
Example #26
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override Expression implementSafe(final RexToLixTranslator translator,
    final RexCall call, final List<Expression> argValueList) {
  final SqlOperator op = call.getOperator();
  final Expression root = translator.getRoot();
  if (op == CURRENT_USER
      || op == SESSION_USER
      || op == USER) {
    return Expressions.call(BuiltInMethod.USER.method, root);
  } else if (op == SYSTEM_USER) {
    return Expressions.call(BuiltInMethod.SYSTEM_USER.method, root);
  } else if (op == CURRENT_PATH
      || op == CURRENT_ROLE
      || op == CURRENT_CATALOG) {
    // By default, the CURRENT_ROLE and CURRENT_CATALOG functions return the
    // empty string because a role or a catalog has to be set explicitly.
    return Expressions.constant("");
  } else if (op == CURRENT_TIMESTAMP) {
    return Expressions.call(BuiltInMethod.CURRENT_TIMESTAMP.method, root);
  } else if (op == CURRENT_TIME) {
    return Expressions.call(BuiltInMethod.CURRENT_TIME.method, root);
  } else if (op == CURRENT_DATE) {
    return Expressions.call(BuiltInMethod.CURRENT_DATE.method, root);
  } else if (op == LOCALTIMESTAMP) {
    return Expressions.call(BuiltInMethod.LOCAL_TIMESTAMP.method, root);
  } else if (op == LOCALTIME) {
    return Expressions.call(BuiltInMethod.LOCAL_TIME.method, root);
  } else {
    throw new AssertionError("unknown function " + op);
  }
}
 
Example #27
Source File: ProjectPrel.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Whether this Project requires a final column re-ordering. Returns False for all cases except when
 * convert_fromjson function is present.  For convert_fromjson function, the Project operator at
 * run-time produces an output schema with convert_fromjson expr appended to the end of the schema.
 * We need a final column re-ordering to ensure the correct column order.
*/
@Override
public boolean needsFinalColumnReordering() {
  for (RexNode expr : this.exps) {
    // TODO: a convert_fromjson nested within other convert functions currently does not work.
    // When it is supported, we should enhance this check by using a visitor to find the nested function.
    if (expr.getKind() == SqlKind.OTHER_FUNCTION &&
        expr instanceof RexCall &&
        ((RexCall) expr).getOperator().getName().equalsIgnoreCase("CONVERT_FROMJSON")) {
      return true;
    }
  }
  return false;
}
 
Example #28
Source File: NaryOperatorConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override public String toDruidExpression(RexNode rexNode, RelDataType rowType,
    DruidQuery druidQuery) {
  final RexCall call = (RexCall) rexNode;
  final List<String> druidExpressions = DruidExpressions.toDruidExpressions(
      druidQuery, rowType,
      call.getOperands());
  if (druidExpressions == null) {
    return null;
  }
  return DruidExpressions.nAryOperatorCall(druidOperatorName, druidExpressions);
}
 
Example #29
Source File: SqlImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Removes cast from string.
 *
 * <p>For example, {@code x > CAST('2015-01-07' AS DATE)}
 * becomes {@code x > '2015-01-07'}.
 */
private static RexNode stripCastFromString(RexNode node, SqlDialect dialect) {
  switch (node.getKind()) {
  case EQUALS:
  case IS_NOT_DISTINCT_FROM:
  case NOT_EQUALS:
  case GREATER_THAN:
  case GREATER_THAN_OR_EQUAL:
  case LESS_THAN:
  case LESS_THAN_OR_EQUAL:
    final RexCall call = (RexCall) node;
    final RexNode o0 = call.operands.get(0);
    final RexNode o1 = call.operands.get(1);
    if (o0.getKind() == SqlKind.CAST
        && o1.getKind() != SqlKind.CAST) {
      if (!dialect.supportsImplicitTypeCoercion((RexCall) o0)) {
        // If the dialect does not support implicit type coercion,
        // we definitely can not strip the cast.
        return node;
      }
      final RexNode o0b = ((RexCall) o0).getOperands().get(0);
      return call.clone(call.getType(), ImmutableList.of(o0b, o1));
    }
    if (o1.getKind() == SqlKind.CAST
        && o0.getKind() != SqlKind.CAST) {
      if (!dialect.supportsImplicitTypeCoercion((RexCall) o1)) {
        return node;
      }
      final RexNode o1b = ((RexCall) o1).getOperands().get(0);
      return call.clone(call.getType(), ImmutableList.of(o0, o1b));
    }
  }
  return node;
}
 
Example #30
Source File: MongoFilter.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Translates a call to a binary operator, reversing arguments if
 * necessary. */
private Void translateBinary(String op, String rop, RexCall call) {
  final RexNode left = call.operands.get(0);
  final RexNode right = call.operands.get(1);
  boolean b = translateBinary2(op, left, right);
  if (b) {
    return null;
  }
  b = translateBinary2(rop, right, left);
  if (b) {
    return null;
  }
  throw new AssertionError("cannot translate op " + op + " call " + call);
}