Java Code Examples for io.prestosql.spi.type.IntegerType

The following examples show how to use io.prestosql.spi.type.IntegerType. These examples are extracted from open source projects. 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 Project: presto   Source File: PrestoThriftBlock.java    License: Apache License 2.0 6 votes vote down vote up
public static PrestoThriftBlock fromRecordSetColumn(RecordSet recordSet, int columnIndex, int totalRecords)
{
    Type type = recordSet.getColumnTypes().get(columnIndex);
    // use more efficient implementations for numeric types which are likely to be used in index join
    if (type instanceof IntegerType) {
        return PrestoThriftInteger.fromRecordSetColumn(recordSet, columnIndex, totalRecords);
    }
    if (type instanceof BigintType) {
        return PrestoThriftBigint.fromRecordSetColumn(recordSet, columnIndex, totalRecords);
    }
    if (type instanceof DateType) {
        return PrestoThriftDate.fromRecordSetColumn(recordSet, columnIndex, totalRecords);
    }
    if (type instanceof TimestampType) {
        return PrestoThriftTimestamp.fromRecordSetColumn(recordSet, columnIndex, totalRecords);
    }
    // less efficient implementation which converts to a block first
    return fromBlock(convertColumnToBlock(recordSet, columnIndex, totalRecords), type);
}
 
Example 2
Source Project: presto   Source File: TpcdsMetadata.java    License: Apache License 2.0 6 votes vote down vote up
public static Type getPrestoType(ColumnType tpcdsType)
{
    switch (tpcdsType.getBase()) {
        case IDENTIFIER:
            return BigintType.BIGINT;
        case INTEGER:
            return IntegerType.INTEGER;
        case DATE:
            return DateType.DATE;
        case DECIMAL:
            return createDecimalType(tpcdsType.getPrecision().get(), tpcdsType.getScale().get());
        case CHAR:
            return createCharType(tpcdsType.getPrecision().get());
        case VARCHAR:
            return createVarcharType(tpcdsType.getPrecision().get());
        case TIME:
            return TimeType.TIME;
    }
    throw new IllegalArgumentException("Unsupported TPC-DS type " + tpcdsType);
}
 
Example 3
Source Project: presto   Source File: SessionPropertyManager.java    License: Apache License 2.0 6 votes vote down vote up
public static String serializeSessionProperty(Type type, Object value)
{
    if (value == null) {
        throw new PrestoException(INVALID_SESSION_PROPERTY, "Session property cannot be null");
    }
    if (BooleanType.BOOLEAN.equals(type)) {
        return value.toString();
    }
    if (BigintType.BIGINT.equals(type)) {
        return value.toString();
    }
    if (IntegerType.INTEGER.equals(type)) {
        return value.toString();
    }
    if (DoubleType.DOUBLE.equals(type)) {
        return value.toString();
    }
    if (VarcharType.VARCHAR.equals(type)) {
        return value.toString();
    }
    if (type instanceof ArrayType || type instanceof MapType) {
        return getJsonCodecForType(type).toJson(value);
    }
    throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property type %s is not supported", type));
}
 
Example 4
Source Project: presto   Source File: SessionPropertyManager.java    License: Apache License 2.0 6 votes vote down vote up
private static Object deserializeSessionProperty(Type type, String value)
{
    if (value == null) {
        throw new PrestoException(INVALID_SESSION_PROPERTY, "Session property cannot be null");
    }
    if (VarcharType.VARCHAR.equals(type)) {
        return value;
    }
    if (BooleanType.BOOLEAN.equals(type)) {
        return Boolean.valueOf(value);
    }
    if (BigintType.BIGINT.equals(type)) {
        return Long.valueOf(value);
    }
    if (IntegerType.INTEGER.equals(type)) {
        return Integer.valueOf(value);
    }
    if (DoubleType.DOUBLE.equals(type)) {
        return Double.valueOf(value);
    }
    if (type instanceof ArrayType || type instanceof MapType) {
        return getJsonCodecForType(type).fromJson(value);
    }
    throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property type %s is not supported", type));
}
 
