Java Code Examples for org.apache.calcite.sql.SqlLiteral#getValue()

The following examples show how to use org.apache.calcite.sql.SqlLiteral#getValue() . 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: ExplainHandler.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
  SqlExplain node = unwrap(sqlNode, SqlExplain.class);
  SqlLiteral op = node.operand(2);
  SqlExplain.Depth depth = (SqlExplain.Depth) op.getValue();
  if (node.getDetailLevel() != null) {
    level = node.getDetailLevel();
  }
  switch (depth) {
  case LOGICAL:
    mode = ResultMode.LOGICAL;
    break;
  case PHYSICAL:
    mode = ResultMode.PHYSICAL;
    break;
  default:
    throw new UnsupportedOperationException("Unknown depth " + depth);
  }

  return node.operand(0);
}
 
Example 2
Source File: MssqlSqlDialect.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Unparses datetime floor for Microsoft SQL Server.
 * There is no TRUNC function, so simulate this using calls to CONVERT.
 *
 * @param writer Writer
 * @param call Call
 */
private void unparseFloor(SqlWriter writer, SqlCall call) {
  SqlLiteral node = call.operand(1);
  TimeUnitRange unit = (TimeUnitRange) node.getValue();

  switch (unit) {
  case YEAR:
    unparseFloorWithUnit(writer, call, 4, "-01-01");
    break;
  case MONTH:
    unparseFloorWithUnit(writer, call, 7, "-01");
    break;
  case WEEK:
    writer.print("CONVERT(DATETIME, CONVERT(VARCHAR(10), "
        + "DATEADD(day, - (6 + DATEPART(weekday, ");
    call.operand(0).unparse(writer, 0, 0);
    writer.print(")) % 7, ");
    call.operand(0).unparse(writer, 0, 0);
    writer.print("), 126))");
    break;
  case DAY:
    unparseFloorWithUnit(writer, call, 10, "");
    break;
  case HOUR:
    unparseFloorWithUnit(writer, call, 13, ":00:00");
    break;
  case MINUTE:
    unparseFloorWithUnit(writer, call, 16, ":00");
    break;
  case SECOND:
    unparseFloorWithUnit(writer, call, 19, ":00");
    break;
  default:
    throw new IllegalArgumentException("MSSQL does not support FLOOR for time unit: "
        + unit);
  }
}
 
Example 3
Source File: SetOptionHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static Object sqlLiteralToObject(final SqlLiteral literal) {
  final Object object = literal.getValue();
  final SqlTypeName typeName = literal.getTypeName();
  switch (typeName) {
  case DECIMAL: {
    final BigDecimal bigDecimal = (BigDecimal) object;
    if (bigDecimal.scale() == 0) {
      return bigDecimal.longValue();
    } else {
      return bigDecimal.doubleValue();
    }
  }

  case DOUBLE:
  case FLOAT:
    return ((BigDecimal) object).doubleValue();

  case SMALLINT:
  case TINYINT:
  case BIGINT:
  case INTEGER:
    return ((BigDecimal) object).longValue();

  case VARBINARY:
  case VARCHAR:
  case CHAR:
    return ((NlsString) object).getValue().toString();

  case BOOLEAN:
    return object;

  default:
    throw UserException.validationError()
      .message("Drill doesn't support assigning literals of type %s in SET statements.", typeName)
      .build(logger);
  }
}
 
Example 4
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void validateLiteralAsDouble(SqlLiteral literal) {
	BigDecimal bd = (BigDecimal) literal.getValue();
	double d = bd.doubleValue();
	if (Double.isInfinite(d) || Double.isNaN(d)) {
		// overflow
		throw newValidationError(literal,
			RESOURCE.numberLiteralOutOfRange(Util.toScientificNotation(bd)));
	}

	// REVIEW jvs 4-Aug-2004:  what about underflow?
}
 
Example 5
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private void validateLiteralAsDouble(SqlLiteral literal) {
	BigDecimal bd = (BigDecimal) literal.getValue();
	double d = bd.doubleValue();
	if (Double.isInfinite(d) || Double.isNaN(d)) {
		// overflow
		throw newValidationError(literal,
			RESOURCE.numberLiteralOutOfRange(Util.toScientificNotation(bd)));
	}

	// REVIEW jvs 4-Aug-2004:  what about underflow?
}
 
