org.apache.calcite.avatica.util.DateTimeUtils Java Examples

The following examples show how to use org.apache.calcite.avatica.util.DateTimeUtils. 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: SqlFunctions.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static int subtractMonths(long t0, long t1) {
  final long millis0 =
      DateTimeUtils.floorMod(t0, DateTimeUtils.MILLIS_PER_DAY);
  final int d0 = (int) DateTimeUtils.floorDiv(t0 - millis0,
      DateTimeUtils.MILLIS_PER_DAY);
  final long millis1 =
      DateTimeUtils.floorMod(t1, DateTimeUtils.MILLIS_PER_DAY);
  final int d1 = (int) DateTimeUtils.floorDiv(t1 - millis1,
      DateTimeUtils.MILLIS_PER_DAY);
  int x = subtractMonths(d0, d1);
  final long d2 = addMonths(d1, x);
  if (d2 == d0 && millis0 < millis1) {
    --x;
  }
  return x;
}
 
Example #2
Source File: RexInterpreter.java    From Quicksql with MIT License 6 votes vote down vote up
private Comparable extract(RexCall call, List<Comparable> values) {
  final Comparable v = values.get(1);
  if (v == N) {
    return N;
  }
  final TimeUnitRange timeUnitRange = (TimeUnitRange) values.get(0);
  final int v2;
  if (v instanceof Long) {
    // TIMESTAMP
    v2 = (int) (((Long) v) / TimeUnit.DAY.multiplier.longValue());
  } else {
    // DATE
    v2 = (Integer) v;
  }
  return DateTimeUtils.unixDateExtract(timeUnitRange, v2);
}
 
Example #3
Source File: RexInterpreter.java    From Quicksql with MIT License 6 votes vote down vote up
private Comparable ceil(RexCall call, List<Comparable> values) {
  if (values.get(0) == N) {
    return N;
  }
  final Long v = (Long) values.get(0);
  final TimeUnitRange unit = (TimeUnitRange) values.get(1);
  switch (unit) {
  case YEAR:
  case MONTH:
    switch (call.getKind()) {
    case FLOOR:
      return DateTimeUtils.unixTimestampFloor(unit, v);
    default:
      return DateTimeUtils.unixTimestampCeil(unit, v);
    }
  }
  final TimeUnitRange subUnit = subUnit(unit);
  for (long v2 = v;;) {
    final int e = DateTimeUtils.unixTimestampExtract(subUnit, v2);
    if (e == 0) {
      return v2;
    }
    v2 -= unit.startUnit.multiplier.longValue();
  }
}
 
Example #4
Source File: SqlFunctions.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Adds a given number of months to a date, represented as the number of
 * days since the epoch. */
public static int addMonths(int date, int m) {
  int y0 = (int) DateTimeUtils.unixDateExtract(TimeUnitRange.YEAR, date);
  int m0 = (int) DateTimeUtils.unixDateExtract(TimeUnitRange.MONTH, date);
  int d0 = (int) DateTimeUtils.unixDateExtract(TimeUnitRange.DAY, date);
  m0 += m;
  int deltaYear = (int) DateTimeUtils.floorDiv(m0, 12);
  y0 += deltaYear;
  m0 = (int) DateTimeUtils.floorMod(m0, 12);
  if (m0 == 0) {
    y0 -= 1;
    m0 += 12;
  }

  int last = lastDay(y0, m0);
  if (d0 > last) {
    d0 = last;
  }
  return DateTimeUtils.ymdToUnixDate(y0, m0, d0);
}
 
