org.apache.calcite.sql.SqlIntervalQualifier Java Examples

The following examples show how to use org.apache.calcite.sql.SqlIntervalQualifier. 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: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testInterval() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  SqlIntervalQualifier sqlIntervalQualifier =
      new SqlIntervalQualifier(TimeUnit.DAY, TimeUnit.DAY, SqlParserPos.ZERO);
  BigDecimal value = new BigDecimal(86400000);
  RexLiteral intervalLiteral = builder.getRexBuilder()
      .makeIntervalLiteral(value, sqlIntervalQualifier);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(
              SqlStdOperatorTable.TUMBLE_END,
              builder.field("HIREDATE"),
              intervalLiteral))
      .build();
  RelJsonWriter jsonWriter = new RelJsonWriter();
  rel.explain(jsonWriter);
  String relJson = jsonWriter.asString();
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[TUMBLE_END($4, 86400000:INTERVAL DAY)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #2
Source File: MssqlSqlDialect.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
  switch (qualifier.timeUnitRange) {
  case YEAR:
  case QUARTER:
  case MONTH:
  case WEEK:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MILLISECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("End unit is not supported now: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example #3
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static long intervalToMillis(
    String literal,
    SqlIntervalQualifier intervalQualifier) {
  Preconditions.checkArgument(!intervalQualifier.isYearMonth(),
      "interval must be day time");
  int[] ret;
  try {
    ret = intervalQualifier.evaluateIntervalLiteral(literal,
        intervalQualifier.getParserPosition(), RelDataTypeSystem.DEFAULT);
    assert ret != null;
  } catch (CalciteContextException e) {
    throw new RuntimeException("while parsing day-to-second interval "
        + literal, e);
  }
  long l = 0;
  long[] conv = new long[5];
  conv[4] = 1; // millisecond
  conv[3] = conv[4] * 1000; // second
  conv[2] = conv[3] * 60; // minute
  conv[1] = conv[2] * 60; // hour
  conv[0] = conv[1] * 24; // day
  for (int i = 1; i < ret.length; i++) {
    l += conv[i - 1] * ret[i];
  }
  return ret[0] * l;
}
 
Example #4
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static long intervalToMonths(
    String literal,
    SqlIntervalQualifier intervalQualifier) {
  Preconditions.checkArgument(intervalQualifier.isYearMonth(),
      "interval must be year month");
  int[] ret;
  try {
    ret = intervalQualifier.evaluateIntervalLiteral(literal,
        intervalQualifier.getParserPosition(), RelDataTypeSystem.DEFAULT);
    assert ret != null;
  } catch (CalciteContextException e) {
    throw new RuntimeException("Error while parsing year-to-month interval "
        + literal, e);
  }

  long l = 0;
  long[] conv = new long[2];
  conv[1] = 1; // months
  conv[0] = conv[1] * 12; // years
  for (int i = 1; i < ret.length; i++) {
    l += conv[i - 1] * ret[i];
  }
  return ret[0] * l;
}
 
Example #5
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Given a {@link SqlTypeName} and nullability, create a RelDataType from the RelDataTypeFactory
 *
 * @param typeFactory RelDataTypeFactory used to create the RelDataType
 * @param sqlTypeName the given SqlTypeName
 * @param isNullable  the nullability of the created RelDataType
 * @return RelDataType Type of call
 */
public static RelDataType createCalciteTypeWithNullability(RelDataTypeFactory typeFactory,
                                                           SqlTypeName sqlTypeName,
                                                           boolean isNullable) {
  RelDataType type;
  if (sqlTypeName.getFamily() == SqlTypeFamily.INTERVAL_DAY_TIME) {
    type = typeFactory.createSqlIntervalType(
        new SqlIntervalQualifier(
            TimeUnit.DAY,
            TimeUnit.MINUTE,
            SqlParserPos.ZERO));
  } else if (sqlTypeName.getFamily() == SqlTypeFamily.INTERVAL_YEAR_MONTH) {
    type = typeFactory.createSqlIntervalType(
        new SqlIntervalQualifier(
            TimeUnit.YEAR,
            TimeUnit.MONTH,
            SqlParserPos.ZERO));
  } else if (sqlTypeName == SqlTypeName.VARCHAR) {
    type = typeFactory.createSqlType(sqlTypeName, Types.MAX_VARCHAR_LENGTH);
  } else {
    type = typeFactory.createSqlType(sqlTypeName);
  }
  return typeFactory.createTypeWithNullability(type, isNullable);
}
 
Example #6
Source File: MssqlSqlDialect.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
  switch (qualifier.timeUnitRange) {
  case YEAR:
  case QUARTER:
  case MONTH:
  case WEEK:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MILLISECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("End unit is not supported now: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example #7
Source File: SqlParserUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
public static long intervalToMillis(
    String literal,
    SqlIntervalQualifier intervalQualifier) {
  Preconditions.checkArgument(!intervalQualifier.isYearMonth(),
      "interval must be day time");
  int[] ret;
  try {
    ret = intervalQualifier.evaluateIntervalLiteral(literal,
        intervalQualifier.getParserPosition(), RelDataTypeSystem.DEFAULT);
    assert ret != null;
  } catch (CalciteContextException e) {
    throw new RuntimeException("while parsing day-to-second interval "
        + literal, e);
  }
  long l = 0;
  long[] conv = new long[5];
  conv[4] = 1; // millisecond
  conv[3] = conv[4] * 1000; // second
  conv[2] = conv[3] * 60; // minute
  conv[1] = conv[2] * 60; // hour
  conv[0] = conv[1] * 24; // day
  for (int i = 1; i < ret.length; i++) {
    l += conv[i - 1] * ret[i];
  }
  return ret[0] * l;
}
 
Example #8
Source File: SqlParserUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
public static long intervalToMonths(
    String literal,
    SqlIntervalQualifier intervalQualifier) {
  Preconditions.checkArgument(intervalQualifier.isYearMonth(),
      "interval must be year month");
  int[] ret;
  try {
    ret = intervalQualifier.evaluateIntervalLiteral(literal,
        intervalQualifier.getParserPosition(), RelDataTypeSystem.DEFAULT);
    assert ret != null;
  } catch (CalciteContextException e) {
    throw new RuntimeException("Error while parsing year-to-month interval "
        + literal, e);
  }

  long l = 0;
  long[] conv = new long[2];
  conv[1] = 1; // months
  conv[0] = conv[1] * 12; // years
  for (int i = 1; i < ret.length; i++) {
    l += conv[i - 1] * ret[i];
  }
  return ret[0] * l;
}
 
Example #9
Source File: View.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@JsonCreator
public FieldType(
    @JsonProperty("name")                       String name,
    @JsonProperty("type")                       SqlTypeName type,
    @JsonProperty("precision")                  Integer precision,
    @JsonProperty("scale")                      Integer scale,
    @JsonProperty("startUnit")                  TimeUnit startUnit,
    @JsonProperty("endUnit")                    TimeUnit endUnit,
    @JsonProperty("fractionalSecondPrecision")  Integer fractionalSecondPrecision,
    @JsonProperty("isNullable")                 Boolean isNullable) {
  this.name = name;
  this.type = type;
  this.precision = precision;
  this.scale = scale;
  this.intervalQualifier =
      null == startUnit
      ? null
      : new SqlIntervalQualifier(
          startUnit, precision, endUnit, fractionalSecondPrecision, SqlParserPos.ZERO );

  // Property "isNullable" is not part of the initial view definition and
  // was added in DRILL-2342.  If the default value is null, consider it as
  // "true".  It is safe to default to "nullable" than "required" type.
  this.isNullable = isNullable == null ? true : isNullable;
}
 
Example #10
Source File: SqlParserUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static SqlIntervalLiteral parseIntervalLiteral(SqlParserPos pos,
    int sign, String s, SqlIntervalQualifier intervalQualifier) {
  final String intervalStr = parseString(s);
  if (intervalStr.equals("")) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalIntervalLiteral(s + " "
            + intervalQualifier.toString(), pos.toString()));
  }
  return SqlLiteral.createInterval(sign, intervalStr, intervalQualifier, pos);
}
 
Example #11
Source File: SqlDatePartFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final SqlParserPos pos = call.getParserPosition();
  return SqlStdOperatorTable.EXTRACT.createCall(pos,
      new SqlIntervalQualifier(timeUnit, null, SqlParserPos.ZERO),
      operands.get(0));
}
 
Example #12
Source File: SqlNodeToRexConverterImpl.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexLiteral convertInterval(
    SqlRexContext cx,
    SqlIntervalQualifier intervalQualifier) {
  RexBuilder rexBuilder = cx.getRexBuilder();

  return rexBuilder.makeIntervalLiteral(intervalQualifier);
}
 
Example #13
Source File: RexBuilder.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal representing an interval value, for example
 * {@code INTERVAL '3-7' YEAR TO MONTH}.
 */
public RexLiteral makeIntervalLiteral(
    BigDecimal v,
    SqlIntervalQualifier intervalQualifier) {
  return makeLiteral(
      v,
      typeFactory.createSqlIntervalType(intervalQualifier),
      intervalQualifier.typeName());
}
 
Example #14
Source File: ConvMaster.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSqlNodeEqual(SqlNode queryNode, SqlNode exprNode) {
    if (queryNode != null && exprNode != null) {
        if (exprNode instanceof SqlIdentifier) {
            int parsedIdx = ParamNodeParser.parseParamIdx(exprNode.toString());
            if (parsedIdx >= 0) {
                SqlNode matchedBefore = matchedNodesMap.get(parsedIdx);
                if (matchedBefore != null) {
                    return ExpressionComparator.isNodeEqual(queryNode, matchedBefore, this);
                } else {
                    matchedNodesMap.put(parsedIdx, queryNode);
                    return true;
                }
            }
        } else if (exprNode instanceof SqlIntervalQualifier) {
            if (!(queryNode instanceof SqlIntervalQualifier)) {
                return false;
            }
            SqlIntervalQualifier thisNode = (SqlIntervalQualifier) queryNode;
            SqlIntervalQualifier thatNode = (SqlIntervalQualifier) exprNode;
            return thisNode.toString().equals(thatNode.toString());
        } else if (exprNode instanceof SqlWindow) {
            if (!(queryNode instanceof SqlWindow)) {
                return false;
            }
            if (((SqlWindow) exprNode).getRefName() instanceof SqlIdentifier) {
                return true;
            }
        }

    }

    return super.isSqlNodeEqual(queryNode, exprNode);
}
 
Example #15
Source File: RelDataTypeFactory.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a field with an interval type.
 */
public Builder add(String name, TimeUnit startUnit, int startPrecision,
    TimeUnit endUnit, int fractionalSecondPrecision) {
  final SqlIntervalQualifier q =
      new SqlIntervalQualifier(startUnit, startPrecision, endUnit,
          fractionalSecondPrecision, SqlParserPos.ZERO);
  add(name, typeFactory.createSqlIntervalType(q));
  return this;
}
 
Example #16
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPADD(unit, count, timestamp)
  //  => timestamp + count * INTERVAL '1' UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  RexNode interval2Add;
  SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
  RexNode op1 = cx.convertExpression(call.operand(1));
  switch (unit) {
  case MICROSECOND:
  case NANOSECOND:
    interval2Add =
        divide(rexBuilder,
            multiply(rexBuilder,
                rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
            BigDecimal.ONE.divide(unit.multiplier,
                RoundingMode.UNNECESSARY));
    break;
  default:
    interval2Add = multiply(rexBuilder,
        rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
  }

  return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
      cx.convertExpression(call.operand(2)), interval2Add);
}
 
Example #17
Source File: IntervalSqlType.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an IntervalSqlType. This should only be called from a factory
 * method.
 */
public IntervalSqlType(RelDataTypeSystem typeSystem,
    SqlIntervalQualifier intervalQualifier,
    boolean isNullable) {
  super(intervalQualifier.typeName(), isNullable, null);
  this.typeSystem = Objects.requireNonNull(typeSystem);
  this.intervalQualifier = Objects.requireNonNull(intervalQualifier);
  computeDigest();
}
 
Example #18
Source File: MysqlSqlDialect.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {

  //  Unit Value         | Expected Format
  // --------------------+-------------------------------------------
  //  MICROSECOND        | MICROSECONDS
  //  SECOND             | SECONDS
  //  MINUTE             | MINUTES
  //  HOUR               | HOURS
  //  DAY                | DAYS
  //  WEEK               | WEEKS
  //  MONTH              | MONTHS
  //  QUARTER            | QUARTERS
  //  YEAR               | YEARS
  //  MINUTE_SECOND      | 'MINUTES:SECONDS'
  //  HOUR_MINUTE        | 'HOURS:MINUTES'
  //  DAY_HOUR           | 'DAYS HOURS'
  //  YEAR_MONTH         | 'YEARS-MONTHS'
  //  MINUTE_MICROSECOND | 'MINUTES:SECONDS.MICROSECONDS'
  //  HOUR_MICROSECOND   | 'HOURS:MINUTES:SECONDS.MICROSECONDS'
  //  SECOND_MICROSECOND | 'SECONDS.MICROSECONDS'
  //  DAY_MINUTE         | 'DAYS HOURS:MINUTES'
  //  DAY_MICROSECOND    | 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
  //  DAY_SECOND         | 'DAYS HOURS:MINUTES:SECONDS'
  //  HOUR_SECOND        | 'HOURS:MINUTES:SECONDS'

  if (!qualifier.useDefaultFractionalSecondPrecision()) {
    throw new AssertionError("Fractional second precision is not supported now ");
  }

  final String start = validate(qualifier.timeUnitRange.startUnit).name();
  if (qualifier.timeUnitRange.startUnit == TimeUnit.SECOND
      || qualifier.timeUnitRange.endUnit == null) {
    writer.keyword(start);
  } else {
    writer.keyword(start + "_" + qualifier.timeUnitRange.endUnit.name());
  }
}
 
Example #19
Source File: SqlDatePartFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final SqlParserPos pos = call.getParserPosition();
  return SqlStdOperatorTable.EXTRACT.createCall(pos,
      new SqlIntervalQualifier(timeUnit, null, SqlParserPos.ZERO),
      operands.get(0));
}
 
Example #20
Source File: MergeTableLikeUtilTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlNode boundedStrategy(String rowtimeColumn, String delay) {
	return new SqlBasicCall(
		SqlStdOperatorTable.MINUS,
		new SqlNode[]{
			identifier(rowtimeColumn),
			SqlLiteral.createInterval(
				1,
				delay,
				new SqlIntervalQualifier(TimeUnit.SECOND, TimeUnit.SECOND, SqlParserPos.ZERO),
				SqlParserPos.ZERO)
		},
		SqlParserPos.ZERO
	);
}
 
Example #21
Source File: MysqlSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {

  //  Unit Value         | Expected Format
  // --------------------+-------------------------------------------
  //  MICROSECOND        | MICROSECONDS
  //  SECOND             | SECONDS
  //  MINUTE             | MINUTES
  //  HOUR               | HOURS
  //  DAY                | DAYS
  //  WEEK               | WEEKS
  //  MONTH              | MONTHS
  //  QUARTER            | QUARTERS
  //  YEAR               | YEARS
  //  MINUTE_SECOND      | 'MINUTES:SECONDS'
  //  HOUR_MINUTE        | 'HOURS:MINUTES'
  //  DAY_HOUR           | 'DAYS HOURS'
  //  YEAR_MONTH         | 'YEARS-MONTHS'
  //  MINUTE_MICROSECOND | 'MINUTES:SECONDS.MICROSECONDS'
  //  HOUR_MICROSECOND   | 'HOURS:MINUTES:SECONDS.MICROSECONDS'
  //  SECOND_MICROSECOND | 'SECONDS.MICROSECONDS'
  //  DAY_MINUTE         | 'DAYS HOURS:MINUTES'
  //  DAY_MICROSECOND    | 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
  //  DAY_SECOND         | 'DAYS HOURS:MINUTES:SECONDS'
  //  HOUR_SECOND        | 'HOURS:MINUTES:SECONDS'

  if (!qualifier.useDefaultFractionalSecondPrecision()) {
    throw new AssertionError("Fractional second precision is not supported now ");
  }

  final String start = validate(qualifier.timeUnitRange.startUnit).name();
  if (qualifier.timeUnitRange.startUnit == TimeUnit.SECOND
      || qualifier.timeUnitRange.endUnit == null) {
    writer.keyword(start);
  } else {
    writer.keyword(start + "_" + qualifier.timeUnitRange.endUnit.name());
  }
}
 
Example #22
Source File: IntervalSqlType.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an IntervalSqlType. This should only be called from a factory
 * method.
 */
public IntervalSqlType(RelDataTypeSystem typeSystem,
    SqlIntervalQualifier intervalQualifier,
    boolean isNullable) {
  super(intervalQualifier.typeName(), isNullable, null);
  this.typeSystem = Objects.requireNonNull(typeSystem);
  this.intervalQualifier = Objects.requireNonNull(intervalQualifier);
  computeDigest();
}
 
Example #23
Source File: Db2SqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {

  // DB2 supported qualifiers. Singular form of these keywords are also acceptable.
  // YEAR/YEARS
  // MONTH/MONTHS
  // DAY/DAYS
  // HOUR/HOURS
  // MINUTE/MINUTES
  // SECOND/SECONDS

  switch (qualifier.timeUnitRange) {
  case YEAR:
  case MONTH:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("Unsupported end unit: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example #24
Source File: BigQuerySqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(
        SqlWriter writer, SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
  final String start = validate(qualifier.timeUnitRange.startUnit).name();
  if (qualifier.timeUnitRange.endUnit == null) {
    writer.keyword(start);
  } else {
    throw new RuntimeException("Range time unit is not supported for BigQuery.");
  }
}
 
Example #25
Source File: RexBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal representing an interval value, for example
 * {@code INTERVAL '3-7' YEAR TO MONTH}.
 */
public RexLiteral makeIntervalLiteral(
    BigDecimal v,
    SqlIntervalQualifier intervalQualifier) {
  return makeLiteral(
      v,
      typeFactory.createSqlIntervalType(intervalQualifier),
      intervalQualifier.typeName());
}
 
Example #26
Source File: DrillExtractConvertlet.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = new LinkedList<>();

  String timeUnit = ((SqlIntervalQualifier) operands.get(0)).timeUnitRange.toString();

  RelDataTypeFactory typeFactory = cx.getTypeFactory();

  //RelDataType nullableReturnType =

  for (SqlNode node: operands) {
     exprs.add(cx.convertExpression(node));
  }

  final RelDataType returnType;
  if(call.getOperator() == SqlStdOperatorTable.EXTRACT) {
    // Legacy code:
    // The return type is wrong!
    // Legacy code choose SqlTypeName.BIGINT simply to avoid conflicting against Calcite's inference mechanism
    // (, which chose BIGINT in validation phase already)
    // Determine NULL-able using 2nd argument's Null-able.
    returnType = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT), exprs.get(1).getType().isNullable());
  } else {
    // Determine NULL-able using 2nd argument's Null-able.
    returnType = typeFactory.createTypeWithNullability(
        typeFactory.createSqlType(
            TypeInferenceUtils.getSqlTypeNameForTimeUnit(timeUnit)),
        exprs.get(1).getType().isNullable());
  }

  return rexBuilder.makeCall(returnType, call.getOperator(), exprs);
}
 
Example #27
Source File: View.java    From Bats with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public Field(
    @JsonProperty("name")                       String name,
    @JsonProperty("type")                       SqlTypeName type,
    @JsonProperty("precision")                  Integer precision,
    @JsonProperty("scale")                      Integer scale,
    @JsonProperty("startUnit")                  TimeUnit startUnit,
    @JsonProperty("endUnit")                    TimeUnit endUnit,
    @JsonProperty("fractionalSecondPrecision")  Integer fractionalSecondPrecision,
    @JsonProperty("isNullable")                 Boolean isNullable,
    @JsonProperty("keyType") Field keyType,
    @JsonProperty("valueType") Field valueType) {
  // Fix for views which were created on Calcite 1.4.
  // After Calcite upgrade star "*" was changed on dynamic star "**" (SchemaPath.DYNAMIC_STAR)
  // and type of star was changed to SqlTypeName.DYNAMIC_STAR
  this.name = "*".equals(name) ? SchemaPath.DYNAMIC_STAR : name;
  this.type = "*".equals(name) && type == SqlTypeName.ANY ? SqlTypeName.DYNAMIC_STAR : type;
  this.precision = precision;
  this.scale = scale;
  this.intervalQualifier =
      null == startUnit
      ? null
      : new SqlIntervalQualifier(
          startUnit, precision, endUnit, fractionalSecondPrecision, SqlParserPos.ZERO );

  // Property "isNullable" is not part of the initial view definition and
  // was added in DRILL-2342.  If the default value is null, consider it as
  // "true".  It is safe to default to "nullable" than "required" type.
  this.isNullable = isNullable == null || isNullable;
  this.keyType = keyType;
  this.valueType = valueType;
}
 
Example #28
Source File: RelDataTypeFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a field with an interval type.
 */
public Builder add(String name, TimeUnit startUnit, int startPrecision,
    TimeUnit endUnit, int fractionalSecondPrecision) {
  final SqlIntervalQualifier q =
      new SqlIntervalQualifier(startUnit, startPrecision, endUnit,
          fractionalSecondPrecision, SqlParserPos.ZERO);
  add(name, typeFactory.createSqlIntervalType(q));
  return this;
}
 
Example #29
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static SqlIntervalLiteral parseIntervalLiteral(SqlParserPos pos,
    int sign, String s, SqlIntervalQualifier intervalQualifier) {
  final String intervalStr = parseString(s);
  if (intervalStr.equals("")) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalIntervalLiteral(s + " "
            + intervalQualifier.toString(), pos.toString()));
  }
  return SqlLiteral.createInterval(sign, intervalStr, intervalQualifier, pos);
}
 
Example #30
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPADD(unit, count, timestamp)
  //  => timestamp + count * INTERVAL '1' UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  RexNode interval2Add;
  SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
  RexNode op1 = cx.convertExpression(call.operand(1));
  switch (unit) {
  case MICROSECOND:
  case NANOSECOND:
    interval2Add =
        divide(rexBuilder,
            multiply(rexBuilder,
                rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
            BigDecimal.ONE.divide(unit.multiplier,
                RoundingMode.UNNECESSARY));
    break;
  default:
    interval2Add = multiply(rexBuilder,
        rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
  }

  return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
      cx.convertExpression(call.operand(2)), interval2Add);
}