Java Code Examples for org.apache.calcite.util.DateString

The following examples show how to use org.apache.calcite.util.DateString. These examples are extracted from open source projects. 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 Project: Bats   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private RexLiteral dateTimeLiteral(RexBuilder rexBuilder, Calendar calendar, RexNode operand) {
    final TimestampString ts;
    final int p;
    switch (operand.getType().getSqlTypeName()) {
    case TIMESTAMP:
        ts = TimestampString.fromCalendarFields(calendar);
        p = operand.getType().getPrecision();
        return rexBuilder.makeTimestampLiteral(ts, p);
    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
        ts = TimestampString.fromCalendarFields(calendar);
        final TimeZone tz = TimeZone.getTimeZone(this.timeZone);
        final TimestampString localTs = new TimestampWithTimeZoneString(ts, tz)
                .withTimeZone(DateTimeUtils.UTC_ZONE).getLocalTimestampString();
        p = operand.getType().getPrecision();
        return rexBuilder.makeTimestampWithLocalTimeZoneLiteral(localTs, p);
    case DATE:
        final DateString d = DateString.fromCalendarFields(calendar);
        return rexBuilder.makeDateLiteral(d);
    default:
        throw Util.unexpected(operand.getType().getSqlTypeName());
    }
}
 
Example 2
Source Project: Bats   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private Calendar timestampValue(RexLiteral timeLiteral) {
    switch (timeLiteral.getTypeName()) {
    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
        final TimeZone tz = TimeZone.getTimeZone(this.timeZone);
        return Util.calendar(
                SqlFunctions.timestampWithLocalTimeZoneToTimestamp(timeLiteral.getValueAs(Long.class), tz));
    case TIMESTAMP:
        return Util.calendar(timeLiteral.getValueAs(Long.class));
    case DATE:
        // Cast date to timestamp with local time zone
        final DateString d = timeLiteral.getValueAs(DateString.class);
        return Util.calendar(d.getMillisSinceEpoch());
    default:
        throw Util.unexpected(timeLiteral.getTypeName());
    }
}
 
Example 3
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private RexLiteral dateTimeLiteral(RexBuilder rexBuilder, Calendar calendar,
    RexNode operand) {
  final TimestampString ts;
  final int p;
  switch (operand.getType().getSqlTypeName()) {
  case TIMESTAMP:
    ts = TimestampString.fromCalendarFields(calendar);
    p = operand.getType().getPrecision();
    return rexBuilder.makeTimestampLiteral(ts, p);
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
    ts = TimestampString.fromCalendarFields(calendar);
    final TimeZone tz = TimeZone.getTimeZone(this.timeZone);
    final TimestampString localTs =
        new TimestampWithTimeZoneString(ts, tz)
            .withTimeZone(DateTimeUtils.UTC_ZONE)
            .getLocalTimestampString();
    p = operand.getType().getPrecision();
    return rexBuilder.makeTimestampWithLocalTimeZoneLiteral(localTs, p);
  case DATE:
    final DateString d = DateString.fromCalendarFields(calendar);
    return rexBuilder.makeDateLiteral(d);
  default:
    throw Util.unexpected(operand.getType().getSqlTypeName());
  }
}
 
Example 4
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private Calendar timestampValue(RexLiteral timeLiteral) {
  switch (timeLiteral.getTypeName()) {
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
    final TimeZone tz = TimeZone.getTimeZone(this.timeZone);
    return Util.calendar(
        SqlFunctions.timestampWithLocalTimeZoneToTimestamp(
            timeLiteral.getValueAs(Long.class), tz));
  case TIMESTAMP:
    return Util.calendar(timeLiteral.getValueAs(Long.class));
  case DATE:
    // Cast date to timestamp with local time zone
    final DateString d = timeLiteral.getValueAs(DateString.class);
    return Util.calendar(d.getMillisSinceEpoch());
  default:
    throw Util.unexpected(timeLiteral.getTypeName());
  }
}
 
Example 5
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Tests {@link RexBuilder#makeDateLiteral(DateString)}. */
@Test void testDateLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RelDataType dateType = typeFactory.createSqlType(SqlTypeName.DATE);
  final RexBuilder builder = new RexBuilder(typeFactory);

  // Old way: provide a Calendar
  final Calendar calendar = Util.calendar();
  calendar.set(1969, Calendar.JULY, 21); // one small step
  calendar.set(Calendar.MILLISECOND, 0);
  checkDate(builder.makeLiteral(calendar, dateType, false));

  // Old way #2: Provide in Integer
  checkDate(builder.makeLiteral(MOON_DAY, dateType, false));

  // The new way
  final DateString d = new DateString(1969, 7, 21);
  checkDate(builder.makeLiteral(d, dateType, false));
}
 
