org.apache.calcite.util.BitString Java Examples

The following examples show how to use org.apache.calcite.util.BitString. 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: SqlLiteral.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal like X'ABAB' from an array of bytes.
 *
 * @param bytes Contents of binary literal
 * @param pos   Parser position
 * @return Binary string literal
 */
public static SqlBinaryStringLiteral createBinaryString(
    byte[] bytes,
    SqlParserPos pos) {
  BitString bits;
  try {
    bits = BitString.createFromBytes(bytes);
  } catch (NumberFormatException e) {
    throw SqlUtil.newContextException(pos, RESOURCE.binaryLiteralInvalid());
  }
  return new SqlBinaryStringLiteral(bits, pos);
}
 
Example #2
Source File: SqlLiteral.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal like X'ABAB'. Although it matters when we derive a type
 * for this beastie, we don't care at this point whether the number of
 * hexits is odd or even.
 */
public static SqlBinaryStringLiteral createBinaryString(
    String s,
    SqlParserPos pos) {
  BitString bits;
  try {
    bits = BitString.createFromHexString(s);
  } catch (NumberFormatException e) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.binaryLiteralInvalid());
  }
  return new SqlBinaryStringLiteral(bits, pos);
}
 
Example #3
Source File: SqlBinaryStringLiteral.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected SqlAbstractStringLiteral concat1(List<SqlLiteral> literals) {
  return new SqlBinaryStringLiteral(
      BitString.concat(
          Util.transform(literals,
              literal -> ((SqlBinaryStringLiteral) literal).getBitString())),
      literals.get(0).getParserPosition());
}
 
Example #4
Source File: SqlBinaryStringLiteral.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected SqlAbstractStringLiteral concat1(List<SqlLiteral> literals) {
  return new SqlBinaryStringLiteral(
      BitString.concat(
          Util.transform(literals,
              literal -> ((SqlBinaryStringLiteral) literal).getBitString())),
      literals.get(0).getParserPosition());
}
 
Example #5
Source File: SqlLiteral.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal like X'ABAB'. Although it matters when we derive a type
 * for this beastie, we don't care at this point whether the number of
 * hexits is odd or even.
 */
public static SqlBinaryStringLiteral createBinaryString(
    String s,
    SqlParserPos pos) {
  BitString bits;
  try {
    bits = BitString.createFromHexString(s);
  } catch (NumberFormatException e) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.binaryLiteralInvalid());
  }
  return new SqlBinaryStringLiteral(bits, pos);
}
 
Example #6
Source File: SqlLiteral.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal like X'ABAB' from an array of bytes.
 *
 * @param bytes Contents of binary literal
 * @param pos   Parser position
 * @return Binary string literal
 */
public static SqlBinaryStringLiteral createBinaryString(
    byte[] bytes,
    SqlParserPos pos) {
  BitString bits;
  try {
    bits = BitString.createFromBytes(bytes);
  } catch (NumberFormatException e) {
    throw SqlUtil.newContextException(pos, RESOURCE.binaryLiteralInvalid());
  }
  return new SqlBinaryStringLiteral(bits, pos);
}
 