Example 5
Source Project: presto   Source File: SessionPropertyManager.java    License: Apache License 2.0 6 votes vote down vote up
private static Class<?> getMapKeyType(Type type)
{
    if (VarcharType.VARCHAR.equals(type)) {
        return String.class;
    }
    if (BooleanType.BOOLEAN.equals(type)) {
        return Boolean.class;
    }
    if (BigintType.BIGINT.equals(type)) {
        return Long.class;
    }
    if (IntegerType.INTEGER.equals(type)) {
        return Integer.class;
    }
    if (DoubleType.DOUBLE.equals(type)) {
        return Double.class;
    }
    throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property map key type %s is not supported", type));
}
 
Example 6
Source Project: presto   Source File: ShowStatsRewrite.java    License: Apache License 2.0 6 votes vote down vote up
private static Expression toStringLiteral(Type type, double value)
{
    if (type.equals(BigintType.BIGINT) || type.equals(IntegerType.INTEGER) || type.equals(SmallintType.SMALLINT) || type.equals(TinyintType.TINYINT)) {
        return new StringLiteral(Long.toString(round(value)));
    }
    if (type.equals(DOUBLE) || type instanceof DecimalType) {
        return new StringLiteral(Double.toString(value));
    }
    if (type.equals(RealType.REAL)) {
        return new StringLiteral(Float.toString((float) value));
    }
    if (type.equals(DATE)) {
        return new StringLiteral(LocalDate.ofEpochDay(round(value)).toString());
    }
    throw new IllegalArgumentException("Unexpected type: " + type);
}
 
Example 7
Source Project: presto   Source File: JsonUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean canCastFromJson(Type type)
{
    if (type instanceof BooleanType ||
            type instanceof TinyintType ||
            type instanceof SmallintType ||
            type instanceof IntegerType ||
            type instanceof BigintType ||
            type instanceof RealType ||
            type instanceof DoubleType ||
            type instanceof DecimalType ||
            type instanceof VarcharType ||
            type instanceof JsonType) {
        return true;
    }
    if (type instanceof ArrayType) {
        return canCastFromJson(((ArrayType) type).getElementType());
    }
    if (type instanceof MapType) {
        return isValidJsonObjectKeyType(((MapType) type).getKeyType()) && canCastFromJson(((MapType) type).getValueType());
    }
    if (type instanceof RowType) {
        return type.getTypeParameters().stream().allMatch(JsonUtil::canCastFromJson);
    }
    return false;
}
 
Example 8
Source Project: presto   Source File: PinotColumn.java    License: Apache License 2.0 6 votes vote down vote up
public static Type getPrestoTypeFromPinotType(DataType dataType)
{
    switch (dataType) {
        case BOOLEAN:
            return BooleanType.BOOLEAN;
        case FLOAT:
        case DOUBLE:
            return DoubleType.DOUBLE;
        case INT:
            return IntegerType.INTEGER;
        case LONG:
            return BigintType.BIGINT;
        case STRING:
            return VarcharType.VARCHAR;
        case BYTES:
            return VarbinaryType.VARBINARY;
        default:
            break;
    }
    throw new PinotException(PINOT_UNSUPPORTED_COLUMN_TYPE, Optional.empty(), "Not support type conversion for pinot data type: " + dataType);
}
 
Example 9
Source Project: presto   Source File: TestRawDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSupportedDataTypeValidation()
{
    // supported types
    singleColumnDecoder(BigintType.BIGINT, "0", "LONG");
    singleColumnDecoder(IntegerType.INTEGER, "0", "INT");
    singleColumnDecoder(SmallintType.SMALLINT, "0", "SHORT");
    singleColumnDecoder(TinyintType.TINYINT, "0", "BYTE");
    singleColumnDecoder(BooleanType.BOOLEAN, "0", "LONG");
    singleColumnDecoder(DoubleType.DOUBLE, "0", "DOUBLE");
    singleColumnDecoder(createUnboundedVarcharType(), "0", "BYTE");
    singleColumnDecoder(createVarcharType(100), "0", "BYTE");

    // some unsupported types
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(RealType.REAL, "0", "BYTE"));
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(DecimalType.createDecimalType(10, 4), "0", "BYTE"));
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(VarbinaryType.VARBINARY, "0", "BYTE"));
}
 
Example 10
Source Project: presto   Source File: TestCsvDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSupportedDataTypeValidation()
{
    // supported types
    singleColumnDecoder(BigintType.BIGINT);
    singleColumnDecoder(IntegerType.INTEGER);
    singleColumnDecoder(SmallintType.SMALLINT);
    singleColumnDecoder(TinyintType.TINYINT);
    singleColumnDecoder(BooleanType.BOOLEAN);
    singleColumnDecoder(DoubleType.DOUBLE);
    singleColumnDecoder(createUnboundedVarcharType());
    singleColumnDecoder(createVarcharType(100));

    // some unsupported types
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(RealType.REAL));
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(DecimalType.createDecimalType(10, 4)));
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(VarbinaryType.VARBINARY));
}
 
