org.apache.calcite.rex.RexLiteral Java Examples

The following examples show how to use org.apache.calcite.rex.RexLiteral. 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: RelMdMinRowCount.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Double getMinRowCount(Sort rel, RelMetadataQuery mq) {
  Double rowCount = mq.getMinRowCount(rel.getInput());
  if (rowCount == null) {
    rowCount = 0D;
  }
  final int offset = rel.offset == null ? 0 : RexLiteral.intValue(rel.offset);
  rowCount = Math.max(rowCount - offset, 0D);

  if (rel.fetch != null) {
    final int limit = RexLiteral.intValue(rel.fetch);
    if (limit < rowCount) {
      return (double) limit;
    }
  }
  return rowCount;
}
 
Example #2
Source File: RelMdMinRowCount.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Double getMinRowCount(EnumerableLimit rel, RelMetadataQuery mq) {
  Double rowCount = mq.getMinRowCount(rel.getInput());
  if (rowCount == null) {
    rowCount = 0D;
  }
  final int offset = rel.offset == null ? 0 : RexLiteral.intValue(rel.offset);
  rowCount = Math.max(rowCount - offset, 0D);

  if (rel.fetch != null) {
    final int limit = RexLiteral.intValue(rel.fetch);
    if (limit < rowCount) {
      return (double) limit;
    }
  }
  return rowCount;
}
 
Example #3
Source File: RelFieldTrimmer.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a project with a dummy column, to protect the parts of the system
 * that cannot handle a relational expression with no columns.
 *
 * @param fieldCount Number of fields in the original relational expression
 * @param input Trimmed input
 * @param originalRelNode Source RelNode for hint propagation (or null if no propagation needed)
 * @return Dummy project
 */
protected TrimResult dummyProject(int fieldCount, RelNode input, RelNode originalRelNode) {
  final RelOptCluster cluster = input.getCluster();
  final Mapping mapping =
      Mappings.create(MappingType.INVERSE_SURJECTION, fieldCount, 1);
  if (input.getRowType().getFieldCount() == 1) {
    // Input already has one field (and may in fact be a dummy project we
    // created for the child). We can't do better.
    return result(input, mapping);
  }
  final RexLiteral expr =
      cluster.getRexBuilder().makeExactLiteral(BigDecimal.ZERO);
  relBuilder.push(input);
  relBuilder.project(ImmutableList.of(expr), ImmutableList.of("DUMMY"));
  RelNode newProject = relBuilder.build();
  if (originalRelNode != null) {
    newProject = RelOptUtil.propagateRelHints(originalRelNode, newProject);
  }
  return result(newProject, mapping);
}
 
Example #4
Source File: TrimFunction.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public FunctionRender render(FunctionRenderer renderer, RexCall call) {
  checkArity(call, 3);

  RexNode op0 = call.getOperands().get(0);
  if (op0 instanceof RexLiteral) {
    final FunctionRender trimChar = call.getOperands().get(1).accept(renderer.getVisitor());
    final FunctionRender inputStr = call.getOperands().get(2).accept(renderer.getVisitor());
    if (TRIM_CHAR.equals(trimChar.getScript())) {
      if (((RexLiteral) op0).getValue() == SqlTrimFunction.Flag.BOTH) {
        return new FunctionRender(inputStr.getScript() + ".trim()", inputStr.getNulls());
      }
    }
  }
  throw new UnsupportedOperationException("incorrect arguments for trim function");
}
 
Example #5
Source File: OLAPValuesRel.java    From kylin with Apache License 2.0 6 votes vote down vote up
/** Creates an OLAPValuesRel. */
public static OLAPValuesRel create(RelOptCluster cluster, final RelDataType rowType,
        final ImmutableList<ImmutableList<RexLiteral>> tuples) {
    final RelMetadataQuery mq = cluster.getMetadataQuery();
    final RelTraitSet traitSet = cluster.traitSetOf(OLAPRel.CONVENTION)
            .replaceIfs(RelCollationTraitDef.INSTANCE, new Supplier<List<RelCollation>>() {
                public List<RelCollation> get() {
                    return RelMdCollation.values(mq, rowType, tuples);
                }
            }).replaceIf(RelDistributionTraitDef.INSTANCE, new Supplier<RelDistribution>() {
                public RelDistribution get() {
                    return RelMdDistribution.values(rowType, tuples);
                }
            });
    return new OLAPValuesRel(cluster, rowType, tuples, traitSet);
}
 