Example 6
Source Project: Bats   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlDateLiteral parseDateLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Calendar cal =
      DateTimeUtils.parseDateFormat(dateStr, Format.PER_THREAD.get().date,
          DateTimeUtils.UTC_ZONE);
  if (cal == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("DATE", s,
            RESOURCE.badFormat(DateTimeUtils.DATE_FORMAT_STRING).str()));
  }
  final DateString d = DateString.fromCalendarFields(cal);
  return SqlLiteral.createDate(d, pos);
}
 
Example 7
Source Project: dremio-oss   Source File: TestIndexBasedPruning.java    License: 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 8
Source Project: dremio-oss   Source File: TestORCSearchArgumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void equal() {
  RexNode eqInt = builder.makeCall(EQUALS, asList(input(0), intLit(0, 23)));
  assertEquals("leaf-0 = (EQUALS intC 23), expr = leaf-0", sarg(eqInt));

  RexNode eqBigInt = builder.makeCall(EQUALS, asList(input(1), bigIntLit(1, 23234234L)));
  assertEquals("leaf-0 = (EQUALS bigIntC 23234234), expr = leaf-0", sarg(eqBigInt));

  RexNode eqFloat = builder.makeCall(EQUALS, asList(input(2), floatLit(2, 23234.23f)));
  assertEquals("leaf-0 = (EQUALS floatC 23234.23), expr = leaf-0", sarg(eqFloat));

  RexNode eqDouble = builder.makeCall(EQUALS, asList(input(3), doubleLit(3, 235234234.234324d)));
  assertEquals("leaf-0 = (EQUALS doubleC 2.35234234234324E8), expr = leaf-0", sarg(eqDouble));

  final int daysSinceEpoch = 24233;
  RexNode eqDate = builder.makeCall(EQUALS, asList(input(4), dateLit(4, daysSinceEpoch)));
  Date date = new Date(DateString.fromDaysSinceEpoch(daysSinceEpoch).getMillisSinceEpoch());
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  final String strDate = dateFormat.format(date);
  assertEquals("leaf-0 = (EQUALS dateC " + strDate + "), expr = leaf-0", sarg(eqDate));

  final long millisSinceEpoch = 232349893L;
  RexNode eqTs = builder.makeCall(EQUALS, asList(input(5), tsLit(5, millisSinceEpoch)));
  final StringBuilder strTime = new StringBuilder();
  strTime.append(new Timestamp(millisSinceEpoch));
  assertEquals("leaf-0 = (EQUALS tsC " + strTime.toString() + "), expr = leaf-0", sarg(eqTs));

  RexNode eqVarchar = builder.makeCall(EQUALS, asList(input(6), varcharLit(6, "str")));
  assertEquals("leaf-0 = (EQUALS varcharC str), expr = leaf-0", sarg(eqVarchar));

  RexNode eqBool = builder.makeCall(EQUALS, asList(input(7), boolLit(7, true)));
  assertEquals("leaf-0 = (EQUALS boolC true), expr = leaf-0", sarg(eqBool));
}
 
Example 9
Source Project: dremio-oss   Source File: TestORCSearchArgumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void notEqual() {
  RexNode eqInt = builder.makeCall(NOT_EQUALS, asList(input(0), intLit(0, 23)));
  assertEquals("leaf-0 = (EQUALS intC 23), expr = (not leaf-0)", sarg(eqInt));

  RexNode eqBigInt = builder.makeCall(NOT_EQUALS, asList(input(1), bigIntLit(1, 23234234L)));
  assertEquals("leaf-0 = (EQUALS bigIntC 23234234), expr = (not leaf-0)", sarg(eqBigInt));

  RexNode eqFloat = builder.makeCall(NOT_EQUALS, asList(input(2), floatLit(2, 23234.23f)));
  assertEquals("leaf-0 = (EQUALS floatC 23234.23), expr = (not leaf-0)", sarg(eqFloat));

  RexNode eqDouble = builder.makeCall(NOT_EQUALS, asList(input(3), doubleLit(3, 235234234.234324d)));
  assertEquals("leaf-0 = (EQUALS doubleC 2.35234234234324E8), expr = (not leaf-0)", sarg(eqDouble));

  final int daysSinceEpoch = 24233;
  RexNode eqDate = builder.makeCall(NOT_EQUALS, asList(input(4), dateLit(4, daysSinceEpoch)));
  Date date = new Date(DateString.fromDaysSinceEpoch(daysSinceEpoch).getMillisSinceEpoch());
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  final String strDate = dateFormat.format(date);
  assertEquals("leaf-0 = (EQUALS dateC " + strDate + "), expr = (not leaf-0)", sarg(eqDate));

  final long millisSinceEpoch = 232349893L;
  RexNode eqTs = builder.makeCall(NOT_EQUALS, asList(input(5), tsLit(5, millisSinceEpoch)));
  final StringBuilder strTime = new StringBuilder();
  strTime.append(new Timestamp(millisSinceEpoch));
  assertEquals("leaf-0 = (EQUALS tsC " + strTime.toString() + "), expr = (not leaf-0)", sarg(eqTs));

  RexNode eqVarchar = builder.makeCall(NOT_EQUALS, asList(input(6), varcharLit(6, "str")));
  assertEquals("leaf-0 = (EQUALS varcharC str), expr = (not leaf-0)", sarg(eqVarchar));

  RexNode eqBool = builder.makeCall(NOT_EQUALS, asList(input(7), boolLit(7, true)));
  assertEquals("leaf-0 = (EQUALS boolC true), expr = (not leaf-0)", sarg(eqBool));
}
 