Example 11
Source Project: transport   Source File: StdUdfWrapper.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private MethodHandle getMethodHandle(StdUDF stdUDF, Metadata metadata, BoundVariables boundVariables,
    boolean[] nullableArguments, AtomicLong requiredFilesNextRefreshTime) {
  Type[] inputTypes = getPrestoTypes(stdUDF.getInputParameterSignatures(), metadata, boundVariables);
  Type outputType = getPrestoType(stdUDF.getOutputParameterSignature(), metadata, boundVariables);

  // Generic MethodHandle for eval where all arguments are of type Object
  Class<?>[] genericMethodHandleArgumentTypes = getMethodHandleArgumentTypes(inputTypes, nullableArguments, true);
  MethodHandle genericMethodHandle =
      methodHandle(StdUdfWrapper.class, "evalInternal", genericMethodHandleArgumentTypes).bindTo(this);

  Class<?>[] specificMethodHandleArgumentTypes = getMethodHandleArgumentTypes(inputTypes, nullableArguments, false);
  Class<?> specificMethodHandleReturnType = getJavaTypeForNullability(outputType, true);
  MethodType specificMethodType =
      MethodType.methodType(specificMethodHandleReturnType, specificMethodHandleArgumentTypes);

  // Specific MethodHandle required by presto where argument types map to the type signature
  MethodHandle specificMethodHandle = MethodHandles.explicitCastArguments(genericMethodHandle, specificMethodType);
  return MethodHandles.insertArguments(specificMethodHandle, 0, stdUDF, inputTypes,
      outputType instanceof IntegerType, requiredFilesNextRefreshTime);
}
 
Example 12
Source Project: presto   Source File: BlackHolePageSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isNumericType(Type type)
{
    return type instanceof TinyintType ||
            type instanceof SmallintType ||
            type instanceof IntegerType ||
            type instanceof BigintType ||
            type instanceof RealType ||
            type instanceof DoubleType ||
            type instanceof DecimalType;
}
 
Example 13
Source Project: presto   Source File: LongColumnReader.java    License: Apache License 2.0 5 votes vote down vote up
public LongColumnReader(Type type, OrcColumn column, LocalMemoryContext systemMemoryContext)
        throws OrcCorruptionException
{
    requireNonNull(type, "type is null");
    verifyStreamType(column, type, t -> t instanceof BigintType || t instanceof IntegerType || t instanceof SmallintType || t instanceof DateType);
    this.type = type;

    this.column = requireNonNull(column, "column is null");
    this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null");
}
 
Example 14
Source Project: presto   Source File: LongColumnReader.java    License: Apache License 2.0 5 votes vote down vote up
private Block readNullBlock(boolean[] isNull, int nonNullCount)
        throws IOException
{
    if (type instanceof BigintType) {
        return longReadNullBlock(isNull, nonNullCount);
    }
    if (type instanceof IntegerType || type instanceof DateType) {
        return intReadNullBlock(isNull, nonNullCount);
    }
    if (type instanceof SmallintType) {
        return shortReadNullBlock(isNull, nonNullCount);
    }
    throw new VerifyError("Unsupported type " + type);
}
 
Example 15
Source Project: presto   Source File: ScalarStatsCalculator.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isIntegralType(Type type)
{
    if (type instanceof BigintType || type instanceof IntegerType || type instanceof SmallintType || type instanceof TinyintType) {
        return true;
    }

    if (type instanceof DecimalType) {
        return ((DecimalType) type).getScale() == 0;
    }

    return false;
}
 
Example 16
Source Project: presto   Source File: StatsNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isDiscrete(Type type)
{
    return type.equals(IntegerType.INTEGER) ||
            type.equals(BigintType.BIGINT) ||
            type.equals(SmallintType.SMALLINT) ||
            type.equals(TinyintType.TINYINT) ||
            type.equals(BooleanType.BOOLEAN) ||
            type.equals(DateType.DATE) ||
            type instanceof DecimalType;
}
 