Example #6
Source File: PrelUtil.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public PathSegment visitCall(RexCall call) {
  if ("ITEM".equals(call.getOperator().getName())) {
    PathSegment mapOrArray = call.operands.get(0).accept(this);
    if (mapOrArray != null) {
      if (call.operands.get(1) instanceof RexLiteral) {
        return mapOrArray.cloneWithNewChild(convertLiteral((RexLiteral) call.operands.get(1)));
      }
      return mapOrArray;
    }
  } else {
    for (RexNode operand : call.operands) {
      addColumn(operand.accept(this));
    }
  }
  return null;
}
 
Example #7
Source File: TupleFilterVisitor.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Override
public TupleFilter visitLiteral(RexLiteral literal) {
    String strValue = null;
    Object literalValue = literal.getValue();
    if (literalValue instanceof NlsString) {
        strValue = ((NlsString) literalValue).getValue();
    } else if (literalValue instanceof GregorianCalendar) {
        GregorianCalendar g = (GregorianCalendar) literalValue;
        strValue = Long.toString(g.getTimeInMillis());
    } else if (literalValue instanceof TimeUnitRange) {
        // Extract(x from y) in where clause
        strValue = ((TimeUnitRange) literalValue).name();
    } else if (literalValue == null) {
        strValue = null;
    } else {
        strValue = literalValue.toString();
    }
    TupleFilter filter = new ConstantTupleFilter(strValue);
    return filter;
}
 
Example #8
Source File: ValuesNode.java    From calcite with Apache License 2.0 6 votes vote down vote up
private ImmutableList<Row> createRows(Compiler compiler,
    ImmutableList<ImmutableList<RexLiteral>> tuples) {
  final List<RexNode> nodes = new ArrayList<>();
  for (ImmutableList<RexLiteral> tuple : tuples) {
    nodes.addAll(tuple);
  }
  final Scalar scalar = compiler.compile(nodes, null);
  final Object[] values = new Object[nodes.size()];
  final Context context = compiler.createContext();
  scalar.execute(context, values);
  final ImmutableList.Builder<Row> rows = ImmutableList.builder();
  Object[] subValues = new Object[fieldCount];
  for (int i = 0; i < values.length; i += fieldCount) {
    System.arraycopy(values, i, subValues, 0, fieldCount);
    rows.add(Row.asCopy(subValues));
  }
  return rows.build();
}
 
Example #9
Source File: DruidRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Sort sort = call.rel(0);
  final DruidQuery query = call.rel(1);
  if (!DruidQuery.isValidSignature(query.signature() + 'l')) {
    return;
  }
  // Either it is:
  // - a pure limit above a query of type scan
  // - a sort and limit on a dimension/metric part of the druid group by query
  if (sort.offset != null && RexLiteral.intValue(sort.offset) != 0) {
    // offset not supported by Druid
    return;
  }
  if (query.getQueryType() == QueryType.SCAN && !RelOptUtil.isPureLimit(sort)) {
    return;
  }

  final RelNode newSort = sort
      .copy(sort.getTraitSet(), ImmutableList.of(Util.last(query.rels)));
  call.transformTo(DruidQuery.extendQuery(query, newSort));
}
 
Example #10
Source File: RexTransformerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-814">[CALCITE-814]
 * RexBuilder reverses precision and scale of DECIMAL literal</a>
 * and
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1344">[CALCITE-1344]
 * Incorrect inferred precision when BigDecimal value is less than 1</a>. */
@Test void testExactLiteral() {
  final RexLiteral literal =
      rexBuilder.makeExactLiteral(new BigDecimal("-1234.56"));
  assertThat(literal.getType().getFullTypeString(),
      is("DECIMAL(6, 2) NOT NULL"));
  assertThat(literal.getValue().toString(), is("-1234.56"));

  final RexLiteral literal2 =
      rexBuilder.makeExactLiteral(new BigDecimal("1234.56"));
  assertThat(literal2.getType().getFullTypeString(),
      is("DECIMAL(6, 2) NOT NULL"));
  assertThat(literal2.getValue().toString(), is("1234.56"));

  final RexLiteral literal3 =
      rexBuilder.makeExactLiteral(new BigDecimal("0.0123456"));
  assertThat(literal3.getType().getFullTypeString(),
      is("DECIMAL(8, 7) NOT NULL"));
  assertThat(literal3.getValue().toString(), is("0.0123456"));

  final RexLiteral literal4 =
      rexBuilder.makeExactLiteral(new BigDecimal("0.01234560"));
  assertThat(literal4.getType().getFullTypeString(),
      is("DECIMAL(9, 8) NOT NULL"));
  assertThat(literal4.getValue().toString(), is("0.01234560"));
}
 