Example 10
Source Project: dremio-oss   Source File: TestORCSearchArgumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void lessThan() {
  RexNode eqInt = builder.makeCall(LESS_THAN, asList(input(0), intLit(0, 23)));
  assertEquals("leaf-0 = (LESS_THAN intC 23), expr = leaf-0", sarg(eqInt));

  RexNode eqBigInt = builder.makeCall(LESS_THAN, asList(input(1), bigIntLit(1, 23234234L)));
  assertEquals("leaf-0 = (LESS_THAN bigIntC 23234234), expr = leaf-0", sarg(eqBigInt));

  RexNode eqFloat = builder.makeCall(LESS_THAN, asList(input(2), floatLit(2, 23234.23f)));
  assertEquals("leaf-0 = (LESS_THAN floatC 23234.23), expr = leaf-0", sarg(eqFloat));

  RexNode eqDouble = builder.makeCall(LESS_THAN, asList(input(3), doubleLit(3, 235234234.234324d)));
  assertEquals("leaf-0 = (LESS_THAN doubleC 2.35234234234324E8), expr = leaf-0", sarg(eqDouble));

  final int daysSinceEpoch = 24233;
  RexNode eqDate = builder.makeCall(LESS_THAN, asList(input(4), dateLit(4, daysSinceEpoch)));
  Date date = new Date(DateString.fromDaysSinceEpoch(daysSinceEpoch).getMillisSinceEpoch());
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  final String strDate = dateFormat.format(date);
  assertEquals("leaf-0 = (LESS_THAN dateC " + strDate + "), expr = leaf-0", sarg(eqDate));

  final long millisSinceEpoch = 232349893L;
  RexNode eqTs = builder.makeCall(LESS_THAN, asList(input(5), tsLit(5, millisSinceEpoch)));
  final StringBuilder strTime = new StringBuilder();
  strTime.append(new Timestamp(millisSinceEpoch));
  assertEquals("leaf-0 = (LESS_THAN tsC " + strTime.toString() + "), expr = leaf-0", sarg(eqTs));

  RexNode eqVarchar = builder.makeCall(LESS_THAN, asList(input(6), varcharLit(6, "str")));
  assertEquals("leaf-0 = (LESS_THAN varcharC str), expr = leaf-0", sarg(eqVarchar));

  RexNode eqBool = builder.makeCall(LESS_THAN, asList(input(7), boolLit(7, true)));
  assertEquals("leaf-0 = (LESS_THAN boolC true), expr = leaf-0", sarg(eqBool));
}
 
Example 11
Source Project: dremio-oss   Source File: TestORCSearchArgumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void lessThanOrEqual() {
  RexNode eqInt = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(0), intLit(0, 23)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS intC 23), expr = leaf-0", sarg(eqInt));

  RexNode eqBigInt = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(1), bigIntLit(1, 23234234L)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS bigIntC 23234234), expr = leaf-0", sarg(eqBigInt));

  RexNode eqFloat = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(2), floatLit(2, 23234.23f)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS floatC 23234.23), expr = leaf-0", sarg(eqFloat));

  RexNode eqDouble = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(3), doubleLit(3, 235234234.234324d)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS doubleC 2.35234234234324E8), expr = leaf-0", sarg(eqDouble));

  final int daysSinceEpoch = 24233;
  RexNode eqDate = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(4), dateLit(4, daysSinceEpoch)));
  Date date = new Date(DateString.fromDaysSinceEpoch(daysSinceEpoch).getMillisSinceEpoch());
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  final String strDate = dateFormat.format(date);
  assertEquals("leaf-0 = (LESS_THAN_EQUALS dateC " + strDate + "), expr = leaf-0", sarg(eqDate));

  final long millisSinceEpoch = 232349893L;
  RexNode eqTs = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(5), tsLit(5, millisSinceEpoch)));
  final StringBuilder strTime = new StringBuilder();
  strTime.append(new Timestamp(millisSinceEpoch));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS tsC " + strTime.toString() + "), expr = leaf-0", sarg(eqTs));

  RexNode eqVarchar = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(6), varcharLit(6, "str")));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS varcharC str), expr = leaf-0", sarg(eqVarchar));

  RexNode eqBool = builder.makeCall(LESS_THAN_OR_EQUAL, asList(input(7), boolLit(7, true)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS boolC true), expr = leaf-0", sarg(eqBool));
}
 