Example #5
Source File: QuicksqlServerResultSet.java    From Quicksql with MIT License 6 votes vote down vote up
public static QuicksqlServerResultSet create(String connectionId, int statementId,
    ResultSet resultSet, int maxRowCount, Signature signature) {
  try {
    final Calendar calendar = DateTimeUtils.calendar();
    final int fetchRowCount;
    if (maxRowCount == QuicksqlServerMeta.UNLIMITED_COUNT) {
      fetchRowCount = -1;
    } else if (maxRowCount < 0L) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else if (maxRowCount > AvaticaStatement.DEFAULT_FETCH_SIZE) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else {
      fetchRowCount = maxRowCount;
    }
    final Meta.Frame firstFrame = frame(null, resultSet,0, fetchRowCount, calendar,
        Optional.of(signature));
    if (firstFrame.done) {
      resultSet.close();
    }
    return new QuicksqlServerResultSet(connectionId, statementId, true, signature,
        firstFrame);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #6
Source File: RexInterpreter.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Comparable extract(RexCall call, List<Comparable> values) {
  final Comparable v = values.get(1);
  if (v == N) {
    return N;
  }
  final TimeUnitRange timeUnitRange = (TimeUnitRange) values.get(0);
  final int v2;
  if (v instanceof Long) {
    // TIMESTAMP
    v2 = (int) (((Long) v) / TimeUnit.DAY.multiplier.longValue());
  } else {
    // DATE
    v2 = (Integer) v;
  }
  return DateTimeUtils.unixDateExtract(timeUnitRange, v2);
}
 
Example #7
Source File: JdbcResultSet.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
public static JdbcResultSet create(String connectionId, int statementId,
    ResultSet resultSet, int maxRowCount, Meta.Signature signature) {
  try {
    final Calendar calendar = DateTimeUtils.calendar();
    final int fetchRowCount;
    if (maxRowCount == JdbcMeta.UNLIMITED_COUNT) {
      fetchRowCount = -1;
    } else if (maxRowCount < 0L) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else if (maxRowCount > AvaticaStatement.DEFAULT_FETCH_SIZE) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else {
      fetchRowCount = maxRowCount;
    }
    final Meta.Frame firstFrame = frame(null, resultSet, 0, fetchRowCount, calendar,
        Optional.of(signature));
    if (firstFrame.done) {
      resultSet.close();
    }
    return new JdbcResultSet(connectionId, statementId, true, signature,
        firstFrame);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #8
Source File: TimestampString.java    From Quicksql with MIT License 6 votes vote down vote up
/** Returns the number of milliseconds since the epoch. */
public long getMillisSinceEpoch() {
  final int year = Integer.valueOf(v.substring(0, 4));
  final int month = Integer.valueOf(v.substring(5, 7));
  final int day = Integer.valueOf(v.substring(8, 10));
  final int h = Integer.valueOf(v.substring(11, 13));
  final int m = Integer.valueOf(v.substring(14, 16));
  final int s = Integer.valueOf(v.substring(17, 19));
  final int ms = getMillisInSecond();
  final int d = DateTimeUtils.ymdToUnixDate(year, month, day);
  return d * DateTimeUtils.MILLIS_PER_DAY
      + h * DateTimeUtils.MILLIS_PER_HOUR
      + m * DateTimeUtils.MILLIS_PER_MINUTE
      + s * DateTimeUtils.MILLIS_PER_SECOND
      + ms;
}
 
Example #9
Source File: MongoEnumerator.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Object convert(Object o, Class clazz) {
  if (o == null) {
    return null;
  }
  Primitive primitive = Primitive.of(clazz);
  if (primitive != null) {
    clazz = primitive.boxClass;
  } else {
    primitive = Primitive.ofBox(clazz);
  }
  if (clazz.isInstance(o)) {
    return o;
  }
  if (o instanceof Date && primitive != null) {
    o = ((Date) o).getTime() / DateTimeUtils.MILLIS_PER_DAY;
  }
  if (o instanceof Number && primitive != null) {
    return primitive.number((Number) o);
  }
  return o;
}
 
Example #10
Source File: ElasticsearchEnumerators.java    From Quicksql with MIT License 6 votes vote down vote up
private static Object convert(Object o, Class clazz) {
  if (o == null) {
    return null;
  }
  Primitive primitive = Primitive.of(clazz);
  if (primitive != null) {
    clazz = primitive.boxClass;
  } else {
    primitive = Primitive.ofBox(clazz);
  }
  if (clazz.isInstance(o)) {
    return o;
  }
  if (o instanceof Date && primitive != null) {
    o = ((Date) o).getTime() / DateTimeUtils.MILLIS_PER_DAY;
  }
  if (o instanceof Number && primitive != null) {
    return primitive.number((Number) o);
  }
  return o;
}
 
Example #11
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testBase64() {
  byte[] bytes = "qwertyasdf".getBytes(UTF_8);
  // Plain bytes get put into protobuf for simplicitly
  Common.TypedValue proto = Common.TypedValue.newBuilder().setBytesValue(
      com.google.protobuf.ByteString.copyFrom(bytes))
      .setType(Common.Rep.BYTE_STRING).build();

  // But we should get back a b64-string to make sure TypedValue doesn't get confused.
  Object deserializedObj = TypedValue.getSerialFromProto(proto);
  assertThat(deserializedObj, is(instanceOf(String.class)));
  assertEquals(new ByteString(bytes).toBase64String(), (String) deserializedObj);

  // But we should get a non-b64 byte array as the JDBC representation
  deserializedObj =
      TypedValue.protoToJdbc(proto, DateTimeUtils.calendar());
  assertThat(deserializedObj, is(instanceOf(byte[].class)));
  assertArrayEquals(bytes, (byte[]) deserializedObj);
}
 
Example #12
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static SqlTimestampLiteral parseTimestampLiteral(String s,
    SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Format format = Format.PER_THREAD.get();
  DateTimeUtils.PrecisionTime pt = null;
  // Allow timestamp literals with and without time fields (as does
  // PostgreSQL); TODO: require time fields except in Babel's lenient mode
  final DateFormat[] dateFormats = {format.timestamp, format.date};
  for (DateFormat dateFormat : dateFormats) {
    pt = DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
        dateFormat, DateTimeUtils.UTC_ZONE, -1);
    if (pt != null) {
      break;
    }
  }
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIMESTAMP", s,
            RESOURCE.badFormat(DateTimeUtils.TIMESTAMP_FORMAT_STRING).str()));
  }
  final TimestampString ts =
      TimestampString.fromCalendarFields(pt.getCalendar())
          .withFraction(pt.getFraction());
  return SqlLiteral.createTimestamp(ts, pt.getPrecision(), pos);
}
 