Example #11
Source File: ElasticsearchSort.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void implement(Implementor implementor) {
  implementor.visitChild(0, getInput());
  final List<RelDataTypeField> fields = getRowType().getFieldList();

  for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
    final String name = fields.get(fieldCollation.getFieldIndex()).getName();
    final String rawName = implementor.expressionItemMap.getOrDefault(name, name);
    implementor.addSort(rawName, fieldCollation.getDirection());
  }

  if (offset != null) {
    implementor.offset(((RexLiteral) offset).getValueAs(Long.class));
  }

  if (fetch != null) {
    implementor.fetch(((RexLiteral) fetch).getValueAs(Long.class));
  }
}
 
Example #12
Source File: LimitPrel.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public PhysicalOperator getPhysicalOperator(PhysicalPlanCreator creator) throws IOException {
  Prel child = (Prel) this.getInput();

  PhysicalOperator childPOP = child.getPhysicalOperator(creator);

  // First offset to include into results (inclusive). Null implies it is starting from offset 0
  int first = offset != null ? Math.max(0, RexLiteral.intValue(offset)) : 0;

  // Last offset to stop including into results (exclusive), translating fetch row counts into an offset.
  // Null value implies including entire remaining result set from first offset
  Integer last = fetch != null ? Math.max(0, RexLiteral.intValue(fetch)) + first : null;

  Limit limit;
  if (isPartitioned) {
    limit = new PartitionLimit(childPOP, first, last, DrillRelOptUtil.IMPLICIT_COLUMN);
  } else {
    limit = new Limit(childPOP, first, last);
  }
  return creator.addMetadata(this, limit);
}
 
Example #13
Source File: TestValuesRel.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testNumericValuesRelRowTypeAdjustment() {
  final int INListLength = 20;

  // Build RowType & Tuples
  RelDataTypeField relDataType = new RelDataTypeFieldImpl("ROW_VALUE", 0, new BasicSqlType(RelDataTypeSystemImpl.REL_DATA_TYPE_SYSTEM, SqlTypeName.ANY));
  RelDataType rowType = new RelRecordType(StructKind.FULLY_QUALIFIED, Arrays.asList(relDataType));
  ImmutableList.Builder<ImmutableList<RexLiteral>> tuples = new ImmutableList.Builder<>();
  for (int i = 0; i < INListLength; i++) {
    tuples.add(new ImmutableList.Builder<RexLiteral>().add(new RexBuilder(typeFactory).makeExactLiteral(new BigDecimal(i))).build());
  }

  // Check original types.
  assertEquals(1, rowType.getFieldCount());
  assertEquals(SqlTypeName.ANY, rowType.getFieldList().get(0).getType().getSqlTypeName());

  // Construct ValuesRel
  final ValuesRel valuesRel = new ValuesRel(cluster, rowType, tuples.build(), traits);

  // Check the adjusted types.
  RelDataType adjustedRowType = valuesRel.getRowType();
  assertEquals(1, adjustedRowType.getFieldCount());
  assertEquals(SqlTypeName.INTEGER, adjustedRowType.getFieldList().get(0).getType().getSqlTypeName());
}
 
Example #14
Source File: ValuesRel.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private static JsonNode convertToJsonNode(RelDataType rowType, ImmutableList<ImmutableList<RexLiteral>> tuples) throws IOException{
  TokenBuffer out = new TokenBuffer(MAPPER.getFactory().getCodec(), false);
  JsonOutput json = new ExtendedJsonOutput(out);
  json.writeStartArray();
  String[] fields = rowType.getFieldNames().toArray(new String[rowType.getFieldCount()]);

  for(List<RexLiteral> row : tuples){
    json.writeStartObject();
    int i =0;
    for(RexLiteral field : row){
      json.writeFieldName(fields[i]);
      writeLiteral(field, json);
      i++;
    }
    json.writeEndObject();
  }
  json.writeEndArray();
  json.flush();
  return out.asParser().readValueAsTree();
}
 