Example 12
Source Project: dremio-oss   Source File: TestORCSearchArgumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void greaterThan() {
  RexNode eqInt = builder.makeCall(GREATER_THAN, asList(input(0), intLit(0, 23)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS intC 23), expr = (not leaf-0)", sarg(eqInt));

  RexNode eqBigInt = builder.makeCall(GREATER_THAN, asList(input(1), bigIntLit(1, 23234234L)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS bigIntC 23234234), expr = (not leaf-0)", sarg(eqBigInt));

  RexNode eqFloat = builder.makeCall(GREATER_THAN, asList(input(2), floatLit(2, 23234.23f)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS floatC 23234.23), expr = (not leaf-0)", sarg(eqFloat));

  RexNode eqDouble = builder.makeCall(GREATER_THAN, asList(input(3), doubleLit(3, 235234234.234324d)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS doubleC 2.35234234234324E8), expr = (not leaf-0)", sarg(eqDouble));

  final int daysSinceEpoch = 24233;
  RexNode eqDate = builder.makeCall(GREATER_THAN, asList(input(4), dateLit(4, daysSinceEpoch)));
  Date date = new Date(DateString.fromDaysSinceEpoch(daysSinceEpoch).getMillisSinceEpoch());
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  final String strDate = dateFormat.format(date);
  assertEquals("leaf-0 = (LESS_THAN_EQUALS dateC " + strDate + "), expr = (not leaf-0)", sarg(eqDate));

  final long millisSinceEpoch = 232349893L;
  RexNode eqTs = builder.makeCall(GREATER_THAN, asList(input(5), tsLit(5, millisSinceEpoch)));
  final StringBuilder strTime = new StringBuilder();
  strTime.append(new Timestamp(millisSinceEpoch));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS tsC " + strTime.toString() + "), expr = (not leaf-0)", sarg(eqTs));

  RexNode eqVarchar = builder.makeCall(GREATER_THAN, asList(input(6), varcharLit(6, "str")));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS varcharC str), expr = (not leaf-0)", sarg(eqVarchar));

  RexNode eqBool = builder.makeCall(GREATER_THAN, asList(input(7), boolLit(7, true)));
  assertEquals("leaf-0 = (LESS_THAN_EQUALS boolC true), expr = (not leaf-0)", sarg(eqBool));
}
 
Example 13
Source Project: dremio-oss   Source File: TestORCSearchArgumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void greaterThanOrEqual() {
  RexNode eqInt = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(0), intLit(0, 23)));
  assertEquals("leaf-0 = (LESS_THAN intC 23), expr = (not leaf-0)", sarg(eqInt));

  RexNode eqBigInt = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(1), bigIntLit(1, 23234234L)));
  assertEquals("leaf-0 = (LESS_THAN bigIntC 23234234), expr = (not leaf-0)", sarg(eqBigInt));

  RexNode eqFloat = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(2), floatLit(2, 23234.23f)));
  assertEquals("leaf-0 = (LESS_THAN floatC 23234.23), expr = (not leaf-0)", sarg(eqFloat));

  RexNode eqDouble = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(3), doubleLit(3, 235234234.234324d)));
  assertEquals("leaf-0 = (LESS_THAN doubleC 2.35234234234324E8), expr = (not leaf-0)", sarg(eqDouble));

  final int daysSinceEpoch = 24233;
  RexNode eqDate = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(4), dateLit(4, daysSinceEpoch)));
  Date date = new Date(DateString.fromDaysSinceEpoch(daysSinceEpoch).getMillisSinceEpoch());
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  final String strDate = dateFormat.format(date);
  assertEquals("leaf-0 = (LESS_THAN dateC " + strDate + "), expr = (not leaf-0)", sarg(eqDate));

  final long millisSinceEpoch = 232349893L;
  RexNode eqTs = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(5), tsLit(5, millisSinceEpoch)));
  final StringBuilder strTime = new StringBuilder();
  strTime.append(new Timestamp(millisSinceEpoch));
  assertEquals("leaf-0 = (LESS_THAN tsC " + strTime.toString() + "), expr = (not leaf-0)", sarg(eqTs));

  RexNode eqVarchar = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(6), varcharLit(6, "str")));
  assertEquals("leaf-0 = (LESS_THAN varcharC str), expr = (not leaf-0)", sarg(eqVarchar));

  RexNode eqBool = builder.makeCall(GREATER_THAN_OR_EQUAL, asList(input(7), boolLit(7, true)));
  assertEquals("leaf-0 = (LESS_THAN boolC true), expr = (not leaf-0)", sarg(eqBool));
}
 