Example #13
Source File: TimestampString.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Returns the number of milliseconds since the epoch. */
public long getMillisSinceEpoch() {
  final int year = Integer.valueOf(v.substring(0, 4));
  final int month = Integer.valueOf(v.substring(5, 7));
  final int day = Integer.valueOf(v.substring(8, 10));
  final int h = Integer.valueOf(v.substring(11, 13));
  final int m = Integer.valueOf(v.substring(14, 16));
  final int s = Integer.valueOf(v.substring(17, 19));
  final int ms = getMillisInSecond();
  final int d = DateTimeUtils.ymdToUnixDate(year, month, day);
  return d * DateTimeUtils.MILLIS_PER_DAY
      + h * DateTimeUtils.MILLIS_PER_HOUR
      + m * DateTimeUtils.MILLIS_PER_MINUTE
      + s * DateTimeUtils.MILLIS_PER_SECOND
      + ms;
}
 
Example #14
Source File: SqlParserUtil.java    From Quicksql with MIT License 6 votes vote down vote up
public static SqlTimestampLiteral parseTimestampLiteral(String s,
    SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Format format = Format.PER_THREAD.get();
  DateTimeUtils.PrecisionTime pt = null;
  // Allow timestamp literals with and without time fields (as does
  // PostgreSQL); TODO: require time fields except in Babel's lenient mode
  final DateFormat[] dateFormats = {format.timestamp, format.date};
  for (DateFormat dateFormat : dateFormats) {
    pt = DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
        dateFormat, DateTimeUtils.UTC_ZONE, -1);
    if (pt != null) {
      break;
    }
  }
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIMESTAMP", s,
            RESOURCE.badFormat(DateTimeUtils.TIMESTAMP_FORMAT_STRING).str()));
  }
  final TimestampString ts =
      TimestampString.fromCalendarFields(pt.getCalendar())
          .withFraction(pt.getFraction());
  return SqlLiteral.createTimestamp(ts, pt.getPrecision(), pos);
}
 
Example #15
Source File: RexInterpreter.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Comparable ceil(RexCall call, List<Comparable> values) {
  if (values.get(0) == N) {
    return N;
  }
  final Long v = (Long) values.get(0);
  final TimeUnitRange unit = (TimeUnitRange) values.get(1);
  switch (unit) {
  case YEAR:
  case MONTH:
    switch (call.getKind()) {
    case FLOOR:
      return DateTimeUtils.unixTimestampFloor(unit, v);
    default:
      return DateTimeUtils.unixTimestampCeil(unit, v);
    }
  }
  final TimeUnitRange subUnit = subUnit(unit);
  for (long v2 = v;;) {
    final int e = DateTimeUtils.unixTimestampExtract(subUnit, v2);
    if (e == 0) {
      return v2;
    }
    v2 -= unit.startUnit.multiplier.longValue();
  }
}
 