Example #15
Source File: WindowPrel.java    From Bats with Apache License 2.0 6 votes vote down vote up
protected LogicalExpression toDrill(AggregateCall call, List<String> fn) {
  DrillParseContext context = new DrillParseContext(PrelUtil.getSettings(getCluster()));

  List<LogicalExpression> args = Lists.newArrayList();
  for (Integer i : call.getArgList()) {
    final int indexInConstants = i - fn.size();
    if (i < fn.size()) {
      args.add(new FieldReference(fn.get(i)));
    } else {
      final RexLiteral constant = constants.get(indexInConstants);
      LogicalExpression expr = DrillOptiq.toDrill(context, getInput(), constant);
      args.add(expr);
    }
  }

  // for count(1).
  if (args.isEmpty()) {
    args.add(new ValueExpressions.LongExpression(1l));
  }

  return new FunctionCall(call.getAggregation().getName().toLowerCase(), args, ExpressionPosition.UNKNOWN);
}
 
Example #16
Source File: GeodeFilter.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the value of a literal to a string.
 *
 * @param literal Literal to translate
 * @return String representation of the literal
 */
private static String literalValue(RexLiteral literal) {
  final Comparable valueComparable = literal.getValueAs(Comparable.class);

  switch (literal.getTypeName()) {
  case TIMESTAMP:
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
    assert valueComparable instanceof TimestampString;
    return "TIMESTAMP '" + valueComparable.toString() + "'";
  case DATE:
    assert valueComparable instanceof DateString;
    return "DATE '" + valueComparable.toString() + "'";
  case TIME:
  case TIME_WITH_LOCAL_TIME_ZONE:
    assert valueComparable instanceof TimeString;
    return "TIME '" + valueComparable.toString() + "'";
  default:
    return String.valueOf(literal.getValue3());
  }
}
 
Example #17
Source File: RelMetadataTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private void addRow(ImmutableList.Builder<ImmutableList<RexLiteral>> builder,
    RexBuilder rexBuilder, Object... values) {
  ImmutableList.Builder<RexLiteral> b = ImmutableList.builder();
  final RelDataType varcharType =
      rexBuilder.getTypeFactory().createSqlType(SqlTypeName.VARCHAR);
  for (Object value : values) {
    final RexLiteral literal;
    if (value == null) {
      literal = rexBuilder.makeNullLiteral(varcharType);
    } else if (value instanceof Integer) {
      literal = rexBuilder.makeExactLiteral(
          BigDecimal.valueOf((Integer) value));
    } else {
      literal = rexBuilder.makeLiteral((String) value);
    }
    b.add(literal);
  }
  builder.add(b.build());
}
 
Example #18
Source File: SparkRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
SparkValues(
    RelOptCluster cluster,
    RelDataType rowType,
    ImmutableList<ImmutableList<RexLiteral>> tuples,
    RelTraitSet traitSet) {
  super(cluster, rowType, tuples, traitSet);
}
 
Example #19
Source File: LogicalValues.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Creates a LogicalValues. */
public static LogicalValues create(RelOptCluster cluster,
    final RelDataType rowType,
    final ImmutableList<ImmutableList<RexLiteral>> tuples) {
  final RelMetadataQuery mq = cluster.getMetadataQuery();
  final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE)
      .replaceIfs(RelCollationTraitDef.INSTANCE,
          () -> RelMdCollation.values(mq, rowType, tuples));
  return new LogicalValues(cluster, traitSet, rowType, tuples);
}
 