Example 17
Source Project: presto   Source File: StatsUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean convertibleToDoubleWithCast(Type type)
{
    return type instanceof DecimalType
            || type instanceof DoubleType
            || type instanceof RealType
            || type instanceof BigintType
            || type instanceof IntegerType
            || type instanceof SmallintType
            || type instanceof TinyintType
            || type instanceof BooleanType;
}
 
Example 18
Source Project: presto   Source File: SessionPropertyManager.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> JsonCodec<T> getJsonCodecForType(Type type)
{
    if (VarcharType.VARCHAR.equals(type)) {
        return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(String.class);
    }
    if (BooleanType.BOOLEAN.equals(type)) {
        return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Boolean.class);
    }
    if (BigintType.BIGINT.equals(type)) {
        return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Long.class);
    }
    if (IntegerType.INTEGER.equals(type)) {
        return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Integer.class);
    }
    if (DoubleType.DOUBLE.equals(type)) {
        return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Double.class);
    }
    if (type instanceof ArrayType) {
        Type elementType = ((ArrayType) type).getElementType();
        return (JsonCodec<T>) JSON_CODEC_FACTORY.listJsonCodec(getJsonCodecForType(elementType));
    }
    if (type instanceof MapType) {
        Type keyType = ((MapType) type).getKeyType();
        Type valueType = ((MapType) type).getValueType();
        return (JsonCodec<T>) JSON_CODEC_FACTORY.mapJsonCodec(getMapKeyType(keyType), getJsonCodecForType(valueType));
    }
    throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property type %s is not supported", type));
}
 
Example 19
Source Project: presto   Source File: InCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static SwitchGenerationCase checkSwitchGenerationCase(Type type, List<RowExpression> values)
{
    if (values.size() > 32) {
        // 32 is chosen because
        // * SET_CONTAINS performs worst when smaller than but close to power of 2
        // * Benchmark shows performance of SET_CONTAINS is better at 50, but similar at 25.
        return SwitchGenerationCase.SET_CONTAINS;
    }

    if (!(type instanceof IntegerType || type instanceof BigintType || type instanceof DateType)) {
        return SwitchGenerationCase.HASH_SWITCH;
    }
    for (RowExpression expression : values) {
        // For non-constant expressions, they will be added to the default case in the generated switch code. They do not affect any of
        // the cases other than the default one. Therefore, it's okay to skip them when choosing between DIRECT_SWITCH and HASH_SWITCH.
        // Same argument applies for nulls.
        if (!(expression instanceof ConstantExpression)) {
            continue;
        }
        Object constant = ((ConstantExpression) expression).getValue();
        if (constant == null) {
            continue;
        }
        long longConstant = ((Number) constant).longValue();
        if (longConstant < Integer.MIN_VALUE || longConstant > Integer.MAX_VALUE) {
            return SwitchGenerationCase.HASH_SWITCH;
        }
    }
    return SwitchGenerationCase.DIRECT_SWITCH;
}
 
Example 20
Source Project: presto   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean canCastToJson(Type type)
{
    if (type instanceof UnknownType ||
            type instanceof BooleanType ||
            type instanceof TinyintType ||
            type instanceof SmallintType ||
            type instanceof IntegerType ||
            type instanceof BigintType ||
            type instanceof RealType ||
            type instanceof DoubleType ||
            type instanceof DecimalType ||
            type instanceof VarcharType ||
            type instanceof JsonType ||
            type instanceof TimestampType ||
            type instanceof DateType) {
        return true;
    }
    if (type instanceof ArrayType) {
        return canCastToJson(((ArrayType) type).getElementType());
    }
    if (type instanceof MapType) {
        MapType mapType = (MapType) type;
        return (mapType.getKeyType() instanceof UnknownType ||
                isValidJsonObjectKeyType(mapType.getKeyType())) &&
                canCastToJson(mapType.getValueType());
    }
    if (type instanceof RowType) {
        return type.getTypeParameters().stream().allMatch(JsonUtil::canCastToJson);
    }
    return false;
}
 
Example 21
Source Project: presto   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isValidJsonObjectKeyType(Type type)
{
    return type instanceof BooleanType ||
            type instanceof TinyintType ||
            type instanceof SmallintType ||
            type instanceof IntegerType ||
            type instanceof BigintType ||
            type instanceof RealType ||
            type instanceof DoubleType ||
            type instanceof DecimalType ||
            type instanceof VarcharType;
}
 