Example #16
Source File: DateRangeRules.java    From calcite with 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 #17
Source File: DateString.java    From Quicksql with MIT License 5 votes vote down vote up
/** Returns the number of days since the epoch. */
public int getDaysSinceEpoch() {
  int year = getYear();
  int month = getMonth();
  int day = getDay();
  return DateTimeUtils.ymdToUnixDate(year, month, day);
}
 
Example #18
Source File: GeodeUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Object convert(Object o, Class clazz) {
  if (o == null) {
    return null;
  }
  Primitive primitive = Primitive.of(clazz);
  if (primitive != null) {
    clazz = primitive.boxClass;
  } else {
    primitive = Primitive.ofBox(clazz);
  }
  if (clazz == null) {
    return o.toString();
  }
  if (Map.class.isAssignableFrom(clazz)
          && o instanceof PdxInstance) {
    // This is in case of nested Objects!
    return Util.toString(
            ((PdxInstance) o).getFieldNames(), "PDX[", ",", "]");
  }
  if (clazz.isInstance(o)) {
    return o;
  }
  if (o instanceof Date && primitive != null) {
    o = ((Date) o).getTime() / DateTimeUtils.MILLIS_PER_DAY;
  }
  if (o instanceof Number && primitive != null) {
    return primitive.number((Number) o);
  }
  return o;
}
 
Example #19
Source File: CalciteConvertors.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private static Time shift(Time v) {
    if (v == null) {
        return null;
    }
    long time = v.getTime();
    int offset = TimeZone.getDefault().getOffset(time);
    return new Time((time + offset) % DateTimeUtils.MILLIS_PER_DAY);
}
 
Example #20
Source File: SqlParserUtil.java    From calcite with 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 #21
Source File: TypedValueTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void testLegacyDecimalParsing() {
  final BigDecimal decimal = new BigDecimal("123451234512345");
  final Calendar calendar = DateTimeUtils.calendar();

  // CALCITE-1103 Decimals were (incorrectly) getting serialized as normal "numbers" which
  // caused them to use the numberValue field. TypedValue should still be able to handle
  // values like this (but large values will be truncated and return bad values).
  Common.TypedValue oldProtoStyle = Common.TypedValue.newBuilder().setType(Common.Rep.NUMBER)
      .setNumberValue(decimal.longValue()).build();

  TypedValue fromProtoTv = TypedValue.fromProto(oldProtoStyle);
  Object o = fromProtoTv.toJdbc(calendar);
  assertEquals(decimal, o);
}
 
