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: 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 #2
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 #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: 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 #5
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 #6
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 #7
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 #8
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 #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: 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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: RelOptUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitCall(RexCall call) {
    if (call.getOperator() == RexBuilder.GET_OPERATOR) {
        RexLiteral literal = (RexLiteral) call.getOperands().get(1);
        extraFields.add(new RelDataTypeFieldImpl((String) literal.getValue2(), -1, call.getType()));
    }
    return super.visitCall(call);
}
 
Example #19
Source File: SimpleRexRemap.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static PathSegment convertLiteral(RexLiteral literal) {
    switch (literal.getType().getSqlTypeName()) {
    case CHAR:
        return new PathSegment.NameSegment(RexLiteral.stringValue(literal));
    case INTEGER:
        return new PathSegment.ArraySegment(RexLiteral.intValue(literal));
    default:
        return null;
    }
}
 
Example #20
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() + "}");
  }
}
 
Example #21
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 #22
Source File: WindowPrel.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static WindowPrel create(RelOptCluster cluster,
                  RelTraitSet traitSet,
                  RelNode child,
                  List<RexLiteral> constants,
                  RelDataType rowType,
                  Group window) {
  final RelTraitSet traits = adjustTraits(cluster, child, Collections.singletonList(window), traitSet)
      // At first glance, Dremio window operator does not preserve distribution
      .replaceIf(DistributionTraitDef.INSTANCE, () -> DistributionTrait.DEFAULT);
  return new WindowPrel(cluster, traits, child, constants, rowType, window);
}
 
Example #23
Source File: RelBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
private ImmutableList<ImmutableList<RexLiteral>> tupleList(int columnCount, Object[] values) {
    final ImmutableList.Builder<ImmutableList<RexLiteral>> listBuilder = ImmutableList.builder();
    final List<RexLiteral> valueList = new ArrayList<>();
    for (int i = 0; i < values.length; i++) {
        Object value = values[i];
        valueList.add((RexLiteral) literal(value));
        if ((i + 1) % columnCount == 0) {
            listBuilder.add(ImmutableList.copyOf(valueList));
            valueList.clear();
        }
    }
    return listBuilder.build();
}
 
Example #24
Source File: TimeExtractionFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the RexCall contains a valid FLOOR unit that we can
 * serialize to Druid.
 *
 * @param rexNode Extract expression
 *
 * @return true if the extract unit is valid
 */
public static boolean isValidTimeFloor(RexNode rexNode) {
  if (rexNode.getKind() != SqlKind.FLOOR) {
    return false;
  }
  final RexCall call = (RexCall) rexNode;
  if (call.operands.size() != 2) {
    return false;
  }
  final RexLiteral flag = (RexLiteral) call.operands.get(1);
  final TimeUnitRange timeUnit = (TimeUnitRange) flag.getValue();
  return timeUnit != null && VALID_TIME_FLOOR.contains(timeUnit);
}
 
Example #25
Source File: DruidDateTimeUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Infers granularity from a time unit.
 * It supports {@code FLOOR(<time> TO <timeunit>)}
 * and {@code EXTRACT(<timeunit> FROM <time>)}.
 * Returns null if it cannot be inferred.
 *
 * @param node the Rex node
 * @return the granularity, or null if it cannot be inferred
 */
@Nullable
public static Granularity extractGranularity(RexNode node, String timeZone) {
  final int valueIndex;
  final int flagIndex;

  if (TimeExtractionFunction.isValidTimeExtract(node)) {
    flagIndex = 0;
    valueIndex = 1;
  } else if (TimeExtractionFunction.isValidTimeFloor(node)) {
    valueIndex = 0;
    flagIndex = 1;
  } else {
    // We can only infer granularity from floor and extract.
    return null;
  }
  final RexCall call = (RexCall) node;
  final RexNode value = call.operands.get(valueIndex);
  final RexLiteral flag = (RexLiteral) call.operands.get(flagIndex);
  final TimeUnitRange timeUnit = (TimeUnitRange) flag.getValue();

  final RelDataType valueType = value.getType();
  if (valueType.getSqlTypeName() == SqlTypeName.DATE
      || valueType.getSqlTypeName() == SqlTypeName.TIMESTAMP) {
    // We use 'UTC' for date/timestamp type as Druid needs timezone information
    return Granularities.createGranularity(timeUnit, "UTC");
  } else if (valueType.getSqlTypeName() == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) {
    return Granularities.createGranularity(timeUnit, timeZone);
  }
  // Type not recognized
  return null;
}
 