Example #7
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 #8
Source File: SqlLiteral.java    From calcite with Apache License 2.0 4 votes vote down vote up
public <T> T getValueAs(Class<T> clazz) {
  if (clazz.isInstance(value)) {
    return clazz.cast(value);
  }
  switch (typeName) {
  case CHAR:
    if (clazz == String.class) {
      return clazz.cast(((NlsString) value).getValue());
    }
    break;
  case BINARY:
    if (clazz == byte[].class) {
      return clazz.cast(((BitString) value).getAsByteArray());
    }
    break;
  case DECIMAL:
    if (clazz == Long.class) {
      return clazz.cast(((BigDecimal) value).unscaledValue().longValue());
    }
    // fall through
  case BIGINT:
  case INTEGER:
  case SMALLINT:
  case TINYINT:
  case DOUBLE:
  case REAL:
  case FLOAT:
    if (clazz == Long.class) {
      return clazz.cast(((BigDecimal) value).longValue());
    } else if (clazz == Integer.class) {
      return clazz.cast(((BigDecimal) value).intValue());
    } else if (clazz == Short.class) {
      return clazz.cast(((BigDecimal) value).shortValue());
    } else if (clazz == Byte.class) {
      return clazz.cast(((BigDecimal) value).byteValue());
    } else if (clazz == Double.class) {
      return clazz.cast(((BigDecimal) value).doubleValue());
    } else if (clazz == Float.class) {
      return clazz.cast(((BigDecimal) value).floatValue());
    }
    break;
  case DATE:
    if (clazz == Calendar.class) {
      return clazz.cast(((DateString) value).toCalendar());
    }
    break;
  case TIME:
    if (clazz == Calendar.class) {
      return clazz.cast(((TimeString) value).toCalendar());
    }
    break;
  case TIMESTAMP:
    if (clazz == Calendar.class) {
      return clazz.cast(((TimestampString) value).toCalendar());
    }
    break;
  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
    final SqlIntervalLiteral.IntervalValue valMonth =
        (SqlIntervalLiteral.IntervalValue) value;
    if (clazz == Long.class) {
      return clazz.cast(valMonth.getSign()
          * SqlParserUtil.intervalToMonths(valMonth));
    } else if (clazz == BigDecimal.class) {
      return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
    } else if (clazz == TimeUnitRange.class) {
      return clazz.cast(valMonth.getIntervalQualifier().timeUnitRange);
    }
    break;
  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:
    final SqlIntervalLiteral.IntervalValue valTime =
        (SqlIntervalLiteral.IntervalValue) value;
    if (clazz == Long.class) {
      return clazz.cast(valTime.getSign()
          * SqlParserUtil.intervalToMillis(valTime));
    } else if (clazz == BigDecimal.class) {
      return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
    } else if (clazz == TimeUnitRange.class) {
      return clazz.cast(valTime.getIntervalQualifier().timeUnitRange);
    }
    break;
  }
  throw new AssertionError("cannot cast " + value + " as " + clazz);
}
 
Example #9
Source File: SqlLiteral.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * @return whether value is appropriate for its type (we have rules about
 * these things)
 */
public static boolean valueMatchesType(
    Object value,
    SqlTypeName typeName) {
  switch (typeName) {
  case BOOLEAN:
    return (value == null) || (value instanceof Boolean);
  case NULL:
    return value == null;
  case DECIMAL:
  case DOUBLE:
    return value instanceof BigDecimal;
  case DATE:
    return value instanceof DateString;
  case TIME:
    return value instanceof TimeString;
  case TIMESTAMP:
    return value instanceof TimestampString;
  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:
    return value instanceof SqlIntervalLiteral.IntervalValue;
  case BINARY:
    return value instanceof BitString;
  case CHAR:
    return value instanceof NlsString;
  case SYMBOL:
    return (value instanceof Enum)
        || (value instanceof SqlSampleSpec);
  case MULTISET:
    return true;
  case INTEGER: // not allowed -- use Decimal
  case VARCHAR: // not allowed -- use Char
  case VARBINARY: // not allowed -- use Binary
  default:
    throw Util.unexpected(typeName);
  }
}
 
Example #10
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);
}
 
Example #11
Source File: SqlBinaryStringLiteral.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override public SqlBinaryStringLiteral clone(SqlParserPos pos) {
  return new SqlBinaryStringLiteral((BitString) value, pos);
}
 
Example #12
Source File: SqlBinaryStringLiteral.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * @return the underlying BitString
 */
public BitString getBitString() {
  return (BitString) value;
}
 
Example #13
Source File: SqlBinaryStringLiteral.java    From calcite with Apache License 2.0 4 votes vote down vote up
protected SqlBinaryStringLiteral(
    BitString val,
    SqlParserPos pos) {
  super(val, SqlTypeName.BINARY, pos);
}
 