Example 6
Source File: AlterTableSetOptionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static AttributeValue createAttributeValue(final SqlLiteral literal) {
  final Object object = literal.getValue();
  final SqlTypeName typeName = literal.getTypeName();
  switch (typeName) {
    case DOUBLE:
    case FLOAT:
      return AttributeValue.of(((BigDecimal) object).doubleValue());

    case SMALLINT:
    case TINYINT:
    case BIGINT:
    case INTEGER:
      return AttributeValue.of(((BigDecimal) object).longValue());

    case VARBINARY:
    case VARCHAR:
    case CHAR:
      return AttributeValue.of(((NlsString) object).getValue());

    case BOOLEAN:
      return AttributeValue.of((Boolean) object);

    default:
      throw UserException.validationError()
          .message("Dremio doesn't support assigning literals of type %s in SET statements.", typeName)
          .buildSilently();
  }
}
 
Example 7
Source File: SetOptionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static OptionValue createOptionValue(final String name, final OptionValue.OptionType type,
                                             final SqlLiteral literal) {
  final Object object = literal.getValue();
  final SqlTypeName typeName = literal.getTypeName();
  switch (typeName) {
  case DECIMAL: {
    final BigDecimal bigDecimal = (BigDecimal) object;
    if (bigDecimal.scale() == 0) {
      return OptionValue.createLong(type, name, bigDecimal.longValue());
    } else {
      return OptionValue.createDouble(type, name, bigDecimal.doubleValue());
    }
  }

  case DOUBLE:
  case FLOAT:
    return OptionValue.createDouble(type, name, ((BigDecimal) object).doubleValue());

  case SMALLINT:
  case TINYINT:
  case BIGINT:
  case INTEGER:
    return OptionValue.createLong(type, name, ((BigDecimal) object).longValue());

  case VARBINARY:
  case VARCHAR:
  case CHAR:
    return OptionValue.createString(type, name, ((NlsString) object).getValue());

  case BOOLEAN:
    return OptionValue.createBoolean(type, name, (Boolean) object);

  default:
    throw UserException.validationError()
      .message("Dremio doesn't support assigning literals of type %s in SET statements.", typeName)
      .build(logger);
  }
}
 
Example 8
Source File: MssqlSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Unparses datetime floor for Microsoft SQL Server.
 * There is no TRUNC function, so simulate this using calls to CONVERT.
 *
 * @param writer Writer
 * @param call Call
 */
private void unparseFloor(SqlWriter writer, SqlCall call) {
  SqlLiteral node = call.operand(1);
  TimeUnitRange unit = (TimeUnitRange) node.getValue();

  switch (unit) {
  case YEAR:
    unparseFloorWithUnit(writer, call, 4, "-01-01");
    break;
  case MONTH:
    unparseFloorWithUnit(writer, call, 7, "-01");
    break;
  case WEEK:
    writer.print("CONVERT(DATETIME, CONVERT(VARCHAR(10), "
        + "DATEADD(day, - (6 + DATEPART(weekday, ");
    call.operand(0).unparse(writer, 0, 0);
    writer.print(")) % 7, ");
    call.operand(0).unparse(writer, 0, 0);
    writer.print("), 126))");
    break;
  case DAY:
    unparseFloorWithUnit(writer, call, 10, "");
    break;
  case HOUR:
    unparseFloorWithUnit(writer, call, 13, ":00:00");
    break;
  case MINUTE:
    unparseFloorWithUnit(writer, call, 16, ":00");
    break;
  case SECOND:
    unparseFloorWithUnit(writer, call, 19, ":00");
    break;
  default:
    throw new IllegalArgumentException("MSSQL does not support FLOOR for time unit: "
        + unit);
  }
}
 
Example 9
Source File: ClickHouseSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Unparses datetime floor for ClickHouse.
 *
 * @param writer Writer
 * @param call Call
 */
private void unparseFloor(SqlWriter writer, SqlCall call) {
  final SqlLiteral timeUnitNode = call.operand(1);
  TimeUnitRange unit = (TimeUnitRange) timeUnitNode.getValue();

  String funName;
  switch (unit) {
  case YEAR:
    funName = "toStartOfYear";
    break;
  case MONTH:
    funName = "toStartOfMonth";
    break;
  case WEEK:
    funName = "toMonday";
    break;
  case DAY:
    funName = "toDate";
    break;
  case HOUR:
    funName = "toStartOfHour";
    break;
  case MINUTE:
    funName = "toStartOfMinute";
    break;
  default:
    throw new RuntimeException("ClickHouse does not support FLOOR for time unit: "
        + unit);
  }

  writer.print(funName);
  SqlWriter.Frame frame = writer.startList("(", ")");
  call.operand(0).unparse(writer, 0, 0);
  writer.endList(frame);
}
 