Example 14
Source Project: flink   Source File: ExpressionConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDateLiteral() {
	RexNode rex = converter.visit(valueLiteral(
		LocalDate.parse("2012-12-12"),
		DataTypes.DATE().notNull()));
	assertThat(
		((RexLiteral) rex).getValueAs(DateString.class),
		equalTo(new DateString("2012-12-12")));
	assertThat(rex.getType().getSqlTypeName(), equalTo(SqlTypeName.DATE));
}
 
Example 15
Source Project: calcite   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlDateLiteral parseDateLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Calendar cal =
      DateTimeUtils.parseDateFormat(dateStr, Format.PER_THREAD.get().date,
          DateTimeUtils.UTC_ZONE);
  if (cal == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("DATE", s,
            RESOURCE.badFormat(DateTimeUtils.DATE_FORMAT_STRING).str()));
  }
  final DateString d = DateString.fromCalendarFields(cal);
  return SqlLiteral.createDate(d, pos);
}
 
Example 16
Source Project: calcite   Source File: DateRangeRulesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testFloorRewriteWithTimezone() {
  final Calendar c = Util.calendar();
  c.clear();
  c.set(2010, Calendar.FEBRUARY, 1, 11, 30, 0);
  final Fixture2 f = new Fixture2();
  checkDateRange(f,
      f.eq(f.floorHour,
          f.timestampLocalTzLiteral(TimestampString.fromCalendarFields(c))),
      "IST",
      is("AND(>=($9, 2010-02-01 17:00:00), <($9, 2010-02-01 18:00:00))"),
      CoreMatchers.any(String.class));

  c.clear();
  c.set(2010, Calendar.FEBRUARY, 1, 11, 00, 0);
  checkDateRange(f,
      f.eq(f.floorHour,
          f.timestampLiteral(TimestampString.fromCalendarFields(c))),
      "IST",
      is("AND(>=($9, 2010-02-01 11:00:00), <($9, 2010-02-01 12:00:00))"),
      CoreMatchers.any(String.class));

  c.clear();
  c.set(2010, Calendar.FEBRUARY, 1, 00, 00, 0);
  checkDateRange(f,
      f.eq(f.floorHour, f.dateLiteral(DateString.fromCalendarFields(c))),
      "IST",
      is("AND(>=($9, 2010-02-01 00:00:00), <($9, 2010-02-01 01:00:00))"),
      CoreMatchers.any(String.class));
}
 
Example 17
Source Project: calcite   Source File: RexImplicationCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testSimpleDate() {
  final Fixture f = new Fixture();
  final DateString d = DateString.fromCalendarFields(Util.calendar());
  final RexNode node1 = f.ge(f.d, f.dateLiteral(d));
  final RexNode node2 = f.eq(f.d, f.dateLiteral(d));
  f.checkImplies(node2, node1);
  f.checkNotImplies(node1, node2);

  final DateString dBeforeEpoch1 = DateString.fromDaysSinceEpoch(-12345);
  final DateString dBeforeEpoch2 = DateString.fromDaysSinceEpoch(-123);
  final RexNode nodeBe1 = f.lt(f.d, f.dateLiteral(dBeforeEpoch1));
  final RexNode nodeBe2 = f.lt(f.d, f.dateLiteral(dBeforeEpoch2));
  f.checkImplies(nodeBe1, nodeBe2);
  f.checkNotImplies(nodeBe2, nodeBe1);
}
 
Example 18
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
private void checkDate(RexNode node) {
  assertThat(node.toString(), is("1969-07-21"));
  RexLiteral literal = (RexLiteral) node;
  assertThat(literal.getValue() instanceof Calendar, is(true));
  assertThat(literal.getValue2() instanceof Integer, is(true));
  assertThat(literal.getValue3() instanceof Integer, is(true));
  assertThat((Integer) literal.getValue2(), is(MOON_DAY));
  assertThat(literal.getValueAs(Calendar.class), notNullValue());
  assertThat(literal.getValueAs(DateString.class), notNullValue());
}
 