Example #14
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 #15
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 #16
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 #17
Source File: SqlLiteral.java    From Bats with Apache License 2.0 4 votes vote down vote up
public <T> T getValueAs(Class<T> clazz) {
  if (clazz.isInstance(value)) {
    return clazz.cast(value);
  }
  switch (typeName) {
  case CHAR:
    if (clazz == String.class) {
      return clazz.cast(((NlsString) value).getValue());
    }
    break;
  case BINARY:
    if (clazz == byte[].class) {
      return clazz.cast(((BitString) value).getAsByteArray());
    }
    break;
  case DECIMAL:
    if (clazz == Long.class) {
      return clazz.cast(((BigDecimal) value).unscaledValue().longValue());
    }
    // fall through
  case BIGINT:
  case INTEGER:
  case SMALLINT:
  case TINYINT:
  case DOUBLE:
  case REAL:
  case FLOAT:
    if (clazz == Long.class) {
      return clazz.cast(((BigDecimal) value).longValue());
    } else if (clazz == Integer.class) {
      return clazz.cast(((BigDecimal) value).intValue());
    } else if (clazz == Short.class) {
      return clazz.cast(((BigDecimal) value).shortValue());
    } else if (clazz == Byte.class) {
      return clazz.cast(((BigDecimal) value).byteValue());
    } else if (clazz == Double.class) {
      return clazz.cast(((BigDecimal) value).doubleValue());
    } else if (clazz == Float.class) {
      return clazz.cast(((BigDecimal) value).floatValue());
    }
    break;
  case DATE:
    if (clazz == Calendar.class) {
      return clazz.cast(((DateString) value).toCalendar());
    }
    break;
  case TIME:
    if (clazz == Calendar.class) {
      return clazz.cast(((TimeString) value).toCalendar());
    }
    break;
  case TIMESTAMP:
    if (clazz == Calendar.class) {
      return clazz.cast(((TimestampString) value).toCalendar());
    }
    break;
  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
    final SqlIntervalLiteral.IntervalValue valMonth =
        (SqlIntervalLiteral.IntervalValue) value;
    if (clazz == Long.class) {
      return clazz.cast(valMonth.getSign()
          * SqlParserUtil.intervalToMonths(valMonth));
    } else if (clazz == BigDecimal.class) {
      return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
    } else if (clazz == TimeUnitRange.class) {
      return clazz.cast(valMonth.getIntervalQualifier().timeUnitRange);
    }
    break;
  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:
    final SqlIntervalLiteral.IntervalValue valTime =
        (SqlIntervalLiteral.IntervalValue) value;
    if (clazz == Long.class) {
      return clazz.cast(valTime.getSign()
          * SqlParserUtil.intervalToMillis(valTime));
    } else if (clazz == BigDecimal.class) {
      return clazz.cast(BigDecimal.valueOf(getValueAs(Long.class)));
    } else if (clazz == TimeUnitRange.class) {
      return clazz.cast(valTime.getIntervalQualifier().timeUnitRange);
    }
    break;
  }
  throw new AssertionError("cannot cast " + value + " as " + clazz);
}
 
Example #18
Source File: SqlLiteral.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * @return whether value is appropriate for its type (we have rules about
 * these things)
 */
public static boolean valueMatchesType(
    Object value,
    SqlTypeName typeName) {
  switch (typeName) {
  case BOOLEAN:
    return (value == null) || (value instanceof Boolean);
  case NULL:
    return value == null;
  case DECIMAL:
  case DOUBLE:
    return value instanceof BigDecimal;
  case DATE:
    return value instanceof DateString;
  case TIME:
    return value instanceof TimeString;
  case TIMESTAMP:
    return value instanceof TimestampString;
  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:
    return value instanceof SqlIntervalLiteral.IntervalValue;
  case BINARY:
    return value instanceof BitString;
  case CHAR:
    return value instanceof NlsString;
  case SYMBOL:
    return (value instanceof Enum)
        || (value instanceof SqlSampleSpec);
  case MULTISET:
    return true;
  case INTEGER: // not allowed -- use Decimal
  case VARCHAR: // not allowed -- use Char
  case VARBINARY: // not allowed -- use Binary
  default:
    throw Util.unexpected(typeName);
  }
}
 
Example #19
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 #20
Source File: SqlBinaryStringLiteral.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override public SqlBinaryStringLiteral clone(SqlParserPos pos) {
  return new SqlBinaryStringLiteral((BitString) value, pos);
}
 
Example #21
Source File: SqlBinaryStringLiteral.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * @return the underlying BitString
 */
public BitString getBitString() {
  return (BitString) value;
}
 
Example #22
Source File: SqlBinaryStringLiteral.java    From Bats with Apache License 2.0 4 votes vote down vote up
protected SqlBinaryStringLiteral(
    BitString val,
    SqlParserPos pos) {
  super(val, SqlTypeName.BINARY, pos);
}