Example 10
Source File: SqlNodeToRexConverterImpl.java    From Bats with Apache License 2.0 4 votes vote down vote up
public RexNode convertLiteral(
    SqlRexContext cx,
    SqlLiteral literal) {
  RexBuilder rexBuilder = cx.getRexBuilder();
  RelDataTypeFactory typeFactory = cx.getTypeFactory();
  SqlValidator validator = cx.getValidator();
  if (literal.getValue() == null) {
    // Since there is no eq. RexLiteral of SqlLiteral.Unknown we
    // treat it as a cast(null as boolean)
    RelDataType type;
    if (literal.getTypeName() == SqlTypeName.BOOLEAN) {
      type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
      type = typeFactory.createTypeWithNullability(type, true);
    } else {
      type = validator.getValidatedNodeType(literal);
    }
    return rexBuilder.makeCast(
        type,
        rexBuilder.constantNull());
  }

  BitString bitString;
  SqlIntervalLiteral.IntervalValue intervalValue;
  long l;

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

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

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

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

  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
  case INTERVAL_DAY:
  case INTERVAL_DAY_HOUR:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    SqlIntervalQualifier sqlIntervalQualifier =
        literal.getValueAs(SqlIntervalLiteral.IntervalValue.class)
            .getIntervalQualifier();
    return rexBuilder.makeIntervalLiteral(
        literal.getValueAs(BigDecimal.class),
        sqlIntervalQualifier);
  default:
    throw Util.unexpected(literal.getTypeName());
  }
}
 
Example 11
Source File: SqlLiteralChainOperator.java    From Bats with Apache License 2.0 4 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startList("", "");
  SqlCollation collation = null;
  for (Ord<SqlNode> operand : Ord.zip(call.getOperandList())) {
    SqlLiteral rand = (SqlLiteral) operand.e;
    if (operand.i > 0) {
      // SQL:2003 says there must be a newline between string
      // fragments.
      writer.newlineAndIndent();
    }
    if (rand instanceof SqlCharStringLiteral) {
      NlsString nls = ((SqlCharStringLiteral) rand).getNlsString();
      if (operand.i == 0) {
        collation = nls.getCollation();

        // print with prefix
        writer.literal(nls.asSql(true, false));
      } else {
        // print without prefix
        writer.literal(nls.asSql(false, false));
      }
    } else if (operand.i == 0) {
      // print with prefix
      rand.unparse(writer, leftPrec, rightPrec);
    } else {
      // print without prefix
      if (rand.getTypeName() == SqlTypeName.BINARY) {
        BitString bs = (BitString) rand.getValue();
        writer.literal("'" + bs.toHexString() + "'");
      } else {
        writer.literal("'" + rand.toValue() + "'");
      }
    }
  }
  if (collation != null) {
    collation.unparse(writer, 0, 0);
  }
  writer.endList(frame);
}
 
Example 12
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
public void validateLiteral(SqlLiteral literal) {
	switch (literal.getTypeName()) {
		case DECIMAL:
			// Decimal and long have the same precision (as 64-bit integers), so
			// the unscaled value of a decimal must fit into a long.

			// REVIEW jvs 4-Aug-2004:  This should probably be calling over to
			// the available calculator implementations to see what they
			// support.  For now use ESP instead.
			//
			// jhyde 2006/12/21: I think the limits should be baked into the
			// type system, not dependent on the calculator implementation.
			BigDecimal bd = (BigDecimal) literal.getValue();
			BigInteger unscaled = bd.unscaledValue();
			long longValue = unscaled.longValue();
			if (!BigInteger.valueOf(longValue).equals(unscaled)) {
				// overflow
				throw newValidationError(literal,
					RESOURCE.numberLiteralOutOfRange(bd.toString()));
			}
			break;

		case DOUBLE:
			validateLiteralAsDouble(literal);
			break;

		case BINARY:
			final BitString bitString = (BitString) literal.getValue();
			if ((bitString.getBitCount() % 8) != 0) {
				throw newValidationError(literal, RESOURCE.binaryLiteralOdd());
			}
			break;

		case DATE:
		case TIME:
		case TIMESTAMP:
			Calendar calendar = literal.getValueAs(Calendar.class);
			final int year = calendar.get(Calendar.YEAR);
			final int era = calendar.get(Calendar.ERA);
			if (year < 1 || era == GregorianCalendar.BC || year > 9999) {
				throw newValidationError(literal,
					RESOURCE.dateLiteralOutOfRange(literal.toString()));
			}
			break;

		case INTERVAL_YEAR:
		case INTERVAL_YEAR_MONTH:
		case INTERVAL_MONTH:
		case INTERVAL_DAY:
		case INTERVAL_DAY_HOUR:
		case INTERVAL_DAY_MINUTE:
		case INTERVAL_DAY_SECOND:
		case INTERVAL_HOUR:
		case INTERVAL_HOUR_MINUTE:
		case INTERVAL_HOUR_SECOND:
		case INTERVAL_MINUTE:
		case INTERVAL_MINUTE_SECOND:
		case INTERVAL_SECOND:
			if (literal instanceof SqlIntervalLiteral) {
				SqlIntervalLiteral.IntervalValue interval =
					(SqlIntervalLiteral.IntervalValue)
						literal.getValue();
				SqlIntervalQualifier intervalQualifier =
					interval.getIntervalQualifier();

				// ensure qualifier is good before attempting to validate literal
				validateIntervalQualifier(intervalQualifier);
				String intervalStr = interval.getIntervalLiteral();
				// throws CalciteContextException if string is invalid
				int[] values = intervalQualifier.evaluateIntervalLiteral(intervalStr,
					literal.getParserPosition(), typeFactory.getTypeSystem());
				Util.discard(values);
			}
			break;
		default:
			// default is to do nothing
	}
}
 
