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

The following examples show how to use io.prestosql.spi.type.DoubleType. 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: PrometheusClient.java    License: Apache License 2.0 6 votes vote down vote up
public PrometheusTable getTable(String schema, String tableName)
{
    requireNonNull(schema, "schema is null");
    requireNonNull(tableName, "tableName is null");
    if (schema.equals("default")) {
        List<String> tableNames = (List<String>) tableSupplier.get().get("data");
        if (tableNames == null) {
            return null;
        }
        if (!tableNames.contains(tableName)) {
            return null;
        }
        MapType varcharMapType = (MapType) typeManager.getType(mapType(VARCHAR.getTypeSignature(), VARCHAR.getTypeSignature()));
        PrometheusTable table = new PrometheusTable(
                tableName,
                ImmutableList.of(
                        new PrometheusColumn("labels", varcharMapType),
                        new PrometheusColumn("timestamp", TimestampType.TIMESTAMP),
                        new PrometheusColumn("value", DoubleType.DOUBLE)));
        PrometheusTableHandle tableHandle = new PrometheusTableHandle(schema, tableName);
        return table;
    }
    return null;
}
 
Example 2
Source Project: presto   Source File: TestPrometheusIntegrationTests1.java    License: Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = "testRetrieveUpValue")
public void testGetColumnTypes()
        throws Exception
{
    URI dataUri = new URI("http://" + server.getAddress().getHost() + ":" + server.getAddress().getPort() + "/");
    RecordSet recordSet = new PrometheusRecordSet(new PrometheusSplit(dataUri), ImmutableList.of(
            new PrometheusColumnHandle("labels", createUnboundedVarcharType(), 0),
            new PrometheusColumnHandle("value", DoubleType.DOUBLE, 1),
            new PrometheusColumnHandle("timestamp", TimestampType.TIMESTAMP, 2)));
    assertEquals(recordSet.getColumnTypes(), ImmutableList.of(createUnboundedVarcharType(), DoubleType.DOUBLE, TimestampType.TIMESTAMP));

    recordSet = new PrometheusRecordSet(new PrometheusSplit(dataUri), ImmutableList.of(
            new PrometheusColumnHandle("value", BIGINT, 1),
            new PrometheusColumnHandle("text", createUnboundedVarcharType(), 0)));
    assertEquals(recordSet.getColumnTypes(), ImmutableList.of(BIGINT, createUnboundedVarcharType()));

    recordSet = new PrometheusRecordSet(new PrometheusSplit(dataUri), ImmutableList.of(
            new PrometheusColumnHandle("value", BIGINT, 1),
            new PrometheusColumnHandle("value", BIGINT, 1),
            new PrometheusColumnHandle("text", createUnboundedVarcharType(), 0)));
    assertEquals(recordSet.getColumnTypes(), ImmutableList.of(BIGINT, BIGINT, createUnboundedVarcharType()));

    recordSet = new PrometheusRecordSet(new PrometheusSplit(dataUri), ImmutableList.of());
    assertEquals(recordSet.getColumnTypes(), ImmutableList.of());
}
 
Example 3
Source Project: presto   Source File: DoubleHistogramAggregation.java    License: Apache License 2.0 6 votes vote down vote up
@OutputFunction("map(double,double)")
public static void output(@AggregationState State state, BlockBuilder out)
{
    if (state.get() == null) {
        out.appendNull();
    }
    else {
        Map<Double, Double> value = state.get().getBuckets();

        BlockBuilder entryBuilder = out.beginBlockEntry();
        for (Map.Entry<Double, Double> entry : value.entrySet()) {
            DoubleType.DOUBLE.writeDouble(entryBuilder, entry.getKey());
            DoubleType.DOUBLE.writeDouble(entryBuilder, entry.getValue());
        }
        out.closeEntry();
    }
}
 
