use of com.facebook.presto.common.type.VarcharType in project presto by prestodb.
the class OrcTester method preprocessWriteValueHive.
private static Object preprocessWriteValueHive(Type type, Object value) {
if (value == null) {
return null;
}
if (type.equals(BOOLEAN)) {
return value;
} else if (type.equals(TINYINT)) {
return ((Number) value).byteValue();
} else if (type.equals(SMALLINT)) {
return ((Number) value).shortValue();
} else if (type.equals(INTEGER)) {
return ((Number) value).intValue();
} else if (type.equals(BIGINT)) {
return ((Number) value).longValue();
} else if (type.equals(REAL)) {
return ((Number) value).floatValue();
} else if (type.equals(DOUBLE)) {
return ((Number) value).doubleValue();
} else if (type instanceof VarcharType) {
return value;
} else if (type instanceof CharType) {
return new HiveChar((String) value, ((CharType) type).getLength());
} else if (type.equals(VARBINARY)) {
return ((SqlVarbinary) value).getBytes();
} else if (type.equals(DATE)) {
int days = ((SqlDate) value).getDays();
LocalDate localDate = LocalDate.ofEpochDay(days);
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
long millis = SECONDS.toMillis(zonedDateTime.toEpochSecond());
Date date = new Date(0);
// millis must be set separately to avoid masking
date.setTime(millis);
return date;
} else if (type.equals(TIMESTAMP)) {
long millisUtc = (int) ((SqlTimestamp) value).getMillisUtc();
return new Timestamp(millisUtc);
} else if (type instanceof DecimalType) {
return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
} else if (type.getTypeSignature().getBase().equals(StandardTypes.ARRAY)) {
Type elementType = type.getTypeParameters().get(0);
return ((List<?>) value).stream().map(element -> preprocessWriteValueHive(elementType, element)).collect(toList());
} else if (type.getTypeSignature().getBase().equals(StandardTypes.MAP)) {
Type keyType = type.getTypeParameters().get(0);
Type valueType = type.getTypeParameters().get(1);
Map<Object, Object> newMap = new HashMap<>();
for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
newMap.put(preprocessWriteValueHive(keyType, entry.getKey()), preprocessWriteValueHive(valueType, entry.getValue()));
}
return newMap;
} else if (type.getTypeSignature().getBase().equals(StandardTypes.ROW)) {
List<?> fieldValues = (List<?>) value;
List<Type> fieldTypes = type.getTypeParameters();
List<Object> newStruct = new ArrayList<>();
for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
newStruct.add(preprocessWriteValueHive(fieldTypes.get(fieldId), fieldValues.get(fieldId)));
}
return newStruct;
}
throw new IllegalArgumentException("unsupported type: " + type);
}
use of com.facebook.presto.common.type.VarcharType in project presto by prestodb.
the class QueryBuilder method buildSql.
public PreparedStatement buildSql(JdbcClient client, ConnectorSession session, Connection connection, String catalog, String schema, String table, List<JdbcColumnHandle> columns, TupleDomain<ColumnHandle> tupleDomain, Optional<JdbcExpression> additionalPredicate) throws SQLException {
StringBuilder sql = new StringBuilder();
String columnNames = columns.stream().map(JdbcColumnHandle::getColumnName).map(this::quote).collect(joining(", "));
sql.append("SELECT ");
sql.append(columnNames);
if (columns.isEmpty()) {
sql.append("null");
}
sql.append(" FROM ");
if (!isNullOrEmpty(catalog)) {
sql.append(quote(catalog)).append('.');
}
if (!isNullOrEmpty(schema)) {
sql.append(quote(schema)).append('.');
}
sql.append(quote(table));
List<TypeAndValue> accumulator = new ArrayList<>();
List<String> clauses = toConjuncts(columns, tupleDomain, accumulator);
if (additionalPredicate.isPresent()) {
clauses = ImmutableList.<String>builder().addAll(clauses).add(additionalPredicate.get().getExpression()).build();
accumulator.addAll(additionalPredicate.get().getBoundConstantValues().stream().map(constantExpression -> new TypeAndValue(constantExpression.getType(), constantExpression.getValue())).collect(ImmutableList.toImmutableList()));
}
if (!clauses.isEmpty()) {
sql.append(" WHERE ").append(Joiner.on(" AND ").join(clauses));
}
sql.append(String.format("/* %s : %s */", session.getUser(), session.getQueryId()));
PreparedStatement statement = client.getPreparedStatement(connection, sql.toString());
for (int i = 0; i < accumulator.size(); i++) {
TypeAndValue typeAndValue = accumulator.get(i);
if (typeAndValue.getType().equals(BigintType.BIGINT)) {
statement.setLong(i + 1, (long) typeAndValue.getValue());
} else if (typeAndValue.getType().equals(IntegerType.INTEGER)) {
statement.setInt(i + 1, ((Number) typeAndValue.getValue()).intValue());
} else if (typeAndValue.getType().equals(SmallintType.SMALLINT)) {
statement.setShort(i + 1, ((Number) typeAndValue.getValue()).shortValue());
} else if (typeAndValue.getType().equals(TinyintType.TINYINT)) {
statement.setByte(i + 1, ((Number) typeAndValue.getValue()).byteValue());
} else if (typeAndValue.getType().equals(DoubleType.DOUBLE)) {
statement.setDouble(i + 1, (double) typeAndValue.getValue());
} else if (typeAndValue.getType().equals(RealType.REAL)) {
statement.setFloat(i + 1, intBitsToFloat(((Number) typeAndValue.getValue()).intValue()));
} else if (typeAndValue.getType().equals(BooleanType.BOOLEAN)) {
statement.setBoolean(i + 1, (boolean) typeAndValue.getValue());
} else if (typeAndValue.getType().equals(DateType.DATE)) {
long millis = DAYS.toMillis((long) typeAndValue.getValue());
statement.setDate(i + 1, new Date(UTC.getMillisKeepLocal(DateTimeZone.getDefault(), millis)));
} else if (typeAndValue.getType().equals(TimeType.TIME)) {
statement.setTime(i + 1, new Time((long) typeAndValue.getValue()));
} else if (typeAndValue.getType().equals(TimeWithTimeZoneType.TIME_WITH_TIME_ZONE)) {
statement.setTime(i + 1, new Time(unpackMillisUtc((long) typeAndValue.getValue())));
} else if (typeAndValue.getType().equals(TimestampType.TIMESTAMP)) {
statement.setTimestamp(i + 1, new Timestamp((long) typeAndValue.getValue()));
} else if (typeAndValue.getType().equals(TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE)) {
statement.setTimestamp(i + 1, new Timestamp(unpackMillisUtc((long) typeAndValue.getValue())));
} else if (typeAndValue.getType() instanceof VarcharType) {
statement.setString(i + 1, ((Slice) typeAndValue.getValue()).toStringUtf8());
} else if (typeAndValue.getType() instanceof CharType) {
statement.setString(i + 1, ((Slice) typeAndValue.getValue()).toStringUtf8());
} else {
throw new UnsupportedOperationException("Can't handle type: " + typeAndValue.getType());
}
}
return statement;
}
use of com.facebook.presto.common.type.VarcharType in project presto by prestodb.
the class DeltaTypeUtils method convertPartitionValue.
public static Object convertPartitionValue(String columnName, String valueString, Type type) {
if (valueString == null) {
return null;
}
try {
if (type.equals(BOOLEAN)) {
checkArgument(valueString.equalsIgnoreCase("true") || valueString.equalsIgnoreCase("false"));
return Boolean.valueOf(valueString);
}
if (type.equals(TINYINT) || type.equals(SMALLINT) || type.equals(INTEGER) || type.equals(BIGINT)) {
return parseLong(valueString);
}
if (type.equals(REAL)) {
return (long) floatToRawIntBits(parseFloat(valueString));
}
if (type.equals(DOUBLE)) {
return parseDouble(valueString);
}
if (type instanceof VarcharType) {
Slice value = utf8Slice(valueString);
VarcharType varcharType = (VarcharType) type;
if (!varcharType.isUnbounded() && SliceUtf8.countCodePoints(value) > varcharType.getLengthSafe()) {
throw new IllegalArgumentException();
}
return value;
}
if (type.equals(VARBINARY)) {
return utf8Slice(valueString);
}
if (isShortDecimal(type) || isLongDecimal(type)) {
com.facebook.presto.common.type.DecimalType decimalType = (com.facebook.presto.common.type.DecimalType) type;
BigDecimal decimal = new BigDecimal(valueString);
decimal = decimal.setScale(decimalType.getScale(), BigDecimal.ROUND_UNNECESSARY);
if (decimal.precision() > decimalType.getPrecision()) {
throw new IllegalArgumentException();
}
BigInteger unscaledValue = decimal.unscaledValue();
return isShortDecimal(type) ? unscaledValue.longValue() : Decimals.encodeUnscaledValue(unscaledValue);
}
if (type.equals(DATE)) {
return LocalDate.parse(valueString, DateTimeFormatter.ISO_LOCAL_DATE).toEpochDay();
}
if (type.equals(TIMESTAMP)) {
// Delta partition serialized value contains up to the second precision
return Timestamp.valueOf(valueString).toLocalDateTime().toEpochSecond(ZoneOffset.UTC) * 1_000;
}
throw new PrestoException(DELTA_UNSUPPORTED_COLUMN_TYPE, format("Unsupported data type '%s' for partition column %s", type, columnName));
} catch (IllegalArgumentException | DateTimeParseException e) {
throw new PrestoException(DELTA_INVALID_PARTITION_VALUE, format("Can not parse partition value '%s' of type '%s' for partition column '%s'", valueString, type, columnName), e);
}
}
use of com.facebook.presto.common.type.VarcharType in project presto by prestodb.
the class HiveTypeTranslator method translate.
@Override
public TypeInfo translate(Type type, Optional<HiveType> defaultHiveType) {
if (BOOLEAN.equals(type)) {
return HIVE_BOOLEAN.getTypeInfo();
}
if (BIGINT.equals(type)) {
return HIVE_LONG.getTypeInfo();
}
if (INTEGER.equals(type)) {
return HIVE_INT.getTypeInfo();
}
if (SMALLINT.equals(type)) {
return HIVE_SHORT.getTypeInfo();
}
if (TINYINT.equals(type)) {
return HIVE_BYTE.getTypeInfo();
}
if (REAL.equals(type)) {
return HIVE_FLOAT.getTypeInfo();
}
if (DOUBLE.equals(type)) {
return HIVE_DOUBLE.getTypeInfo();
}
if (type instanceof VarcharType) {
VarcharType varcharType = (VarcharType) type;
int varcharLength = varcharType.getLength();
if (varcharLength <= HiveVarchar.MAX_VARCHAR_LENGTH) {
return getVarcharTypeInfo(varcharLength);
} else if (varcharLength == VarcharType.UNBOUNDED_LENGTH) {
return HIVE_STRING.getTypeInfo();
} else {
throw new PrestoException(NOT_SUPPORTED, format("Unsupported Hive type: %s. Supported VARCHAR types: VARCHAR(<=%d), VARCHAR.", type, HiveVarchar.MAX_VARCHAR_LENGTH));
}
}
if (type instanceof EnumType<?>) {
return translate(((EnumType<?>) type).getValueType());
}
if (type instanceof CharType) {
CharType charType = (CharType) type;
int charLength = charType.getLength();
if (charLength <= HiveChar.MAX_CHAR_LENGTH) {
return getCharTypeInfo(charLength);
}
throw new PrestoException(NOT_SUPPORTED, format("Unsupported Hive type: %s. Supported CHAR types: CHAR(<=%d).", type, HiveChar.MAX_CHAR_LENGTH));
}
if (type instanceof TypeWithName) {
return translate(((TypeWithName) type).getType());
}
if (VARBINARY.equals(type)) {
return HIVE_BINARY.getTypeInfo();
}
if (DATE.equals(type)) {
return HIVE_DATE.getTypeInfo();
}
if (TIMESTAMP.equals(type)) {
return HIVE_TIMESTAMP.getTypeInfo();
}
if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
return new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale());
}
if (isArrayType(type)) {
TypeInfo elementType = translate(type.getTypeParameters().get(0), defaultHiveType);
return getListTypeInfo(elementType);
}
if (isMapType(type)) {
TypeInfo keyType = translate(type.getTypeParameters().get(0), defaultHiveType);
TypeInfo valueType = translate(type.getTypeParameters().get(1), defaultHiveType);
return getMapTypeInfo(keyType, valueType);
}
if (isRowType(type)) {
ImmutableList.Builder<String> fieldNames = ImmutableList.builder();
for (TypeSignatureParameter parameter : type.getTypeSignature().getParameters()) {
if (!parameter.isNamedTypeSignature()) {
throw new IllegalArgumentException(format("Expected all parameters to be named type, but got %s", parameter));
}
NamedTypeSignature namedTypeSignature = parameter.getNamedTypeSignature();
if (!namedTypeSignature.getName().isPresent()) {
throw new PrestoException(NOT_SUPPORTED, format("Anonymous row type is not supported in Hive. Please give each field a name: %s", type));
}
fieldNames.add(namedTypeSignature.getName().get());
}
return getStructTypeInfo(fieldNames.build(), type.getTypeParameters().stream().map(t -> translate(t, defaultHiveType)).collect(toList()));
}
return defaultHiveType.orElseThrow(() -> new PrestoException(NOT_SUPPORTED, format("No default Hive type provided for unsupported Hive type: %s", type))).getTypeInfo();
}
use of com.facebook.presto.common.type.VarcharType in project presto by prestodb.
the class ParquetTester method writeValue.
private static void writeValue(Type type, BlockBuilder blockBuilder, Object value) {
if (value == null) {
blockBuilder.appendNull();
} else {
if (BOOLEAN.equals(type)) {
type.writeBoolean(blockBuilder, (Boolean) value);
} else if (TINYINT.equals(type) || SMALLINT.equals(type) || INTEGER.equals(type) || BIGINT.equals(type)) {
type.writeLong(blockBuilder, ((Number) value).longValue());
} else if (Decimals.isShortDecimal(type)) {
type.writeLong(blockBuilder, ((SqlDecimal) value).getUnscaledValue().longValue());
} else if (Decimals.isLongDecimal(type)) {
if (Decimals.overflows(((SqlDecimal) value).getUnscaledValue(), MAX_PRECISION_INT64)) {
type.writeSlice(blockBuilder, Decimals.encodeUnscaledValue(((SqlDecimal) value).toBigDecimal().unscaledValue()));
} else {
type.writeSlice(blockBuilder, Decimals.encodeUnscaledValue(((SqlDecimal) value).getUnscaledValue().longValue()));
}
} else if (DOUBLE.equals(type)) {
type.writeDouble(blockBuilder, ((Number) value).doubleValue());
} else if (REAL.equals(type)) {
float floatValue = ((Number) value).floatValue();
type.writeLong(blockBuilder, Float.floatToIntBits(floatValue));
} else if (type instanceof VarcharType) {
Slice slice = truncateToLength(utf8Slice((String) value), type);
type.writeSlice(blockBuilder, slice);
} else if (type instanceof CharType) {
Slice slice = truncateToLengthAndTrimSpaces(utf8Slice((String) value), type);
type.writeSlice(blockBuilder, slice);
} else if (VARBINARY.equals(type)) {
type.writeSlice(blockBuilder, Slices.wrappedBuffer(((SqlVarbinary) value).getBytes()));
} else if (DATE.equals(type)) {
long days = ((SqlDate) value).getDays();
type.writeLong(blockBuilder, days);
} else if (TIMESTAMP.equals(type)) {
long millis = ((SqlTimestamp) value).getMillisUtc();
type.writeLong(blockBuilder, millis);
} else {
if (type instanceof ArrayType) {
List<?> array = (List<?>) value;
Type elementType = type.getTypeParameters().get(0);
BlockBuilder arrayBlockBuilder = blockBuilder.beginBlockEntry();
for (Object elementValue : array) {
writeValue(elementType, arrayBlockBuilder, elementValue);
}
blockBuilder.closeEntry();
} else if (type instanceof MapType) {
Map<?, ?> map = (Map<?, ?>) value;
Type keyType = type.getTypeParameters().get(0);
Type valueType = type.getTypeParameters().get(1);
BlockBuilder mapBlockBuilder = blockBuilder.beginBlockEntry();
for (Map.Entry<?, ?> entry : map.entrySet()) {
writeValue(keyType, mapBlockBuilder, entry.getKey());
writeValue(valueType, mapBlockBuilder, entry.getValue());
}
blockBuilder.closeEntry();
} else if (type instanceof RowType) {
List<?> array = (List<?>) value;
List<Type> fieldTypes = type.getTypeParameters();
BlockBuilder rowBlockBuilder = blockBuilder.beginBlockEntry();
for (int fieldId = 0; fieldId < fieldTypes.size(); fieldId++) {
Type fieldType = fieldTypes.get(fieldId);
writeValue(fieldType, rowBlockBuilder, array.get(fieldId));
}
blockBuilder.closeEntry();
} else {
throw new IllegalArgumentException("Unsupported type " + type);
}
}
}
}
Aggregations