Example 19
Source Project: Bats   Source File: SqlNodeToRexConverterImpl.java    License: Apache License 2.0 4 votes vote down vote up
public RexNode convertLiteral(
    SqlRexContext cx,
    SqlLiteral literal) {
  RexBuilder rexBuilder = cx.getRexBuilder();
  RelDataTypeFactory typeFactory = cx.getTypeFactory();
  SqlValidator validator = cx.getValidator();
  if (literal.getValue() == null) {
    // Since there is no eq. RexLiteral of SqlLiteral.Unknown we
    // treat it as a cast(null as boolean)
    RelDataType type;
    if (literal.getTypeName() == SqlTypeName.BOOLEAN) {
      type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
      type = typeFactory.createTypeWithNullability(type, true);
    } else {
      type = validator.getValidatedNodeType(literal);
    }
    return rexBuilder.makeCast(
        type,
        rexBuilder.constantNull());
  }

  BitString bitString;
  SqlIntervalLiteral.IntervalValue intervalValue;
  long l;

  switch (literal.getTypeName()) {
  case DECIMAL:
    // exact number
    BigDecimal bd = literal.getValueAs(BigDecimal.class);
    return rexBuilder.makeExactLiteral(
        bd,
        literal.createSqlType(typeFactory));

  case DOUBLE:
    // approximate type
    // TODO:  preserve fixed-point precision and large integers
    return rexBuilder.makeApproxLiteral(literal.getValueAs(BigDecimal.class));

  case CHAR:
    return rexBuilder.makeCharLiteral(literal.getValueAs(NlsString.class));
  case BOOLEAN:
    return rexBuilder.makeLiteral(literal.getValueAs(Boolean.class));
  case BINARY:
    bitString = literal.getValueAs(BitString.class);
    Preconditions.checkArgument((bitString.getBitCount() % 8) == 0,
        "incomplete octet");

    // An even number of hexits (e.g. X'ABCD') makes whole number
    // of bytes.
    ByteString byteString = new ByteString(bitString.getAsByteArray());
    return rexBuilder.makeBinaryLiteral(byteString);
  case SYMBOL:
    return rexBuilder.makeFlag(literal.getValueAs(Enum.class));
  case TIMESTAMP:
    return rexBuilder.makeTimestampLiteral(
        literal.getValueAs(TimestampString.class),
        ((SqlTimestampLiteral) literal).getPrec());
  case TIME:
    return rexBuilder.makeTimeLiteral(
        literal.getValueAs(TimeString.class),
        ((SqlTimeLiteral) literal).getPrec());
  case DATE:
    return rexBuilder.makeDateLiteral(literal.getValueAs(DateString.class));

  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:
    SqlIntervalQualifier sqlIntervalQualifier =
        literal.getValueAs(SqlIntervalLiteral.IntervalValue.class)
            .getIntervalQualifier();
    return rexBuilder.makeIntervalLiteral(
        literal.getValueAs(BigDecimal.class),
        sqlIntervalQualifier);
  default:
    throw Util.unexpected(literal.getTypeName());
  }
}
 
Example 20
Source Project: Bats   Source File: SqlLiteral.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @return whether value is appropriate for its type (we have rules about
 * these things)
 */
public static boolean valueMatchesType(
    Object value,
    SqlTypeName typeName) {
  switch (typeName) {
  case BOOLEAN:
    return (value == null) || (value instanceof Boolean);
  case NULL:
    return value == null;
  case DECIMAL:
  case DOUBLE:
    return value instanceof BigDecimal;
  case DATE:
    return value instanceof DateString;
  case TIME:
    return value instanceof TimeString;
  case TIMESTAMP:
    return value instanceof TimestampString;
  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:
    return value instanceof SqlIntervalLiteral.IntervalValue;
  case BINARY:
    return value instanceof BitString;
  case CHAR:
    return value instanceof NlsString;
  case SYMBOL:
    return (value instanceof Enum)
        || (value instanceof SqlSampleSpec);
  case MULTISET:
    return true;
  case INTEGER: // not allowed -- use Decimal
  case VARCHAR: // not allowed -- use Char
  case VARBINARY: // not allowed -- use Binary
  default:
    throw Util.unexpected(typeName);
  }
}
 