Example 22
Source Project: presto   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
static ObjectKeyProvider createObjectKeyProvider(Type type)
{
    if (type instanceof UnknownType) {
        return (block, position) -> null;
    }
    if (type instanceof BooleanType) {
        return (block, position) -> type.getBoolean(block, position) ? "true" : "false";
    }
    if (type instanceof TinyintType || type instanceof SmallintType || type instanceof IntegerType || type instanceof BigintType) {
        return (block, position) -> String.valueOf(type.getLong(block, position));
    }
    if (type instanceof RealType) {
        return (block, position) -> String.valueOf(intBitsToFloat(toIntExact(type.getLong(block, position))));
    }
    if (type instanceof DoubleType) {
        return (block, position) -> String.valueOf(type.getDouble(block, position));
    }
    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        if (isShortDecimal(decimalType)) {
            return (block, position) -> Decimals.toString(decimalType.getLong(block, position), decimalType.getScale());
        }
        return (block, position) -> Decimals.toString(
                decodeUnscaledValue(type.getSlice(block, position)),
                decimalType.getScale());
    }
    if (type instanceof VarcharType) {
        return (block, position) -> type.getSlice(block, position).toStringUtf8();
    }

    throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Unsupported type: %s", type));
}
 
Example 23
Source Project: presto   Source File: TestQueryResultRows.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleNullValues()
{
    List<Column> columns = ImmutableList.of(new Column("_col0", INTEGER, new ClientTypeSignature(INTEGER)), new Column("_col1", BOOLEAN, new ClientTypeSignature(BOOLEAN)));
    List<Type> types = ImmutableList.of(IntegerType.INTEGER, BooleanType.BOOLEAN);

    List<Page> pages = rowPagesBuilder(types)
            .row(0, null)
            .pageBreak()
            .row(1, null)
            .pageBreak()
            .row(2, true)
            .build();

    TestExceptionConsumer exceptionConsumer = new TestExceptionConsumer();
    QueryResultRows rows = queryResultRowsBuilder(getSession())
            .withColumnsAndTypes(columns, types)
            .withExceptionConsumer(exceptionConsumer)
            .addPages(pages)
            .build();

    assertFalse(rows.isEmpty(), "rows are empty");
    assertThat(rows.getTotalRowsCount()).isEqualTo(3);

    assertThat(getAllValues(rows))
            .hasSize(3)
            .containsExactly(newArrayList(0, null), newArrayList(1, null), newArrayList(2, true));
}
 
Example 24
Source Project: presto   Source File: TestQueryResultRows.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "columns and types size mismatch")
public void shouldThrowWhenColumnsAndTypesSizeMismatch()
{
    List<Column> columns = ImmutableList.of(INT_COLUMN.apply("_col0"));
    List<Type> types = ImmutableList.of(IntegerType.INTEGER, BooleanType.BOOLEAN);

    List<Page> pages = rowPagesBuilder(types)
            .row(0, null)
            .build();

    queryResultRowsBuilder(getSession())
            .addPages(pages)
            .withColumnsAndTypes(columns, types)
            .build();
}
 
Example 25
Source Project: presto   Source File: TestQueryResultRows.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "columns and types must be present at the same time")
public void shouldThrowWhenColumnsAreNull()
{
    List<Type> types = ImmutableList.of(IntegerType.INTEGER, BooleanType.BOOLEAN);

    List<Page> pages = rowPagesBuilder(types)
            .row(0, null)
            .build();

    queryResultRowsBuilder(getSession())
            .addPages(pages)
            .withColumnsAndTypes(null, types)
            .build();
}
 
Example 26
Source Project: presto   Source File: TestQueryResultRows.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "columns and types must be present at the same time")
public void shouldThrowWhenTypesAreNull()
{
    List<Column> columns = ImmutableList.of(INT_COLUMN.apply("_col0"));
    List<Type> types = ImmutableList.of(IntegerType.INTEGER, BooleanType.BOOLEAN);

    List<Page> pages = rowPagesBuilder(types)
            .row(0, null)
            .build();

    queryResultRowsBuilder(getSession())
            .addPages(pages)
            .withColumnsAndTypes(columns, null)
            .build();
}
 
