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

The following examples show how to use org.apache.calcite.avatica.util.TimeUnitRange. 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: DateRangeRules.java    From calcite with 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 #2
Source File: DateRangeRules.java    From Quicksql with 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 #3
Source File: DateRangeRules.java    From Quicksql with 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 #4
Source File: DateRangeRules.java    From Quicksql with 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 #5
Source File: DateRangeRules.java    From Quicksql with 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 #6
Source File: DateRangeRules.java    From calcite with 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 #7
Source File: SqlDateTimeUtils.java    From flink with 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 #8
Source File: Granularities.java    From calcite with 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 #9
Source File: OracleSqlDialect.java    From calcite with 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 #10
Source File: SqlDateTimeUtils.java    From flink with 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 #11
Source File: DateRangeRules.java    From calcite with 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 #12
Source File: DateRangeRules.java    From Quicksql with 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 #13
Source File: DateRangeRules.java    From Quicksql with 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 #14
Source File: DateRangeRules.java    From Quicksql with 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 #15
Source File: SqlFunctionUtils.java    From flink with 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 #16
Source File: DateRangeRules.java    From calcite with 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;
  }
}
 
Example #17
Source File: DruidDateTimeUtils.java    From Quicksql with 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 #18
Source File: Granularities.java    From Quicksql with 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 #19
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 #20
Source File: DateRangeRules.java    From calcite with 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 #21
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 #22
Source File: SqlDatePartOperator.java    From dremio-oss with 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 #23
Source File: TupleFilterVisitor.java    From kylin-on-parquet-v2 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 #24
Source File: OracleSqlDialect.java    From Quicksql with 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 #25
Source File: SparkSqlDialect.java    From Quicksql with 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 #26
Source File: HsqldbSqlDialect.java    From Quicksql with 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 #27
Source File: HsqldbSqlDialect.java    From Quicksql with 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 #28
Source File: DateRangeRulesTest.java    From Quicksql with 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 #29
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 #30
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);
}