Example 21
Source Project: Bats   Source File: SqlLiteral.java    License: Apache License 2.0 4 votes vote down vote up
public <T> T getValueAs(Class<T> clazz) {
  if (clazz.isInstance(value)) {
    return clazz.cast(value);
  }
  switch (typeName) {
  case CHAR:
    if (clazz == String.class) {
      return clazz.cast(((NlsString) value).getValue());
    }
    break;
  case BINARY:
    if (clazz == byte[].class) {
      return clazz.cast(((BitString) value).getAsByteArray());
    }
    break;
  case DECIMAL:
    if (clazz == Long.class) {
      return clazz.cast(((BigDecimal) value).unscaledValue().longValue());
    }
    // fall through
  case BIGINT:
  case INTEGER:
  case SMALLINT:
  case TINYINT:
  case DOUBLE:
  case REAL:
  case FLOAT:
    if (clazz == Long.class) {
      return clazz.cast(((BigDecimal) value).longValue());
    } else if (clazz == Integer.class) {
      return clazz.cast(((BigDecimal) value).intValue());
    } else if (clazz == Short.class) {
      return clazz.cast(((BigDecimal) value).shortValue());
    } else if (clazz == Byte.class) {
      return clazz.cast(((BigDecimal) value).byteValue());
    } else if (clazz == Double.class) {
      return clazz.cast(((BigDecimal) value).doubleValue());
    } else if (clazz == Float.class) {
      return clazz.cast(((BigDecimal) value).floatValue());
    }
    break;
  case DATE:
    if (clazz == Calendar.class) {
      return clazz.cast(((DateString) value).toCalendar());
    }
    break;
  case TIME:
    if (clazz == Calendar.class) {
      return clazz.cast(((TimeString) value).toCalendar());
    }
    break;
  case TIMESTAMP:
    if (clazz == Calendar.class) {
      return clazz.cast(((TimestampString) value).toCalendar());
    }
    break;
  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
    final SqlIntervalLiteral.IntervalValue valMonth =
        (SqlIntervalLiteral.IntervalValue) value;
    if (clazz == Long.class) {
      return clazz.cast(valMonth.getSign()
          * SqlParserUtil.intervalToMonths(valMonth));
    } else if (clazz == BigDecimal.class) {
      return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
    } else if (clazz == TimeUnitRange.class) {
      return clazz.cast(valMonth.getIntervalQualifier().timeUnitRange);
    }
    break;
  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:
    final SqlIntervalLiteral.IntervalValue valTime =
        (SqlIntervalLiteral.IntervalValue) value;
    if (clazz == Long.class) {
      return clazz.cast(valTime.getSign()
          * SqlParserUtil.intervalToMillis(valTime));
    } else if (clazz == BigDecimal.class) {
      return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
    } else if (clazz == TimeUnitRange.class) {
      return clazz.cast(valTime.getIntervalQualifier().timeUnitRange);
    }
    break;
  }
  throw new AssertionError("cannot cast " + value + " as " + clazz);
}
 
Example 22
Source Project: Bats   Source File: SqlLiteral.java    License: Apache License 2.0 4 votes vote down vote up
@Deprecated // to be removed before 2.0
public static SqlDateLiteral createDate(
    Calendar calendar,
    SqlParserPos pos) {
  return createDate(DateString.fromCalendarFields(calendar), pos);
}
 
Example 23
Source Project: Bats   Source File: SqlLiteral.java    License: Apache License 2.0 4 votes vote down vote up
public static SqlDateLiteral createDate(
    DateString date,
    SqlParserPos pos) {
  return new SqlDateLiteral(date, pos);
}
 
Example 24
Source Project: Bats   Source File: SqlDateLiteral.java    License: Apache License 2.0 4 votes vote down vote up
SqlDateLiteral(DateString d, SqlParserPos pos) {
  super(d, false, SqlTypeName.DATE, 0, pos);
}
 
Example 25
Source Project: Bats   Source File: SqlDateLiteral.java    License: Apache License 2.0 4 votes vote down vote up
/** Converts this literal to a {@link DateString}. */
protected DateString getDate() {
  return (DateString) value;
}
 
Example 26
Source Project: Bats   Source File: SqlDateLiteral.java    License: Apache License 2.0 4 votes vote down vote up
@Override public SqlDateLiteral clone(SqlParserPos pos) {
  return new SqlDateLiteral((DateString) value, pos);
}
 
Example 27
Source Project: Bats   Source File: RexBuilder.java    License: Apache License 2.0 4 votes vote down vote up
/** @deprecated Use {@link #makeDateLiteral(DateString)}. */
@Deprecated // to be removed before 2.0
public RexLiteral makeDateLiteral(Calendar calendar) {
  return makeDateLiteral(DateString.fromCalendarFields(calendar));
}
 
Example 28
Source Project: Bats   Source File: RexBuilder.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a Date literal.
 */
public RexLiteral makeDateLiteral(DateString date) {
  return makeLiteral(Objects.requireNonNull(date),
      typeFactory.createSqlType(SqlTypeName.DATE), SqlTypeName.DATE);
}
 