Example 4
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 5
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 6
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 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: TestAnnotationEngineForAggregates.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStateOnDifferentThanFirstPositionAggregationParse()
{
    Signature expectedSignature = new Signature(
            "simple_exact_aggregate_aggregation_state_moved",
            DoubleType.DOUBLE.getTypeSignature(),
            ImmutableList.of(DoubleType.DOUBLE.getTypeSignature()));

    ParametricAggregation aggregation = parseFunctionDefinition(StateOnDifferentThanFirstPositionAggregationFunction.class);
    assertEquals(aggregation.getFunctionMetadata().getSignature(), expectedSignature);

    AggregationImplementation implementation = getOnlyElement(aggregation.getImplementations().getExactImplementations().values());
    assertEquals(implementation.getDefinitionClass(), StateOnDifferentThanFirstPositionAggregationFunction.class);
    List<AggregationMetadata.ParameterMetadata.ParameterType> expectedMetadataTypes = ImmutableList.of(AggregationMetadata.ParameterMetadata.ParameterType.INPUT_CHANNEL, AggregationMetadata.ParameterMetadata.ParameterType.STATE);
    assertTrue(implementation.getInputParameterMetadataTypes().equals(expectedMetadataTypes));
}
 
Example 9
Source Project: presto   Source File: TestAnnotationEngineForAggregates.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNotDecomposableAggregationParse()
{
    Signature expectedSignature = new Signature(
            "custom_decomposable_aggregate",
            DoubleType.DOUBLE.getTypeSignature(),
            ImmutableList.of(DoubleType.DOUBLE.getTypeSignature()));

    ParametricAggregation aggregation = parseFunctionDefinition(NotDecomposableAggregationFunction.class);
    assertEquals(aggregation.getFunctionMetadata().getDescription(), "Aggregate with Decomposable=false");
    assertTrue(aggregation.getFunctionMetadata().isDeterministic());
    assertEquals(aggregation.getFunctionMetadata().getSignature(), expectedSignature);
    assertFalse(aggregation.isDecomposable());

    InternalAggregationFunction specialized = aggregation.specialize(BoundVariables.builder().build(), 1, METADATA);
    assertEquals(specialized.getFinalType(), DoubleType.DOUBLE);
    assertEquals(specialized.name(), "custom_decomposable_aggregate");
}
 
Example 10
Source Project: presto   Source File: TestAnnotationEngineForAggregates.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFixedTypeParameterInjectionAggregateFunctionParse()
{
    Signature expectedSignature = new Signature(
            "fixed_type_parameter_injection",
            ImmutableList.of(),
            ImmutableList.of(),
            DoubleType.DOUBLE.getTypeSignature(),
            ImmutableList.of(DoubleType.DOUBLE.getTypeSignature()),
            false);

    ParametricAggregation aggregation = parseFunctionDefinition(FixedTypeParameterInjectionAggregateFunction.class);
    assertEquals(aggregation.getFunctionMetadata().getDescription(), "Simple aggregate with fixed parameter type injected");
    assertTrue(aggregation.getFunctionMetadata().isDeterministic());
    assertEquals(aggregation.getFunctionMetadata().getSignature(), expectedSignature);
    ParametricImplementationsGroup<AggregationImplementation> implementations = aggregation.getImplementations();
    assertImplementationCount(implementations, 1, 0, 0);
    AggregationImplementation implementationDouble = implementations.getExactImplementations().get(expectedSignature);
    assertFalse(implementationDouble.getStateSerializerFactory().isPresent());
    assertEquals(implementationDouble.getDefinitionClass(), FixedTypeParameterInjectionAggregateFunction.class);
    assertDependencyCount(implementationDouble, 1, 1, 1);
    assertFalse(implementationDouble.hasSpecializedTypeParameters());
    List<AggregationMetadata.ParameterMetadata.ParameterType> expectedMetadataTypes = ImmutableList.of(AggregationMetadata.ParameterMetadata.ParameterType.STATE, AggregationMetadata.ParameterMetadata.ParameterType.INPUT_CHANNEL);
    assertTrue(implementationDouble.getInputParameterMetadataTypes().equals(expectedMetadataTypes));
    assertEquals(implementationDouble.getStateClass(), NullableDoubleState.class);
}
 
Example 11
Source Project: presto   Source File: MLFeaturesFunctions.java    License: Apache License 2.0 6 votes vote down vote up
private static Block featuresHelper(PageBuilder pageBuilder, double... features)
{
    if (pageBuilder.isFull()) {
        pageBuilder.reset();
    }

    BlockBuilder mapBlockBuilder = pageBuilder.getBlockBuilder(0);
    BlockBuilder blockBuilder = mapBlockBuilder.beginBlockEntry();

    for (int i = 0; i < features.length; i++) {
        BigintType.BIGINT.writeLong(blockBuilder, i);
        DoubleType.DOUBLE.writeDouble(blockBuilder, features[i]);
    }

    mapBlockBuilder.closeEntry();
    pageBuilder.declarePosition();
    return mapBlockBuilder.getObject(mapBlockBuilder.getPositionCount() - 1, Block.class);
}
 
