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

The following examples show how to use io.prestosql.spi.type.VarcharType. 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: AccumuloRowSerializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Recursive helper function used by {@link AccumuloRowSerializer#getArrayFromBlock} and
 * {@link AccumuloRowSerializer#getMapFromBlock} to decode the Block into a Java type.
 *
 * @param type Presto type
 * @param block Block to decode
 * @param position Position in the block to get
 * @return Java object from the Block
 */
static Object readObject(Type type, Block block, int position)
{
    if (Types.isArrayType(type)) {
        Type elementType = Types.getElementType(type);
        return getArrayFromBlock(elementType, block.getObject(position, Block.class));
    }
    else if (Types.isMapType(type)) {
        return getMapFromBlock(type, block.getObject(position, Block.class));
    }
    else {
        if (type.getJavaType() == Slice.class) {
            Slice slice = (Slice) TypeUtils.readNativeValue(type, block, position);
            return type.equals(VarcharType.VARCHAR) ? slice.toStringUtf8() : slice.getBytes();
        }

        return TypeUtils.readNativeValue(type, block, position);
    }
}
 
Example 2
Source Project: presto   Source File: LexicoderRowSerializer.java    License: Apache License 2.0 6 votes vote down vote up
public static Lexicoder getLexicoder(Type type)
{
    if (Types.isArrayType(type)) {
        return getListLexicoder(type);
    }
    else if (Types.isMapType(type)) {
        return getMapLexicoder(type);
    }
    else if (type instanceof VarcharType) {
        return LEXICODER_MAP.get(VARCHAR);
    }
    else {
        Lexicoder lexicoder = LEXICODER_MAP.get(type);
        if (lexicoder == null) {
            throw new PrestoException(NOT_SUPPORTED, "No lexicoder for type " + type);
        }
        return lexicoder;
    }
}
 
Example 3
Source Project: presto   Source File: ColumnIndexStatsUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static JDBCType jdbcType(Type type)
{
    if (type.equals(BOOLEAN)) {
        return JDBCType.BOOLEAN;
    }
    if (type.equals(BIGINT) || type.equals(TIMESTAMP)) {
        return JDBCType.BIGINT;
    }
    if (type.equals(INTEGER)) {
        return JDBCType.INTEGER;
    }
    if (type.equals(DOUBLE)) {
        return JDBCType.DOUBLE;
    }
    if (type.equals(DATE)) {
        return JDBCType.INTEGER;
    }
    if (type instanceof VarcharType) {
        return JDBCType.VARBINARY;
    }
    return null;
}
 
Example 4
Source Project: presto   Source File: AvroColumnDecoder.java    License: Apache License 2.0 6 votes vote down vote up
private static Slice getSlice(Object value, Type type, String columnName)
{
    if (type instanceof VarcharType && (value instanceof CharSequence || value instanceof GenericEnumSymbol)) {
        return truncateToLength(utf8Slice(value.toString()), type);
    }

    if (type instanceof VarbinaryType) {
        if (value instanceof ByteBuffer) {
            return Slices.wrappedBuffer((ByteBuffer) value);
        }
        else if (value instanceof GenericFixed) {
            return Slices.wrappedBuffer(((GenericFixed) value).bytes());
        }
    }

    throw new PrestoException(DECODER_CONVERSION_NOT_SUPPORTED, format("cannot decode object of '%s' as '%s' for column '%s'", value.getClass(), type, columnName));
}
 
Example 5
Source Project: presto   Source File: VarcharToIntegerNumberCoercer.java    License: Apache License 2.0 6 votes vote down vote up
public VarcharToIntegerNumberCoercer(VarcharType fromType, T toType)
{
    super(fromType, toType);

    if (toType.equals(TINYINT)) {
        minValue = Byte.MIN_VALUE;
        maxValue = Byte.MAX_VALUE;
    }
    else if (toType.equals(SMALLINT)) {
        minValue = Short.MIN_VALUE;
        maxValue = Short.MAX_VALUE;
    }
    else if (toType.equals(INTEGER)) {
        minValue = Integer.MIN_VALUE;
        maxValue = Integer.MAX_VALUE;
    }
    else if (toType.equals(BIGINT)) {
        minValue = Long.MIN_VALUE;
        maxValue = Long.MAX_VALUE;
    }
    else {
        throw new PrestoException(NOT_SUPPORTED, format("Could not create Coercer from from varchar to %s", toType));
    }
}
 
Example 6
Source Project: presto   Source File: LiteralFunction.java    License: Apache License 2.0 6 votes vote down vote up
public static Type typeForMagicLiteral(Type type)
{
    Class<?> clazz = type.getJavaType();
    clazz = Primitives.unwrap(clazz);

    if (clazz == long.class) {
        return BIGINT;
    }
    if (clazz == double.class) {
        return DOUBLE;
    }
    if (!clazz.isPrimitive()) {
        if (type instanceof VarcharType) {
            return type;
        }
        else {
            return VARBINARY;
        }
    }
    if (clazz == boolean.class) {
        return BOOLEAN;
    }
    throw new IllegalArgumentException("Unhandled Java type: " + clazz.getName());
}
 
Example 7
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 8
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 9
Source Project: presto   Source File: ExpressionAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Type visitLikePredicate(LikePredicate node, StackableAstVisitorContext<Context> context)
{
    Type valueType = process(node.getValue(), context);
    if (!(valueType instanceof CharType) && !(valueType instanceof VarcharType)) {
        coerceType(context, node.getValue(), VARCHAR, "Left side of LIKE expression");
    }

    Type patternType = getVarcharType(node.getPattern(), context);
    coerceType(context, node.getPattern(), patternType, "Pattern for LIKE expression");
    if (node.getEscape().isPresent()) {
        Expression escape = node.getEscape().get();
        Type escapeType = getVarcharType(escape, context);
        coerceType(context, escape, escapeType, "Escape for LIKE expression");
    }

    return setExpressionType(node, BOOLEAN);
}
 
Example 10
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 11
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 12
Source Project: presto   Source File: TestMapAggFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapAgg()
{
    assertWindowQuery("map_agg(orderkey, orderstatus) OVER(PARTITION BY orderdate)",
            resultBuilder(TEST_SESSION, BIGINT, VarcharType.createVarcharType(1), mapType(BIGINT, VarcharType.createVarcharType(1)))
                    .row(1, "O", ImmutableMap.of(1, "O"))
                    .row(2, "O", ImmutableMap.of(2, "O"))
                    .row(3, "F", ImmutableMap.of(3, "F"))
                    .row(4, "O", ImmutableMap.of(4, "O"))
                    .row(5, "F", ImmutableMap.of(5, "F"))
                    .row(6, "F", ImmutableMap.of(6, "F"))
                    .row(7, "O", ImmutableMap.of(7, "O"))
                    .row(32, "O", ImmutableMap.of(32, "O"))
                    .row(33, "F", ImmutableMap.of(33, "F"))
                    .row(34, "O", ImmutableMap.of(34, "O"))
                    .build());
}
 
Example 13
Source Project: presto   Source File: TestVariableWidthBlock.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSizeInBytes()
{
    int numEntries = 1000;
    VarcharType unboundedVarcharType = createUnboundedVarcharType();
    VariableWidthBlockBuilder blockBuilder = new VariableWidthBlockBuilder(null, numEntries, 20 * numEntries);
    for (int i = 0; i < numEntries; i++) {
        unboundedVarcharType.writeString(blockBuilder, String.valueOf(ThreadLocalRandom.current().nextLong()));
    }
    Block block = blockBuilder.build();

    List<Block> splitQuarter = splitBlock(block, 4);
    long sizeInBytes = block.getSizeInBytes();
    long quarter1size = splitQuarter.get(0).getSizeInBytes();
    long quarter2size = splitQuarter.get(1).getSizeInBytes();
    long quarter3size = splitQuarter.get(2).getSizeInBytes();
    long quarter4size = splitQuarter.get(3).getSizeInBytes();
    double expectedQuarterSizeMin = sizeInBytes * 0.2;
    double expectedQuarterSizeMax = sizeInBytes * 0.3;
    assertTrue(quarter1size > expectedQuarterSizeMin && quarter1size < expectedQuarterSizeMax, format("quarter1size is %s, should be between %s and %s", quarter1size, expectedQuarterSizeMin, expectedQuarterSizeMax));
    assertTrue(quarter2size > expectedQuarterSizeMin && quarter2size < expectedQuarterSizeMax, format("quarter2size is %s, should be between %s and %s", quarter2size, expectedQuarterSizeMin, expectedQuarterSizeMax));
    assertTrue(quarter3size > expectedQuarterSizeMin && quarter3size < expectedQuarterSizeMax, format("quarter3size is %s, should be between %s and %s", quarter3size, expectedQuarterSizeMin, expectedQuarterSizeMax));
    assertTrue(quarter4size > expectedQuarterSizeMin && quarter4size < expectedQuarterSizeMax, format("quarter4size is %s, should be between %s and %s", quarter4size, expectedQuarterSizeMin, expectedQuarterSizeMax));
    assertEquals(quarter1size + quarter2size + quarter3size + quarter4size, sizeInBytes);
}
 
Example 14
Source Project: presto   Source File: TestTypeValidator.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp()
{
    symbolAllocator = new SymbolAllocator();
    columnA = symbolAllocator.newSymbol("a", BIGINT);
    columnB = symbolAllocator.newSymbol("b", INTEGER);
    columnC = symbolAllocator.newSymbol("c", DOUBLE);
    columnD = symbolAllocator.newSymbol("d", DATE);
    columnE = symbolAllocator.newSymbol("e", VarcharType.createVarcharType(3));  // varchar(3), to test type only coercion

    Map<Symbol, ColumnHandle> assignments = ImmutableMap.<Symbol, ColumnHandle>builder()
            .put(columnA, new TestingColumnHandle("a"))
            .put(columnB, new TestingColumnHandle("b"))
            .put(columnC, new TestingColumnHandle("c"))
            .put(columnD, new TestingColumnHandle("d"))
            .put(columnE, new TestingColumnHandle("e"))
            .build();

    baseTableScan = new TableScanNode(
            newId(),
            TEST_TABLE_HANDLE,
            ImmutableList.copyOf(assignments.keySet()),
            assignments,
            TupleDomain.all());
}
 
Example 15
Source Project: presto   Source File: PrometheusRecordCursor.java    License: Apache License 2.0 5 votes vote down vote up
static void writeObject(BlockBuilder builder, Type type, Object obj)
{
    if (Types.isArrayType(type)) {
        BlockBuilder arrayBldr = builder.beginBlockEntry();
        Type elementType = Types.getElementType(type);
        for (Object item : (List<?>) obj) {
            writeObject(arrayBldr, elementType, item);
        }
        builder.closeEntry();
    }
    else if (Types.isMapType(type)) {
        BlockBuilder mapBlockBuilder = builder.beginBlockEntry();
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) obj).entrySet()) {
            writeObject(mapBlockBuilder, Types.getKeyType(type), entry.getKey());
            writeObject(mapBlockBuilder, Types.getValueType(type), entry.getValue());
        }
        builder.closeEntry();
    }
    else {
        if (BOOLEAN.equals(type)
                || TINYINT.equals(type)
                || SMALLINT.equals(type)
                || INTEGER.equals(type)
                || BIGINT.equals(type)
                || DOUBLE.equals(type)
                || type instanceof VarcharType) {
            TypeUtils.writeNativeValue(type, builder, obj);
        }
    }
}
 