Example 13
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
public void validateLiteral(SqlLiteral literal) {
	switch (literal.getTypeName()) {
		case DECIMAL:
			// Decimal and long have the same precision (as 64-bit integers), so
			// the unscaled value of a decimal must fit into a long.

			// REVIEW jvs 4-Aug-2004:  This should probably be calling over to
			// the available calculator implementations to see what they
			// support.  For now use ESP instead.
			//
			// jhyde 2006/12/21: I think the limits should be baked into the
			// type system, not dependent on the calculator implementation.
			BigDecimal bd = (BigDecimal) literal.getValue();
			BigInteger unscaled = bd.unscaledValue();
			long longValue = unscaled.longValue();
			if (!BigInteger.valueOf(longValue).equals(unscaled)) {
				// overflow
				throw newValidationError(literal,
					RESOURCE.numberLiteralOutOfRange(bd.toString()));
			}
			break;

		case DOUBLE:
			validateLiteralAsDouble(literal);
			break;

		case BINARY:
			final BitString bitString = (BitString) literal.getValue();
			if ((bitString.getBitCount() % 8) != 0) {
				throw newValidationError(literal, RESOURCE.binaryLiteralOdd());
			}
			break;

		case DATE:
		case TIME:
		case TIMESTAMP:
			Calendar calendar = literal.getValueAs(Calendar.class);
			final int year = calendar.get(Calendar.YEAR);
			final int era = calendar.get(Calendar.ERA);
			if (year < 1 || era == GregorianCalendar.BC || year > 9999) {
				throw newValidationError(literal,
					RESOURCE.dateLiteralOutOfRange(literal.toString()));
			}
			break;

		case INTERVAL_YEAR:
		case INTERVAL_YEAR_MONTH:
		case INTERVAL_MONTH:
		case INTERVAL_DAY:
		case INTERVAL_DAY_HOUR:
		case INTERVAL_DAY_MINUTE:
		case INTERVAL_DAY_SECOND:
		case INTERVAL_HOUR:
		case INTERVAL_HOUR_MINUTE:
		case INTERVAL_HOUR_SECOND:
		case INTERVAL_MINUTE:
		case INTERVAL_MINUTE_SECOND:
		case INTERVAL_SECOND:
			if (literal instanceof SqlIntervalLiteral) {
				SqlIntervalLiteral.IntervalValue interval =
					(SqlIntervalLiteral.IntervalValue)
						literal.getValue();
				SqlIntervalQualifier intervalQualifier =
					interval.getIntervalQualifier();

				// ensure qualifier is good before attempting to validate literal
				validateIntervalQualifier(intervalQualifier);
				String intervalStr = interval.getIntervalLiteral();
				// throws CalciteContextException if string is invalid
				int[] values = intervalQualifier.evaluateIntervalLiteral(intervalStr,
					literal.getParserPosition(), typeFactory.getTypeSystem());
				Util.discard(values);
			}
			break;
		default:
			// default is to do nothing
	}
}
 