Example 12
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 13
Source Project: presto   Source File: TestAvroDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSupportedDataTypeValidation()
{
    // supported types
    singleColumnDecoder(BigintType.BIGINT);
    singleColumnDecoder(VarbinaryType.VARBINARY);
    singleColumnDecoder(BooleanType.BOOLEAN);
    singleColumnDecoder(DoubleType.DOUBLE);
    singleColumnDecoder(createUnboundedVarcharType());
    singleColumnDecoder(createVarcharType(100));
    singleColumnDecoder(new ArrayType(BigintType.BIGINT));
    singleColumnDecoder(VARCHAR_MAP_TYPE);
    singleColumnDecoder(DOUBLE_MAP_TYPE);

    // some unsupported types
    assertUnsupportedColumnTypeException(() -> singleColumnDecoder(DecimalType.createDecimalType(10, 4)));
}
 
Example 14
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 15
Source Project: presto   Source File: TestRawDecoder.java    License: Apache License 2.0 6 votes vote down vote up
private void checkTwice(Map<DecoderColumnHandle, FieldValueProvider> decodedRow, DecoderColumnHandle handle)
{
    FieldValueProvider provider = decodedRow.get(handle);
    assertNotNull(provider);
    Type type = handle.getType();
    if (type == BigintType.BIGINT) {
        assertEquals(provider.getLong(), provider.getLong());
    }
    else if (type == BooleanType.BOOLEAN) {
        assertEquals(provider.getBoolean(), provider.getBoolean());
    }
    else if (type == DoubleType.DOUBLE) {
        assertEquals(provider.getDouble(), provider.getDouble());
    }
    else if (type == VarcharType.VARCHAR) {
        assertEquals(provider.getSlice(), provider.getSlice());
    }
}
 
Example 16
Source Project: presto   Source File: TestCsvDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNulls()
{
    String csv = ",,,";

    DecoderTestColumnHandle row1 = new DecoderTestColumnHandle(0, "row1", createVarcharType(10), "0", null, null, false, false, false);
    DecoderTestColumnHandle row2 = new DecoderTestColumnHandle(1, "row2", BigintType.BIGINT, "1", null, null, false, false, false);
    DecoderTestColumnHandle row3 = new DecoderTestColumnHandle(2, "row3", DoubleType.DOUBLE, "2", null, null, false, false, false);
    DecoderTestColumnHandle row4 = new DecoderTestColumnHandle(3, "row4", BooleanType.BOOLEAN, "3", null, null, false, false, false);

    Set<DecoderColumnHandle> columns = ImmutableSet.of(row1, row2, row3, row4);
    RowDecoder rowDecoder = DECODER_FACTORY.create(emptyMap(), columns);

    Map<DecoderColumnHandle, FieldValueProvider> decodedRow = rowDecoder.decodeRow(csv.getBytes(StandardCharsets.UTF_8), null)
            .orElseThrow(AssertionError::new);

    assertEquals(decodedRow.size(), columns.size());

    checkIsNull(decodedRow, row1);
    checkIsNull(decodedRow, row2);
    checkIsNull(decodedRow, row3);
    checkIsNull(decodedRow, row4);
}
 
Example 17
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 18
Source Project: presto   Source File: TestPrometheusTable.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testColumnMetadata()
{
    assertEquals(prometheusTable.getColumnsMetadata(), ImmutableList.of(
            new ColumnMetadata("labels", varcharMapType),
            new ColumnMetadata("timestamp", TimestampType.TIMESTAMP),
            new ColumnMetadata("value", DoubleType.DOUBLE)));
}
 
Example 19
Source Project: presto   Source File: TestPrometheusIntegrationTests2.java    License: Apache License 2.0 5 votes vote down vote up
@Test(dependsOnMethods = "testRetrieveUpValue")
public void testMetadata()
        throws Exception
{
    assertTrue(client.getTableNames("default").contains("up"));
    PrometheusTable table = client.getTable("default", "up");
    assertNotNull(table, "table is null");
    assertEquals(table.getName(), "up");
    assertEquals(table.getColumns(), ImmutableList.of(
            new PrometheusColumn("labels", varcharMapType),
            new PrometheusColumn("timestamp", TimestampType.TIMESTAMP),
            new PrometheusColumn("value", DoubleType.DOUBLE)));
}
 