Example 16
Source Project: presto   Source File: HiveCoercionPolicy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean canCoerce(HiveType fromHiveType, HiveType toHiveType)
{
    Type fromType = typeManager.getType(fromHiveType.getTypeSignature());
    Type toType = typeManager.getType(toHiveType.getTypeSignature());
    if (fromType instanceof VarcharType) {
        return toHiveType.equals(HIVE_BYTE) || toHiveType.equals(HIVE_SHORT) || toHiveType.equals(HIVE_INT) || toHiveType.equals(HIVE_LONG);
    }
    if (toType instanceof VarcharType) {
        return fromHiveType.equals(HIVE_BYTE) || fromHiveType.equals(HIVE_SHORT) || fromHiveType.equals(HIVE_INT) || fromHiveType.equals(HIVE_LONG);
    }
    if (fromHiveType.equals(HIVE_BYTE)) {
        return toHiveType.equals(HIVE_SHORT) || toHiveType.equals(HIVE_INT) || toHiveType.equals(HIVE_LONG);
    }
    if (fromHiveType.equals(HIVE_SHORT)) {
        return toHiveType.equals(HIVE_INT) || toHiveType.equals(HIVE_LONG);
    }
    if (fromHiveType.equals(HIVE_INT)) {
        return toHiveType.equals(HIVE_LONG);
    }
    if (fromHiveType.equals(HIVE_FLOAT)) {
        return toHiveType.equals(HIVE_DOUBLE) || toType instanceof DecimalType;
    }
    if (fromHiveType.equals(HIVE_DOUBLE)) {
        return toHiveType.equals(HIVE_FLOAT) || toType instanceof DecimalType;
    }
    if (fromType instanceof DecimalType) {
        return toType instanceof DecimalType || toHiveType.equals(HIVE_FLOAT) || toHiveType.equals(HIVE_DOUBLE);
    }

    return canCoerceForList(fromHiveType, toHiveType) || canCoerceForMap(fromHiveType, toHiveType) || canCoerceForStruct(fromHiveType, toHiveType);
}
 