Example 27
Source Project: presto   Source File: TestQueryResultRows.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "data present without columns and types")
public void shouldThrowWhenDataIsPresentWithoutColumns()
{
    List<Page> pages = rowPagesBuilder(ImmutableList.of(IntegerType.INTEGER, BooleanType.BOOLEAN))
            .row(0, null)
            .build();

    queryResultRowsBuilder(getSession())
            .addPages(pages)
            .build();
}
 
Example 28
Source Project: presto   Source File: MongoSession.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<Object> translateValue(Object prestoNativeValue, Type type)
{
    requireNonNull(prestoNativeValue, "prestoNativeValue is null");
    requireNonNull(type, "type is null");
    checkArgument(Primitives.wrap(type.getJavaType()).isInstance(prestoNativeValue), "%s (%s) is not a valid representation for %s", prestoNativeValue, prestoNativeValue.getClass(), type);

    if (type == TINYINT) {
        return Optional.of((long) SignedBytes.checkedCast(((Long) prestoNativeValue)));
    }

    if (type == SMALLINT) {
        return Optional.of((long) Shorts.checkedCast(((Long) prestoNativeValue)));
    }

    if (type == IntegerType.INTEGER) {
        return Optional.of((long) toIntExact(((Long) prestoNativeValue)));
    }

    if (type == BIGINT) {
        return Optional.of(prestoNativeValue);
    }

    if (type instanceof ObjectIdType) {
        return Optional.of(new ObjectId(((Slice) prestoNativeValue).getBytes()));
    }

    if (type instanceof VarcharType) {
        return Optional.of(((Slice) prestoNativeValue).toStringUtf8());
    }

    return Optional.empty();
}
 
Example 29
Source Project: presto   Source File: ExpressionConverter.java    License: Apache License 2.0 5 votes vote down vote up
private static Object getIcebergLiteralValue(Type type, Marker marker)
{
    if (type instanceof IntegerType) {
        return toIntExact((long) marker.getValue());
    }

    if (type instanceof RealType) {
        return intBitsToFloat(toIntExact((long) marker.getValue()));
    }

    // TODO: Remove this conversion once we move to next iceberg version
    if (type instanceof DateType) {
        return toIntExact(((Long) marker.getValue()));
    }

    if (type instanceof VarcharType) {
        return ((Slice) marker.getValue()).toStringUtf8();
    }

    if (type instanceof VarbinaryType) {
        return ByteBuffer.wrap(((Slice) marker.getValue()).getBytes());
    }

    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        Object value = requireNonNull(marker.getValue(), "The value of the marker must be non-null");
        if (Decimals.isShortDecimal(decimalType)) {
            checkArgument(value instanceof Long, "A short decimal should be represented by a Long value but was %s", value.getClass().getName());
            return BigDecimal.valueOf((long) value).movePointLeft(decimalType.getScale());
        }
        checkArgument(value instanceof Slice, "A long decimal should be represented by a Slice value but was %s", value.getClass().getName());
        return new BigDecimal(Decimals.decodeUnscaledValue((Slice) value), decimalType.getScale());
    }

    return marker.getValue();
}
 
Example 30
Source Project: presto   Source File: IcebergPageSink.java    License: Apache License 2.0 5 votes vote down vote up
public static Object getIcebergValue(Block block, int position, Type type)
{
    if (block.isNull(position)) {
        return null;
    }
    if (type instanceof BigintType) {
        return type.getLong(block, position);
    }
    if (type instanceof IntegerType || type instanceof SmallintType || type instanceof TinyintType || type instanceof DateType) {
        return toIntExact(type.getLong(block, position));
    }
    if (type instanceof BooleanType) {
        return type.getBoolean(block, position);
    }
    if (type instanceof DecimalType) {
        return readBigDecimal((DecimalType) type, block, position);
    }
    if (type instanceof RealType) {
        return intBitsToFloat(toIntExact(type.getLong(block, position)));
    }
    if (type instanceof DoubleType) {
        return type.getDouble(block, position);
    }
    if (type instanceof TimestampType) {
        return MILLISECONDS.toMicros(type.getLong(block, position));
    }
    if (type instanceof TimestampWithTimeZoneType) {
        return MILLISECONDS.toMicros(unpackMillisUtc(type.getLong(block, position)));
    }
    if (type instanceof VarbinaryType) {
        return type.getSlice(block, position).getBytes();
    }
    if (type instanceof VarcharType) {
        return type.getSlice(block, position).toStringUtf8();
    }
    throw new UnsupportedOperationException("Type not supported as partition column: " + type.getDisplayName());
}