Java Code Examples for org.apache.calcite.avatica.util.TimeUnitRange

The following examples show how to use org.apache.calcite.avatica.util.TimeUnitRange. 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: flink   Source File: SqlDateTimeUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static long timestampFloor(TimeUnitRange range, long ts, TimeZone tz) {
	// assume that we are at UTC timezone, just for algorithm performance
	long offset = tz.getOffset(ts);
	long utcTs = ts + offset;

	switch (range) {
		case HOUR:
			return floor(utcTs, MILLIS_PER_HOUR) - offset;
		case DAY:
			return floor(utcTs, MILLIS_PER_DAY) - offset;
		case MONTH:
		case YEAR:
		case QUARTER:
			int days = (int) (utcTs / MILLIS_PER_DAY + EPOCH_JULIAN);
			return julianDateFloor(range, days, true) * MILLIS_PER_DAY - offset;
		default:
			// for MINUTE and SECONDS etc...,
			// it is more effective to use arithmetic Method
			throw new AssertionError(range);
	}
}
 
Example 2
Source Project: flink   Source File: SqlDateTimeUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Keep the algorithm consistent with Calcite DateTimeUtils.julianDateFloor, but here
 * we take time zone into account.
 */
public static long timestampCeil(TimeUnitRange range, long ts, TimeZone tz) {
	// assume that we are at UTC timezone, just for algorithm performance
	long offset = tz.getOffset(ts);
	long utcTs = ts + offset;

	switch (range) {
		case HOUR:
			return ceil(utcTs, MILLIS_PER_HOUR) - offset;
		case DAY:
			return ceil(utcTs, MILLIS_PER_DAY) - offset;
		case MONTH:
		case YEAR:
		case QUARTER:
			int days = (int) (utcTs / MILLIS_PER_DAY + EPOCH_JULIAN);
			return julianDateFloor(range, days, false) * MILLIS_PER_DAY - offset;
		default:
			// for MINUTE and SECONDS etc...,
			// it is more effective to use arithmetic Method
			throw new AssertionError(range);
	}
}
 
Example 3
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
@Override public Object visitCall(RexCall call) {
  switch (call.getKind()) {
  case EXTRACT:
    final RexLiteral operand = (RexLiteral) call.getOperands().get(0);
    timeUnits.add((TimeUnitRange) operand.getValue());
    break;
  case FLOOR:
  case CEIL:
    // Check that the call to FLOOR/CEIL is on date-time
    if (call.getOperands().size() == 2) {
      opKinds.add(call.getKind());
    }
    break;
  }
  return super.visitCall(call);
}
 
Example 4
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
private boolean canRewriteExtract(RexNode operand) {
  // We rely on timeUnits being sorted (so YEAR comes before MONTH
  // before HOUR) and unique. If we have seen a predicate on YEAR,
  // operandRanges will not be empty. This checks whether we can rewrite
  // the "extract" condition. For example, in the condition
  //
  //   extract(MONTH from time) = someValue
  //   OR extract(YEAR from time) = someValue
  //
  // we cannot rewrite extract on MONTH.
  if (timeUnit == TimeUnitRange.YEAR) {
    return true;
  }
  final RangeSet<Calendar> calendarRangeSet = operandRanges.get(operand);
  if (calendarRangeSet == null || calendarRangeSet.isEmpty()) {
    return false;
  }
  for (Range<Calendar> range : calendarRangeSet.asRanges()) {
    // Cannot reWrite if range does not have an upper or lower bound
    if (!range.hasUpperBound() || !range.hasLowerBound()) {
      return false;
    }
  }
  return true;
}
 
Example 5
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
private boolean next(Calendar c, TimeUnitRange timeUnit, int v,
    Range<Calendar> r, boolean strict) {
  final Calendar original = (Calendar) c.clone();
  final int code = TIME_UNIT_CODES.get(timeUnit);
  for (;;) {
    c.set(code, v);
    int v2 = c.get(code);
    if (v2 < v) {
      // E.g. when we set DAY=30 on 2014-02-01, we get 2014-02-30 because
      // February has 28 days.
      continue;
    }
    if (strict && original.compareTo(c) == 0) {
      c.add(TIME_UNIT_CODES.get(TIME_UNIT_PARENTS.get(timeUnit)), 1);
      continue;
    }
    if (!r.contains(c)) {
      return false;
    }
    return true;
  }
}
 
Example 6
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
private static boolean isValid(int v, TimeUnitRange timeUnit) {
  switch (timeUnit) {
  case YEAR:
    return v > 0;
  case MONTH:
    return v >= Calendar.JANUARY && v <= Calendar.DECEMBER;
  case DAY:
    return v > 0 && v <= 31;
  case HOUR:
    return v >= 0 && v <= 24;
  case MINUTE:
  case SECOND:
    return v >= 0 && v <= 60;
  default:
    return false;
  }
}
 