Example 14
Source File: ExplainHandler.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
  public List<Explain> toResult(String sql, SqlNode sqlNode) throws Exception {
    try {
      final SqlExplain node = SqlNodeUtil.unwrap(sqlNode, SqlExplain.class);
      final SqlLiteral op = node.operand(2);
      final SqlExplain.Depth depth = (SqlExplain.Depth) op.getValue();

      final ResultMode mode;
      SqlExplainLevel level = SqlExplainLevel.ALL_ATTRIBUTES;

      if (node.getDetailLevel() != null) {
        level = node.getDetailLevel();
      }

      switch (depth) {
      case LOGICAL:
        mode = ResultMode.LOGICAL;
        break;
      case PHYSICAL:
        mode = ResultMode.PHYSICAL;
        break;
      default:
        throw new UnsupportedOperationException("Unknown depth " + depth);
      }

      final SqlNode innerNode = node.operand(0);

//      try(DisabledBlock block = toggle.openDisabledBlock()){
        Rel drel;
        final ConvertedRelNode convertedRelNode = PrelTransformer.validateAndConvert(config, innerNode);
        final RelDataType validatedRowType = convertedRelNode.getValidatedRowType();
        final RelNode queryRelNode = convertedRelNode.getConvertedNode();

        PrelTransformer.log("Calcite", queryRelNode, logger, null);
        drel = PrelTransformer.convertToDrel(config, queryRelNode, validatedRowType);

        if (mode == ResultMode.LOGICAL) {
          return Collections.singletonList(new Explain(RelOptUtil.toString(drel, level)));
        }

        final Pair<Prel, String> convertToPrel = PrelTransformer.convertToPrel(config, drel);
        final String text = convertToPrel.getValue();
        return Collections.singletonList(new Explain(text));
//      }
    } catch (Exception ex){
      throw SqlExceptionHelper.coerceException(logger, sql, ex, true);
    }
  }
 
Example 15
Source File: SqlNodeToRexConverterImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RexNode convertLiteral(
    SqlRexContext cx,
    SqlLiteral literal) {
  RexBuilder rexBuilder = cx.getRexBuilder();
  RelDataTypeFactory typeFactory = cx.getTypeFactory();
  SqlValidator validator = cx.getValidator();
  if (literal.getValue() == null) {
    // Since there is no eq. RexLiteral of SqlLiteral.Unknown we
    // treat it as a cast(null as boolean)
    RelDataType type;
    if (literal.getTypeName() == SqlTypeName.BOOLEAN) {
      type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
      type = typeFactory.createTypeWithNullability(type, true);
    } else {
      type = validator.getValidatedNodeType(literal);
    }
    return rexBuilder.makeNullLiteral(type);
  }

  BitString bitString;
  SqlIntervalLiteral.IntervalValue intervalValue;
  long l;

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

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

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

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

  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
  case INTERVAL_DAY:
  case INTERVAL_DAY_HOUR:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    SqlIntervalQualifier sqlIntervalQualifier =
        literal.getValueAs(SqlIntervalLiteral.IntervalValue.class)
            .getIntervalQualifier();
    return rexBuilder.makeIntervalLiteral(
        literal.getValueAs(BigDecimal.class),
        sqlIntervalQualifier);
  default:
    throw Util.unexpected(literal.getTypeName());
  }
}
 
Example 16
Source File: SqlLiteralChainOperator.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startList("", "");
  SqlCollation collation = null;
  for (Ord<SqlNode> operand : Ord.zip(call.getOperandList())) {
    SqlLiteral rand = (SqlLiteral) operand.e;
    if (operand.i > 0) {
      // SQL:2003 says there must be a newline between string
      // fragments.
      writer.newlineAndIndent();
    }
    if (rand instanceof SqlCharStringLiteral) {
      NlsString nls = ((SqlCharStringLiteral) rand).getNlsString();
      if (operand.i == 0) {
        collation = nls.getCollation();

        // print with prefix
        writer.literal(nls.asSql(true, false, writer.getDialect()));
      } else {
        // print without prefix
        writer.literal(nls.asSql(false, false, writer.getDialect()));
      }
    } else if (operand.i == 0) {
      // print with prefix
      rand.unparse(writer, leftPrec, rightPrec);
    } else {
      // print without prefix
      if (rand.getTypeName() == SqlTypeName.BINARY) {
        BitString bs = (BitString) rand.getValue();
        writer.literal("'" + bs.toHexString() + "'");
      } else {
        writer.literal("'" + rand.toValue() + "'");
      }
    }
  }
  if (collation != null) {
    collation.unparse(writer);
  }
  writer.endList(frame);
}