Example #20
Source File: TestIndexBasedPruning.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name = "{index}: Doing index pruning on {0}. Following condition is expected to be passed: {1}")
public static Iterable<Object[]> getTestCases() {
  RexInputRef dateCol = REX_BUILDER.makeInputRef(TYPE_FACTORY.createTypeWithNullability(TYPE_FACTORY.createSqlType(SqlTypeName.DATE), true),0);
  RexNode dateLiteral = REX_BUILDER.makeDateLiteral(new DateString("2010-01-01"));
  RexInputRef intCol = REX_BUILDER.makeInputRef(TYPE_FACTORY.createTypeWithNullability(TYPE_FACTORY.createSqlType(SqlTypeName.INTEGER), true),1);
  RexNode intLiteral = REX_BUILDER.makeLiteral(2, TYPE_FACTORY.createSqlType(SqlTypeName.INTEGER), false);
  RexNode castDate = REX_BUILDER.makeCast(dateLiteral.getType(), intLiteral);

  long longVal = ((GregorianCalendar) ((RexLiteral) dateLiteral).getValue()).getTimeInMillis();
  SearchTypes.SearchQuery q1 = SearchQueryUtils.and(SearchQueryUtils.newRangeLong("$D$::LONG-date_col", longVal, longVal, true, true));
  RexNode cond1 = REX_BUILDER.makeCall(EQUALS, dateCol, dateLiteral);

  int intVal = ((BigDecimal) ((RexLiteral) intLiteral).getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
  SearchTypes.SearchQuery q2 = SearchQueryUtils.and(SearchQueryUtils.newRangeInt("$D$::INTEGER-int_col", intVal, intVal, true, true));
  RexNode cond2 = REX_BUILDER.makeCall(EQUALS, intCol, intLiteral);

  RexNode cond3 = REX_BUILDER.makeCall(EQUALS, dateCol, castDate);

  RexNode cond4 = REX_BUILDER.makeCall(GREATER_THAN, dateCol, castDate);

  // equivalent to where $0 = "2010-01-01" and $1 = 1 => both filters can be index pruned
  RexNode testCondition1 = REX_BUILDER.makeCall(AND, cond1, cond2);

  // equivalent to where $0 = CAST(1 as DATE) and $1 = 1 => only the second filter can be index pruned
  RexNode testCondition2 = REX_BUILDER.makeCall(AND, cond3, cond2);

  // equivalent to where $0 = CAST(1 as DATE) and $0 > CAST(1 as DATE) => none of them can be index pruned
  RexNode testCondition3 = REX_BUILDER.makeCall(AND, cond3, cond4);

  return ImmutableList.<Object[]>builder()
      .add(new Object[] { testCondition1, SearchQueryUtils.and(ImmutableList.of(q2, q1)) })
      .add(new Object[] { testCondition2, SearchQueryUtils.and(ImmutableList.of(q2)) })
      .add(new Object[] { testCondition3, null })
      .build();
}
 
Example #21
Source File: LimitRelBase.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public double estimateRowCount(RelMetadataQuery mq) {
  int off = offset != null ? RexLiteral.intValue(offset) : 0 ;

  if (fetch == null) {
    return mq.getRowCount(getInput()) - off;
  } else {
    int f = RexLiteral.intValue(fetch);
    return off + f;
  }
}
 
Example #22
Source File: SchemaField.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public SchemaPath visitCall(RexCall call) {
  if(call.getOperator().getSyntax() != SqlSyntax.SPECIAL || call.getOperator() != SqlStdOperatorTable.ITEM){
    return null;
  }
  LogicalExpression logExpr = call.getOperands().get(0).accept(this);

  if (!(logExpr instanceof SchemaPath)) {
    return (SchemaPath) logExpr;
  }

  SchemaPath left = (SchemaPath) logExpr;
  final RexLiteral literal = (RexLiteral) call.getOperands().get(1);
  switch(literal.getTypeName()){
  case DECIMAL:
  case INTEGER:
    switch(indexMode){
    case ALLOW:
      return left.getChild(((BigDecimal)literal.getValue()).intValue());
    case SKIP:
      return left;
    case DISALLOW:
    default:
      return null;
    }

  case CHAR:
  case VARCHAR:
    return left.getChild(literal.getValue2().toString());
  default:
    // fall through
  }

  return null;
}
 
Example #23
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;
}
 
Example #24
Source File: ProjectAnalyzer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionRender visitLiteral(RexLiteral literal) {
  if (!renderer.isScriptsEnabled()) {
    throw UserException.permissionError().message("Scripts must be enabled to allow for complex expression pushdowns.").build(logger);
  }
  requiresScripts = true;
  switch (literal.getType().getSqlTypeName()) {
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      throw UserException.unsupportedError().message("Intervals are not allowed for complex expression pushdowns.").build(logger);

    case BIGINT:
      return new FunctionRender(literal.toString() + "L", ImmutableList.<NullReference>of());

    case DOUBLE:
      return new FunctionRender(literal.toString() + "D", ImmutableList.<NullReference>of());

    case DATE:
    case TIME:
    case TIMESTAMP:
      return new FunctionRender("Instant.ofEpochMilli(" + Long.toString(((Calendar) literal.getValue()).getTimeInMillis()) + "L)", ImmutableList.of());
    default:
      return new FunctionRender(literal.toString(), ImmutableList.<NullReference>of());
  }
}
 