Example 20
Source Project: presto   Source File: TestPrometheusRecordSetProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRecordSet()
{
    ConnectorTableHandle tableHandle = new PrometheusTableHandle("schema", "table");
    PrometheusRecordSetProvider recordSetProvider = new PrometheusRecordSetProvider();
    RecordSet recordSet = recordSetProvider.getRecordSet(PrometheusTransactionHandle.INSTANCE, SESSION,
            new PrometheusSplit(dataUri), tableHandle, ImmutableList.of(
                    new PrometheusColumnHandle("labels", varcharMapType, 0),
                    new PrometheusColumnHandle("timestamp", TimestampType.TIMESTAMP, 1),
                    new PrometheusColumnHandle("value", DoubleType.DOUBLE, 2)));
    assertNotNull(recordSet, "recordSet is null");

    RecordCursor cursor = recordSet.cursor();
    assertNotNull(cursor, "cursor is null");

    Map<Timestamp, Map> actual = new LinkedHashMap<>();
    while (cursor.advanceNextPosition()) {
        actual.put((Timestamp) cursor.getObject(1), (Map) getMapFromBlock(varcharMapType, (Block) cursor.getObject(0)));
    }
    Map<Timestamp, Map> expected = ImmutableMap.<Timestamp, Map>builder()
            .put(Timestamp.from(Instant.ofEpochMilli(1565962969044L)), ImmutableMap.of("instance",
                    "localhost:9090", "__name__", "up", "job", "prometheus"))
            .put(Timestamp.from(Instant.ofEpochMilli(1565962984045L)), ImmutableMap.of("instance",
                    "localhost:9090", "__name__", "up", "job", "prometheus"))
            .put(Timestamp.from(Instant.ofEpochMilli(1565962999044L)), ImmutableMap.of("instance",
                    "localhost:9090", "__name__", "up", "job", "prometheus"))
            .put(Timestamp.from(Instant.ofEpochMilli(1565963014044L)), ImmutableMap.of("instance",
                    "localhost:9090", "__name__", "up", "job", "prometheus"))
            .build();
    assertEquals(actual, expected);
}
 
Example 21
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 22
Source Project: presto   Source File: TestPostgreSqlTypeMapping.java    License: Apache License 2.0 5 votes vote down vote up
private static DataType<Double> postgreSqlDoubleDataType()
{
    return dataType("double precision", DoubleType.DOUBLE,
            value -> {
                if (Double.isFinite(value)) {
                    return value.toString();
                }
                if (Double.isNaN(value)) {
                    return "'NaN'::double precision";
                }
                return format("'%sInfinity'::double precision", value > 0 ? "+" : "-");
            },
            doubleDataType()::toPrestoLiteral,
            Function.identity());
}
 
Example 23
Source Project: presto   Source File: DoubleColumnReader.java    License: Apache License 2.0 5 votes vote down vote up
public DoubleColumnReader(Type type, OrcColumn column, LocalMemoryContext systemMemoryContext)
        throws OrcCorruptionException
{
    requireNonNull(type, "type is null");
    verifyStreamType(column, type, DoubleType.class::isInstance);

    this.column = requireNonNull(column, "column is null");
    this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null");
}
 
Example 24
Source Project: presto   Source File: DataType.java    License: Apache License 2.0 5 votes vote down vote up
public static DataType<Double> doubleDataType()
{
    return dataType("double", DoubleType.DOUBLE,
            value -> {
                if (Double.isFinite(value)) {
                    return value.toString();
                }
                if (Double.isNaN(value)) {
                    return "nan()";
                }
                return format("%sinfinity()", value > 0 ? "+" : "-");
            });
}
 
Example 25
Source Project: presto   Source File: DoubleSumAggregation.java    License: Apache License 2.0 5 votes vote down vote up
@OutputFunction(StandardTypes.DOUBLE)
public static void output(@AggregationState LongDoubleState state, BlockBuilder out)
{
    if (state.getFirst() == 0) {
        out.appendNull();
    }
    else {
        DoubleType.DOUBLE.writeDouble(out, state.getSecond());
    }
}
 
Example 26
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 27
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 28
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 29
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 30
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));
}