Example 17
Source Project: presto   Source File: TestTypeConversions.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertStringArrayField()
{
    Field field = Field.newBuilder("test", LegacySQLTypeName.STRING)
            .setMode(Field.Mode.REPEATED)
            .build();
    ColumnMetadata metadata = Conversions.toColumnMetadata(field);
    assertThat(metadata.getType()).isEqualTo(new ArrayType(VarcharType.VARCHAR));
}
 
Example 18
Source Project: presto   Source File: AccumuloRecordCursor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Slice getSlice(int field)
{
    Type type = getType(field);
    if (type instanceof VarbinaryType) {
        return Slices.wrappedBuffer(serializer.getVarbinary(fieldToColumnName[field]));
    }
    if (type instanceof VarcharType) {
        return Slices.utf8Slice(serializer.getVarchar(fieldToColumnName[field]));
    }
    throw new PrestoException(NOT_SUPPORTED, "Unsupported type " + type);
}
 
Example 19
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());
}
 
Example 20
Source Project: presto   Source File: PinotSegmentPageSource.java    License: Apache License 2.0 5 votes vote down vote up
Slice getSlice(int rowIndex, int columnIndex)
{
    Type prestoType = getType(columnIndex);
    if (prestoType instanceof VarcharType) {
        String field = currentDataTable.getDataTable().getString(rowIndex, columnIndex);
        return getUtf8Slice(field);
    }
    else if (prestoType instanceof VarbinaryType) {
        return Slices.wrappedBuffer(toBytes(currentDataTable.getDataTable().getString(rowIndex, columnIndex)));
    }
    return Slices.EMPTY_SLICE;
}
 