Example #25
Source File: ElasticsearchFilter.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
private boolean translateBinary(SqlKind operator, RexNode left, RexNode right) {
    if (right.getKind() != SqlKind.LITERAL) return false;
    final RexLiteral rightLiteral = (RexLiteral) right;
    switch (left.getKind())
    {
        case INPUT_REF:
            String name = getRowType().getFieldNames().get(((RexInputRef) left).getIndex());
            translateOp(operator, name, rightLiteral);
            return true;
        case CAST:
            return translateBinary(operator, ((RexCall) left).operands.get(0), right);
        default: return false;
    }
}
 
Example #26
Source File: SubQueryDecorrelator.java    From flink with Apache License 2.0 5 votes vote down vote up
/** Returns a literal output field, or null if it is not literal. */
private static RexLiteral projectedLiteral(RelNode rel, int i) {
	if (rel instanceof Project) {
		final Project project = (Project) rel;
		final RexNode node = project.getProjects().get(i);
		if (node instanceof RexLiteral) {
			return (RexLiteral) node;
		}
	}
	return null;
}
 
Example #27
Source File: SqlImplementor.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public SqlNode toSql(RexProgram program, RexNode rex) {
    if (rex.getKind() == SqlKind.LITERAL) {
        final RexLiteral literal = (RexLiteral) rex;
        if (literal.getTypeName().getFamily() == SqlTypeFamily.CHARACTER) {
            return new SqlIdentifier(RexLiteral.stringValue(literal), POS);
        }
    }
    return super.toSql(program, rex);
}
 
Example #28
Source File: RexUtil.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static boolean isConstant(RexNode rexNode) {
    if (rexNode instanceof RexLiteral) {
        return true;
    }

    if (rexNode instanceof RexCall && SqlKind.CAST.equals(rexNode.getKind())
            && ((RexCall) rexNode).getOperands().get(0) instanceof RexLiteral) {
        return true;
    }

    return false;
}
 
Example #29
Source File: CeilOperatorConversion.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override public String toDruidExpression(RexNode rexNode, RelDataType rowType,
    DruidQuery query) {
  final RexCall call = (RexCall) rexNode;
  final RexNode arg = call.getOperands().get(0);
  final String druidExpression = DruidExpressions.toDruidExpression(
      arg,
      rowType,
      query);
  if (druidExpression == null) {
    return null;
  } else if (call.getOperands().size() == 1) {
    // case CEIL(expr)
    return  DruidQuery.format("ceil(%s)", druidExpression);
  } else if (call.getOperands().size() == 2) {
    // CEIL(expr TO timeUnit)
    final RexLiteral flag = (RexLiteral) call.getOperands().get(1);
    final TimeUnitRange timeUnit = (TimeUnitRange) flag.getValue();
    final Granularity.Type type = DruidDateTimeUtils.toDruidGranularity(timeUnit);
    if (type == null) {
      // Unknown Granularity bail out
      return null;
    }
    String isoPeriodFormat = DruidDateTimeUtils.toISOPeriodFormat(type);
    if (isoPeriodFormat == null) {
      return null;
    }
    final TimeZone tz;
    if (arg.getType().getSqlTypeName() == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) {
      tz = TimeZone.getTimeZone(query.getConnectionConfig().timeZone());
    } else {
      tz = DateTimeUtils.UTC_ZONE;
    }
    return DruidExpressions.applyTimestampCeil(
        druidExpression, isoPeriodFormat, "", tz);
  } else {
    return null;
  }
}
 
Example #30
Source File: MongoSort.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void implement(Implementor implementor) {
  implementor.visitChild(0, getInput());
  if (!collation.getFieldCollations().isEmpty()) {
    final List<String> keys = new ArrayList<>();
    final List<RelDataTypeField> fields = getRowType().getFieldList();
    for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
      final String name =
          fields.get(fieldCollation.getFieldIndex()).getName();
      keys.add(name + ": " + direction(fieldCollation));
      if (false) {
        // TODO: NULLS FIRST and NULLS LAST
        switch (fieldCollation.nullDirection) {
        case FIRST:
          break;
        case LAST:
          break;
        }
      }
    }
    implementor.add(null,
        "{$sort: " + Util.toString(keys, "{", ", ", "}") + "}");
  }
  if (offset != null) {
    implementor.add(null,
        "{$skip: " + ((RexLiteral) offset).getValue() + "}");
  }
  if (fetch != null) {
    implementor.add(null,
        "{$limit: " + ((RexLiteral) fetch).getValue() + "}");
  }
}