Example #26
Source File: RelOptUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Decomposes the WHERE clause of a view into predicates that constraint
 * a column to a particular value.
 *
 * <p>This method is key to the validation of a modifiable view. Columns that
 * are constrained to a single value can be omitted from the
 * SELECT clause of a modifiable view.
 *
 * @param projectMap Mapping from column ordinal to the expression that
 * populate that column, to be populated by this method
 * @param filters List of remaining filters, to be populated by this method
 * @param constraint Constraint to be analyzed
 */
public static void inferViewPredicates(Map<Integer, RexNode> projectMap, List<RexNode> filters,
        RexNode constraint) {
    for (RexNode node : conjunctions(constraint)) {
        switch (node.getKind()) {
        case EQUALS:
            final List<RexNode> operands = ((RexCall) node).getOperands();
            RexNode o0 = operands.get(0);
            RexNode o1 = operands.get(1);
            if (o0 instanceof RexLiteral) {
                o0 = operands.get(1);
                o1 = operands.get(0);
            }
            if (o0.getKind() == SqlKind.CAST) {
                o0 = ((RexCall) o0).getOperands().get(0);
            }
            if (o0 instanceof RexInputRef && o1 instanceof RexLiteral) {
                final int index = ((RexInputRef) o0).getIndex();
                if (projectMap.get(index) == null) {
                    projectMap.put(index, o1);
                    continue;
                }
            }
        }
        filters.add(node);
    }
}
 
Example #27
Source File: SplunkPushDownRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
private String toString(boolean like, RexLiteral literal) {
  String value = null;
  SqlTypeName litSqlType = literal.getTypeName();
  if (SqlTypeName.NUMERIC_TYPES.contains(litSqlType)) {
    value = literal.getValue().toString();
  } else if (litSqlType == SqlTypeName.CHAR) {
    value = ((NlsString) literal.getValue()).getValue();
    if (like) {
      value = value.replace("%", "*");
    }
    value = searchEscape(value);
  }
  return value;
}
 
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: RelMdCollation.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Helper method to determine a
 * {@link org.apache.calcite.rel.core.Values}'s collation.
 *
 * <p>We actually under-report the collations. A Values with 0 or 1 rows - an
 * edge case, but legitimate and very common - is ordered by every permutation
 * of every subset of the columns.
 *
 * <p>So, our algorithm aims to:<ul>
 *   <li>produce at most N collations (where N is the number of columns);
 *   <li>make each collation as long as possible;
 *   <li>do not repeat combinations already emitted -
 *       if we've emitted {@code (a, b)} do not later emit {@code (b, a)};
 *   <li>probe the actual values and make sure that each collation is
 *      consistent with the data
 * </ul>
 *
 * <p>So, for an empty Values with 4 columns, we would emit
 * {@code (a, b, c, d), (b, c, d), (c, d), (d)}. */
public static List<RelCollation> values(RelMetadataQuery mq,
    RelDataType rowType, ImmutableList<ImmutableList<RexLiteral>> tuples) {
  Util.discard(mq); // for future use
  final List<RelCollation> list = new ArrayList<>();
  final int n = rowType.getFieldCount();
  final List<Pair<RelFieldCollation, Ordering<List<RexLiteral>>>> pairs =
      new ArrayList<>();
outer:
  for (int i = 0; i < n; i++) {
    pairs.clear();
    for (int j = i; j < n; j++) {
      final RelFieldCollation fieldCollation = new RelFieldCollation(j);
      Ordering<List<RexLiteral>> comparator = comparator(fieldCollation);
      Ordering<List<RexLiteral>> ordering;
      if (pairs.isEmpty()) {
        ordering = comparator;
      } else {
        ordering = Util.last(pairs).right.compound(comparator);
      }
      pairs.add(Pair.of(fieldCollation, ordering));
      if (!ordering.isOrdered(tuples)) {
        if (j == i) {
          continue outer;
        }
        pairs.remove(pairs.size() - 1);
      }
    }
    if (!pairs.isEmpty()) {
      list.add(RelCollations.of(Pair.left(pairs)));
    }
  }
  return list;
}
 
Example #30
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);
}