Example 21
Source Project: presto   Source File: SliceColumnReader.java    License: Apache License 2.0 5 votes vote down vote up
private static int getMaxCodePointCount(Type type)
{
    if (isVarcharType(type)) {
        VarcharType varcharType = (VarcharType) type;
        return varcharType.isUnbounded() ? -1 : varcharType.getBoundedLength();
    }
    if (isCharType(type)) {
        return ((CharType) type).getLength();
    }
    if (isVarbinaryType(type)) {
        return -1;
    }
    throw new IllegalArgumentException("Unsupported encoding " + type.getDisplayName());
}
 
Example 22
Source Project: pulsar   Source File: PulsarRecordCursor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Slice getSlice(int field) {
    checkFieldType(field, Slice.class);

    Object record = getRecord(field);
    Type type = getType(field);
    if (type == VarcharType.VARCHAR) {
        return Slices.utf8Slice(record.toString());
    } else if (type == VarbinaryType.VARBINARY) {
        return Slices.wrappedBuffer(toBytes(record));
    } else {
        throw new PrestoException(NOT_SUPPORTED, "Unsupported type " + type);
    }
}
 
Example 23
Source Project: presto   Source File: HiveCoercionRecordCursor.java    License: Apache License 2.0 5 votes vote down vote up
private static Coercer createCoercer(TypeManager typeManager, HiveType fromHiveType, HiveType toHiveType, BridgingRecordCursor bridgingRecordCursor)
{
    Type fromType = typeManager.getType(fromHiveType.getTypeSignature());
    Type toType = typeManager.getType(toHiveType.getTypeSignature());
    if (toType instanceof VarcharType && (fromHiveType.equals(HIVE_BYTE) || fromHiveType.equals(HIVE_SHORT) || fromHiveType.equals(HIVE_INT) || fromHiveType.equals(HIVE_LONG))) {
        return new IntegerNumberToVarcharCoercer();
    }
    if (fromType instanceof VarcharType && (toHiveType.equals(HIVE_BYTE) || toHiveType.equals(HIVE_SHORT) || toHiveType.equals(HIVE_INT) || toHiveType.equals(HIVE_LONG))) {
        return new VarcharToIntegerNumberCoercer(toHiveType);
    }
    if (fromHiveType.equals(HIVE_BYTE) && toHiveType.equals(HIVE_SHORT) || toHiveType.equals(HIVE_INT) || toHiveType.equals(HIVE_LONG)) {
        return new IntegerNumberUpscaleCoercer();
    }
    if (fromHiveType.equals(HIVE_SHORT) && toHiveType.equals(HIVE_INT) || toHiveType.equals(HIVE_LONG)) {
        return new IntegerNumberUpscaleCoercer();
    }
    if (fromHiveType.equals(HIVE_INT) && toHiveType.equals(HIVE_LONG)) {
        return new IntegerNumberUpscaleCoercer();
    }
    if (fromHiveType.equals(HIVE_FLOAT) && toHiveType.equals(HIVE_DOUBLE)) {
        return new FloatToDoubleCoercer();
    }
    if (isArrayType(fromType) && isArrayType(toType)) {
        return new ListCoercer(typeManager, fromHiveType, toHiveType, bridgingRecordCursor);
    }
    if (isMapType(fromType) && isMapType(toType)) {
        return new MapCoercer(typeManager, fromHiveType, toHiveType, bridgingRecordCursor);
    }
    if (isRowType(fromType) && isRowType(toType)) {
        return new StructCoercer(typeManager, fromHiveType, toHiveType, bridgingRecordCursor);
    }

    throw new PrestoException(NOT_SUPPORTED, format("Unsupported coercion from %s to %s", fromHiveType, toHiveType));
}
 