Example 7
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
private Range<Calendar> extractRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  switch (comparison) {
  case EQUALS:
    return Range.closedOpen(round(c, timeUnit, true),
        round(c, timeUnit, false));
  case LESS_THAN:
    return Range.lessThan(round(c, timeUnit, true));
  case LESS_THAN_OR_EQUAL:
    return Range.lessThan(round(c, timeUnit, false));
  case GREATER_THAN:
    return Range.atLeast(round(c, timeUnit, false));
  case GREATER_THAN_OR_EQUAL:
    return Range.atLeast(round(c, timeUnit, true));
  default:
    throw new AssertionError(comparison);
  }
}
 
Example 8
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
private RexNode compareFloorCeil(SqlKind comparison, RexNode operand,
    RexLiteral timeLiteral, TimeUnitRange timeUnit, boolean floor) {
  RangeSet<Calendar> rangeSet = operandRanges.get(operand);
  if (rangeSet == null) {
    rangeSet = ImmutableRangeSet.<Calendar>of().complement();
  }
  final RangeSet<Calendar> s2 = TreeRangeSet.create();
  final Calendar c = timestampValue(timeLiteral);
  final Range<Calendar> range = floor
      ? floorRange(timeUnit, comparison, c)
      : ceilRange(timeUnit, comparison, c);
  s2.add(range);
  // Intersect old range set with new.
  s2.removeAll(rangeSet.complement());
  operandRanges.put(operand, ImmutableRangeSet.copyOf(s2));
  if (range.isEmpty()) {
    return rexBuilder.makeLiteral(false);
  }
  return toRex(operand, range);
}
 