Example #22
Source File: QuarkMetaResultSet.java    From quark with Apache License 2.0 5 votes vote down vote up
public static QuarkMetaResultSet create(String connectionId, int statementId,
                                        Iterator iterator,
                                        long maxRowCount, Meta.Signature signature) {
  try {
    final Calendar calendar = Calendar.getInstance(DateTimeUtils.GMT_ZONE);
    final int fetchRowCount;
    if (maxRowCount == QuarkMetaImpl.UNLIMITED_COUNT) {
      fetchRowCount = -1;
    } else if (maxRowCount < 0L) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else if (maxRowCount > AvaticaStatement.DEFAULT_FETCH_SIZE) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else {
      fetchRowCount = (int) maxRowCount;
    }
    final Meta.Frame firstFrame;
    if (!iterator.hasNext()) {
      firstFrame = Meta.Frame.EMPTY;
    } else {
      firstFrame = frame(iterator, signature.columns, 0, fetchRowCount, calendar);
    }
    return new QuarkMetaResultSet(connectionId, statementId, true, signature,
        firstFrame);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #23
Source File: SqlDateTimeUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the epoch days since 1970-01-01.
 */
public static int strToDate(String dateStr, String fromFormat) {
	// It is OK to use UTC, we just want get the epoch days
	// TODO  use offset, better performance
	long ts = parseToTimeMillis(dateStr, fromFormat, TimeZone.getTimeZone("UTC"));
	ZoneId zoneId = ZoneId.of("UTC");
	Instant instant = Instant.ofEpochMilli(ts);
	ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zoneId);
	return DateTimeUtils.ymdToUnixDate(zdt.getYear(), zdt.getMonthValue(), zdt.getDayOfMonth());
}
 
Example #24
Source File: TimeString.java    From calcite with Apache License 2.0 5 votes vote down vote up
public int getMillisOfDay() {
  int h = Integer.valueOf(v.substring(0, 2));
  int m = Integer.valueOf(v.substring(3, 5));
  int s = Integer.valueOf(v.substring(6, 8));
  int ms = getMillisInSecond();
  return (int) (h * DateTimeUtils.MILLIS_PER_HOUR
      + m * DateTimeUtils.MILLIS_PER_MINUTE
      + s * DateTimeUtils.MILLIS_PER_SECOND
      + ms);
}
 
Example #25
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Normalizes a TIME value into 00:00:00..23:59:39. */
private Expression normalize(SqlTypeName typeName, Expression e) {
  switch (typeName) {
  case TIME:
    return Expressions.call(BuiltInMethod.FLOOR_MOD.method, e,
        Expressions.constant(DateTimeUtils.MILLIS_PER_DAY));
  default:
    return e;
  }
}
 
Example #26
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 #27
Source File: SqlLimitsTest.java    From Quicksql with MIT License 5 votes vote down vote up
private void printLimit(
    PrintWriter pw,
    String desc,
    RelDataType type,
    boolean sign,
    SqlTypeName.Limit limit,
    boolean beyond) {
  Object o = ((BasicSqlType) type).getLimit(sign, limit, beyond);
  if (o == null) {
    return;
  }
  pw.print(desc);
  String s;
  if (o instanceof byte[]) {
    int k = 0;
    StringBuilder buf = new StringBuilder("{");
    for (byte b : (byte[]) o) {
      if (k++ > 0) {
        buf.append(", ");
      }
      buf.append(Integer.toHexString(b & 0xff));
    }
    buf.append("}");
    s = buf.toString();
  } else if (o instanceof Calendar) {
    Calendar calendar = (Calendar) o;
    DateFormat dateFormat = getDateFormat(type.getSqlTypeName());
    dateFormat.setTimeZone(DateTimeUtils.UTC_ZONE);
    s = dateFormat.format(calendar.getTime());
  } else {
    s = o.toString();
  }
  pw.print(s);
  SqlLiteral literal =
      type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
  pw.print("; as SQL: ");
  pw.print(literal.toSqlString(AnsiSqlDialect.DEFAULT));
  pw.println();
}
 
Example #28
Source File: RexBuilder.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Comparable zeroValue(RelDataType type) {
  switch (type.getSqlTypeName()) {
  case CHAR:
    return new NlsString(Spaces.of(type.getPrecision()), null, null);
  case VARCHAR:
    return new NlsString("", null, null);
  case BINARY:
    return new ByteString(new byte[type.getPrecision()]);
  case VARBINARY:
    return ByteString.EMPTY;
  case TINYINT:
  case SMALLINT:
  case INTEGER:
  case BIGINT:
  case DECIMAL:
  case FLOAT:
  case REAL:
  case DOUBLE:
    return BigDecimal.ZERO;
  case BOOLEAN:
    return false;
  case TIME:
  case DATE:
  case TIMESTAMP:
    return DateTimeUtils.ZERO_CALENDAR;
  case TIME_WITH_LOCAL_TIME_ZONE:
    return new TimeString(0, 0, 0);
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
    return new TimestampString(0, 0, 0, 0, 0, 0);
  default:
    throw Util.unexpected(type.getSqlTypeName());
  }
}
 
Example #29
Source File: SqlParserUtil.java    From Quicksql with MIT License 5 votes vote down vote up
public static SqlTimeLiteral parseTimeLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final DateTimeUtils.PrecisionTime pt =
      DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
          Format.PER_THREAD.get().time, DateTimeUtils.UTC_ZONE, -1);
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIME", s,
            RESOURCE.badFormat(DateTimeUtils.TIME_FORMAT_STRING).str()));
  }
  final TimeString t = TimeString.fromCalendarFields(pt.getCalendar())
      .withFraction(pt.getFraction());
  return SqlLiteral.createTime(t, pt.getPrecision(), pos);
}
 
Example #30
Source File: WindowsGrouping.java    From flink with Apache License 2.0 5 votes vote down vote up
private long getTimeValue(BaseRow row) {
	if (isDate) {
		return row.getInt(timeIndex) * DateTimeUtils.MILLIS_PER_DAY;
	} else {
		return row.getLong(timeIndex);
	}
}