Example 24
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 25
Source Project: presto   Source File: TpcdsTableStatisticsFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<DoubleRange> toRange(Optional<Object> min, Optional<Object> max, Type columnType)
{
    if (columnType instanceof VarcharType || columnType instanceof CharType || columnType.equals(TIME)) {
        return Optional.empty();
    }
    if (min.isEmpty() || max.isEmpty()) {
        return Optional.empty();
    }
    return Optional.of(new DoubleRange(toDouble(min.get(), columnType), toDouble(max.get(), columnType)));
}
 
Example 26
Source Project: presto   Source File: DataType.java    License: Apache License 2.0 5 votes vote down vote up
private static DataType<String> varcharDataType(Optional<Integer> length, String properties)
{
    String prefix = length.map(size -> "varchar(" + size + ")").orElse("varchar");
    String suffix = properties.isEmpty() ? "" : " " + properties;
    VarcharType varcharType = length.map(VarcharType::createVarcharType).orElse(createUnboundedVarcharType());
    return stringDataType(prefix + suffix, varcharType);
}
 
Example 27
Source Project: presto   Source File: AbstractTestWindowQueries.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWindowMapAgg()
{
    MaterializedResult actual = computeActual("" +
            "SELECT map_agg(orderkey, orderpriority) OVER(PARTITION BY orderstatus) FROM\n" +
            "(SELECT * FROM orders ORDER BY orderkey LIMIT 5) t");
    MaterializedResult expected = resultBuilder(getSession(), mapType(BIGINT, VarcharType.createVarcharType(1)))
            .row(ImmutableMap.of(1L, "5-LOW", 2L, "1-URGENT", 4L, "5-LOW"))
            .row(ImmutableMap.of(1L, "5-LOW", 2L, "1-URGENT", 4L, "5-LOW"))
            .row(ImmutableMap.of(1L, "5-LOW", 2L, "1-URGENT", 4L, "5-LOW"))
            .row(ImmutableMap.of(3L, "5-LOW", 5L, "5-LOW"))
            .row(ImmutableMap.of(3L, "5-LOW", 5L, "5-LOW"))
            .build();
    assertEqualsIgnoreOrder(actual.getMaterializedRows(), expected.getMaterializedRows());
}
 