Example 9
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  final Calendar ceil = ceil(c, timeUnit);
  boolean boundary = ceil.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
  case LESS_THAN:
    return Range.atMost(decrement(ceil, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
  case GREATER_THAN:
    return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return Range.greaterThan(decrement(ceil, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example 10
Source Project: Quicksql   Source File: DruidDateTimeUtils.java    License: MIT License 6 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
 */
public static Granularity extractGranularity(RexNode node, String timeZone) {
  final int flagIndex;

  if (TimeExtractionFunction.isValidTimeExtract(node)) {
    flagIndex = 0;
  } else if (TimeExtractionFunction.isValidTimeFloor(node)) {
    flagIndex = 1;
  } else {
    // We can only infer granularity from floor and extract.
    return null;
  }
  final RexCall call = (RexCall) node;
  final RexLiteral flag = (RexLiteral) call.operands.get(flagIndex);
  final TimeUnitRange timeUnit = (TimeUnitRange) flag.getValue();
  return Granularities.createGranularity(timeUnit, timeZone);
}
 
Example 11
Source Project: Quicksql   Source File: Granularities.java    License: MIT License 6 votes vote down vote up
/** Creates a Granularity based on a time unit.
 *
 * <p>When used in a query, Druid will rollup and round time values based on
 * specified period and timezone. */
@Nonnull public static Granularity createGranularity(TimeUnitRange timeUnit,
                                                     String timeZone) {
  switch (timeUnit) {
  case YEAR:
    return new PeriodGranularity(Granularity.Type.YEAR, "P1Y", timeZone);
  case QUARTER:
    return new PeriodGranularity(Granularity.Type.QUARTER, "P3M", timeZone);
  case MONTH:
    return new PeriodGranularity(Granularity.Type.MONTH, "P1M", timeZone);
  case WEEK:
    return new PeriodGranularity(Granularity.Type.WEEK, "P1W", timeZone);
  case DAY:
    return new PeriodGranularity(Granularity.Type.DAY, "P1D", timeZone);
  case HOUR:
    return new PeriodGranularity(Granularity.Type.HOUR, "PT1H", timeZone);
  case MINUTE:
    return new PeriodGranularity(Granularity.Type.MINUTE, "PT1M", timeZone);
  case SECOND:
    return new PeriodGranularity(Granularity.Type.SECOND, "PT1S", timeZone);
  default:
    throw new AssertionError(timeUnit);
  }
}
 
Example 12
Source Project: Quicksql   Source File: OracleSqlDialect.java    License: MIT License 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    SqlUtil.unparseFunctionSyntax(SqlLibraryOperators.SUBSTR, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 13
Source Project: Quicksql   Source File: SparkSqlDialect.java    License: MIT License 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    SqlUtil.unparseFunctionSyntax(SPARKSQL_SUBSTRING, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "DATE_TRUNC", false);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 14
Source Project: Quicksql   Source File: HsqldbSqlDialect.java    License: MIT License 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  switch (call.getKind()) {
  case FLOOR:
    if (call.operandCount() != 2) {
      super.unparseCall(writer, call, leftPrec, rightPrec);
      return;
    }

    final SqlLiteral timeUnitNode = call.operand(1);
    final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

    final String translatedLit = convertTimeUnit(timeUnit);
    SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, translatedLit,
        timeUnitNode.getParserPosition());
    SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
    break;

  default:
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example 15
Source Project: Quicksql   Source File: HsqldbSqlDialect.java    License: MIT License 6 votes vote down vote up
private static String convertTimeUnit(TimeUnitRange unit) {
  switch (unit) {
  case YEAR:
    return "YYYY";
  case MONTH:
    return "MM";
  case DAY:
    return "DD";
  case WEEK:
    return "WW";
  case HOUR:
    return "HH24";
  case MINUTE:
    return "MI";
  case SECOND:
    return "SS";
  default:
    throw new AssertionError("could not convert time unit to HSQLDB equivalent: "
        + unit);
  }
}
 
Example 16
Source Project: Quicksql   Source File: RexInterpreter.java    License: 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 17
Source Project: Quicksql   Source File: RexInterpreter.java    License: 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 18
Source Project: Quicksql   Source File: DateRangeRulesTest.java    License: MIT License 6 votes vote down vote up
@Test public void testExtractYearFromDateColumn() {
  final Fixture2 f = new Fixture2();

  final RexNode e = f.eq(f.literal(2014), f.exYearD);
  assertThat(DateRangeRules.extractTimeUnits(e),
      is(set(TimeUnitRange.YEAR)));
  assertThat(DateRangeRules.extractTimeUnits(f.dec), is(set()));
  assertThat(DateRangeRules.extractTimeUnits(f.literal(1)), is(set()));

  // extract YEAR from a DATE column
  checkDateRange(f, e, is("AND(>=($8, 2014-01-01), <($8, 2015-01-01))"));
  checkDateRange(f, f.eq(f.exYearD, f.literal(2014)),
      is("AND(>=($8, 2014-01-01), <($8, 2015-01-01))"));
  checkDateRange(f, f.ge(f.exYearD, f.literal(2014)),
      is(">=($8, 2014-01-01)"));
  checkDateRange(f, f.gt(f.exYearD, f.literal(2014)),
      is(">=($8, 2015-01-01)"));
  checkDateRange(f, f.lt(f.exYearD, f.literal(2014)),
      is("<($8, 2014-01-01)"));
  checkDateRange(f, f.le(f.exYearD, f.literal(2014)),
      is("<($8, 2015-01-01)"));
  checkDateRange(f, f.ne(f.exYearD, f.literal(2014)),
      is("<>(EXTRACT(FLAG(YEAR), $8), 2014)"));
}
 
Example 19
Source Project: kylin-on-parquet-v2   Source File: TupleFilterVisitor.java    License: 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 20
Source Project: dremio-oss   Source File: SqlDatePartOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  final RexBuilder rexBuilder = cx.getRexBuilder();

  final SqlLiteral literal = (SqlLiteral) call.getOperandList().get(0);
  final String value = ((NlsString)literal.getValue()).getValue();
  TimeUnitRange range = VALID_PERIODS.get(value.toLowerCase());
  Preconditions.checkNotNull(range, "Unhandle range type: %s.", value);
  List<RexNode> exprs = new ArrayList<>();

  exprs.add(rexBuilder.makeFlag(range));
  exprs.add(cx.convertExpression(call.getOperandList().get(1)));

  RelDataTypeFactory typeFactory = cx.getTypeFactory();
  final RelDataType returnType
      = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT), exprs.get(1).getType().isNullable());
  return rexBuilder.makeCall(returnType, SqlStdOperatorTable.EXTRACT, exprs);
}
 
Example 21
Source Project: kylin   Source File: TupleFilterVisitor.java    License: 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 22
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private Range<Calendar> floorRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  Calendar floor = floor(c, timeUnit);
  boolean boundary = floor.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.closedOpen(floor, boundary ? increment(floor, timeUnit) : floor);
  case LESS_THAN:
    return boundary ? Range.lessThan(floor) : Range.lessThan(increment(floor, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return Range.lessThan(increment(floor, timeUnit));
  case GREATER_THAN:
    return Range.atLeast(increment(floor, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return boundary ? Range.atLeast(floor) : Range.atLeast(increment(floor, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example 23
Source Project: calcite   Source File: SqlFunctions.java    License: 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 24
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private RexNode compareFloorCeil(SqlKind comparison, RexNode operand,
    RexLiteral timeLiteral, TimeUnitRange timeUnit, boolean floor) {
  RangeSet<Calendar> rangeSet = operandRanges.get(operand);
  if (rangeSet == null) {
    rangeSet = ImmutableRangeSet.<Calendar>of().complement();
  }
  final RangeSet<Calendar> s2 = TreeRangeSet.create();
  final Calendar c = timestampValue(timeLiteral);
  final Range<Calendar> range = floor
      ? floorRange(timeUnit, comparison, c)
      : ceilRange(timeUnit, comparison, c);
  s2.add(range);
  // Intersect old range set with new.
  s2.removeAll(rangeSet.complement());
  operandRanges.put(operand, ImmutableRangeSet.copyOf(s2));
  if (range.isEmpty()) {
    return rexBuilder.makeLiteral(false);
  }
  return toRex(operand, range);
}
 
Example 25
Source Project: flink   Source File: SqlFunctionUtils.java    License: Apache License 2.0 6 votes vote down vote up
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 26
Source Project: calcite   Source File: Granularities.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates a Granularity based on a time unit.
 *
 * <p>When used in a query, Druid will rollup and round time values based on
 * specified period and timezone. */
@Nonnull public static Granularity createGranularity(TimeUnitRange timeUnit,
    String timeZone) {
  switch (timeUnit) {
  case YEAR:
    return new PeriodGranularity(Granularity.Type.YEAR, "P1Y", timeZone);
  case QUARTER:
    return new PeriodGranularity(Granularity.Type.QUARTER, "P3M", timeZone);
  case MONTH:
    return new PeriodGranularity(Granularity.Type.MONTH, "P1M", timeZone);
  case WEEK:
    return new PeriodGranularity(Granularity.Type.WEEK, "P1W", timeZone);
  case DAY:
    return new PeriodGranularity(Granularity.Type.DAY, "P1D", timeZone);
  case HOUR:
    return new PeriodGranularity(Granularity.Type.HOUR, "PT1H", timeZone);
  case MINUTE:
    return new PeriodGranularity(Granularity.Type.MINUTE, "PT1M", timeZone);
  case SECOND:
    return new PeriodGranularity(Granularity.Type.SECOND, "PT1S", timeZone);
  default:
    throw new AssertionError(timeUnit);
  }
}
 
Example 27
Source Project: calcite   Source File: OracleSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    SqlUtil.unparseFunctionSyntax(SqlLibraryOperators.SUBSTR, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 28
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
/** Replaces calls to EXTRACT, FLOOR and CEIL in an expression. */
@VisibleForTesting
public static RexNode replaceTimeUnits(RexBuilder rexBuilder, RexNode e,
    String timeZone) {
  ImmutableSortedSet<TimeUnitRange> timeUnits = extractTimeUnits(e);
  if (!timeUnits.contains(TimeUnitRange.YEAR)) {
    // Case when we have FLOOR or CEIL but no extract on YEAR.
    // Add YEAR as TimeUnit so that FLOOR gets replaced in first iteration
    // with timeUnit YEAR.
    timeUnits = ImmutableSortedSet.<TimeUnitRange>naturalOrder()
        .addAll(timeUnits).add(TimeUnitRange.YEAR).build();
  }
  final Map<RexNode, RangeSet<Calendar>> operandRanges = new HashMap<>();
  for (TimeUnitRange timeUnit : timeUnits) {
    e = e.accept(
        new ExtractShuttle(rexBuilder, timeUnit, operandRanges, timeUnits,
            timeZone));
  }
  return e;
}
 
Example 29
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
@Override public Void visitCall(RexCall call) {
  switch (call.getKind()) {
  case EXTRACT:
    final RexLiteral operand = (RexLiteral) call.getOperands().get(0);
    timeUnits.add((TimeUnitRange) operand.getValue());
    break;
  case FLOOR:
  case CEIL:
    // Check that the call to FLOOR/CEIL is on date-time
    if (call.getOperands().size() == 2) {
      opKinds.add(call.getKind());
    }
    break;
  }
  return super.visitCall(call);
}
 
Example 30
Source Project: calcite   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isValid(int v, TimeUnitRange timeUnit) {
  switch (timeUnit) {
  case YEAR:
    return v > 0;
  case MONTH:
    return v >= Calendar.JANUARY && v <= Calendar.DECEMBER;
  case DAY:
    return v > 0 && v <= 31;
  case HOUR:
    return v >= 0 && v <= 24;
  case MINUTE:
  case SECOND:
    return v >= 0 && v <= 60;
  default:
    return false;
  }
}