Example 29
Source Project: Bats   Source File: RexBuilder.java    License: Apache License 2.0 4 votes vote down vote up
/** Converts the type of a value to comply with
 * {@link org.apache.calcite.rex.RexLiteral#valueMatchesType}. */
private static Object clean(Object o, RelDataType type) {
  if (o == null) {
    return null;
  }
  switch (type.getSqlTypeName()) {
  case TINYINT:
  case SMALLINT:
  case INTEGER:
  case BIGINT:
  case DECIMAL:
  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:
    if (o instanceof BigDecimal) {
      return o;
    }
    return new BigDecimal(((Number) o).longValue());
  case FLOAT:
    if (o instanceof BigDecimal) {
      return o;
    }
    return new BigDecimal(((Number) o).doubleValue(), MathContext.DECIMAL32)
        .stripTrailingZeros();
  case REAL:
  case DOUBLE:
    if (o instanceof BigDecimal) {
      return o;
    }
    return new BigDecimal(((Number) o).doubleValue(), MathContext.DECIMAL64)
        .stripTrailingZeros();
  case CHAR:
  case VARCHAR:
    if (o instanceof NlsString) {
      return o;
    }
    return new NlsString((String) o, type.getCharset().name(),
        type.getCollation());
  case TIME:
    if (o instanceof TimeString) {
      return o;
    } else if (o instanceof Calendar) {
      if (!((Calendar) o).getTimeZone().equals(DateTimeUtils.UTC_ZONE)) {
        throw new AssertionError();
      }
      return TimeString.fromCalendarFields((Calendar) o);
    } else {
      return TimeString.fromMillisOfDay((Integer) o);
    }
  case TIME_WITH_LOCAL_TIME_ZONE:
    if (o instanceof TimeString) {
      return o;
    } else {
      return TimeString.fromMillisOfDay((Integer) o);
    }
  case DATE:
    if (o instanceof DateString) {
      return o;
    } else if (o instanceof Calendar) {
      if (!((Calendar) o).getTimeZone().equals(DateTimeUtils.UTC_ZONE)) {
        throw new AssertionError();
      }
      return DateString.fromCalendarFields((Calendar) o);
    } else {
      return DateString.fromDaysSinceEpoch((Integer) o);
    }
  case TIMESTAMP:
    if (o instanceof TimestampString) {
      return o;
    } else if (o instanceof Calendar) {
      if (!((Calendar) o).getTimeZone().equals(DateTimeUtils.UTC_ZONE)) {
        throw new AssertionError();
      }
      return TimestampString.fromCalendarFields((Calendar) o);
    } else {
      return TimestampString.fromMillisSinceEpoch((Long) o);
    }
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
    if (o instanceof TimestampString) {
      return o;
    } else {
      return TimestampString.fromMillisSinceEpoch((Long) o);
    }
  default:
    return o;
  }
}
 
Example 30
Source Project: Bats   Source File: RexToSqlNodeConverterImpl.java    License: Apache License 2.0 4 votes vote down vote up
public SqlNode convertLiteral(RexLiteral literal) {
  // Numeric
  if (SqlTypeFamily.EXACT_NUMERIC.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createExactNumeric(
        literal.getValue().toString(),
        SqlParserPos.ZERO);
  }

  if (SqlTypeFamily.APPROXIMATE_NUMERIC.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createApproxNumeric(
        literal.getValue().toString(),
        SqlParserPos.ZERO);
  }

  // Timestamp
  if (SqlTypeFamily.TIMESTAMP.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createTimestamp(
        literal.getValueAs(TimestampString.class),
        0,
        SqlParserPos.ZERO);
  }

  // Date
  if (SqlTypeFamily.DATE.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createDate(
        literal.getValueAs(DateString.class),
        SqlParserPos.ZERO);
  }

  // Time
  if (SqlTypeFamily.TIME.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createTime(
        literal.getValueAs(TimeString.class),
        0,
        SqlParserPos.ZERO);
  }

  // String
  if (SqlTypeFamily.CHARACTER.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createCharString(
        ((NlsString) (literal.getValue())).getValue(),
        SqlParserPos.ZERO);
  }

  // Boolean
  if (SqlTypeFamily.BOOLEAN.getTypeNames().contains(
      literal.getTypeName())) {
    return SqlLiteral.createBoolean(
        (Boolean) literal.getValue(),
        SqlParserPos.ZERO);
  }

  // Null
  if (SqlTypeFamily.NULL == literal.getTypeName().getFamily()) {
    return SqlLiteral.createNull(SqlParserPos.ZERO);
  }

  return null;
}