Example 28
Source Project: presto   Source File: ColumnJdbcTable.java    License: Apache License 2.0 5 votes vote down vote up
private static Integer charOctetLength(Type type)
{
    if (isVarcharType(type)) {
        return ((VarcharType) type).getLength().orElse(VarcharType.UNBOUNDED_LENGTH);
    }
    if (isCharType(type)) {
        return ((CharType) type).getLength();
    }
    if (type.equals(VARBINARY)) {
        return Integer.MAX_VALUE;
    }
    return null;
}
 
Example 29
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 30
Source Project: presto   Source File: LogicalPlanner.java    License: Apache License 2.0 5 votes vote down vote up
private Expression noTruncationCast(Expression expression, Type fromType, Type toType)
{
    if (fromType instanceof UnknownType || (!(toType instanceof VarcharType) && !(toType instanceof CharType))) {
        return new Cast(expression, toSqlType(toType));
    }
    int targetLength;
    if (toType instanceof VarcharType) {
        if (((VarcharType) toType).isUnbounded()) {
            return new Cast(expression, toSqlType(toType));
        }
        targetLength = ((VarcharType) toType).getBoundedLength();
    }
    else {
        targetLength = ((CharType) toType).getLength();
    }

    checkState(fromType instanceof VarcharType || fromType instanceof CharType, "inserting non-character value to column of character type");
    ResolvedFunction spaceTrimmedLength = metadata.resolveFunction(QualifiedName.of("$space_trimmed_length"), fromTypes(VARCHAR));
    ResolvedFunction fail = metadata.resolveFunction(QualifiedName.of("fail"), fromTypes(VARCHAR));

    return new IfExpression(
            // check if the trimmed value fits in the target type
            new ComparisonExpression(
                    GREATER_THAN_OR_EQUAL,
                    new GenericLiteral("BIGINT", Integer.toString(targetLength)),
                    new CoalesceExpression(
                            new FunctionCall(
                                    spaceTrimmedLength.toQualifiedName(),
                                    ImmutableList.of(new Cast(expression, toSqlType(VARCHAR)))),
                            new GenericLiteral("BIGINT", "0"))),
            new Cast(expression, toSqlType(toType)),
            new Cast(
                    new FunctionCall(
                            fail.toQualifiedName(),
                            ImmutableList.of(new Cast(new StringLiteral("Cannot truncate non-space characters on INSERT"), toSqlType(VARCHAR)))),
                    toSqlType(toType)));
}