Java Code Examples for io.prestosql.spi.type.Type#getJavaType()

The following examples show how to use io.prestosql.spi.type.Type#getJavaType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LiteralFunction.java    From presto with 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 2
Source File: TestScalarFunctionAdapter.java    From presto with Apache License 2.0 6 votes vote down vote up
private static Object getTestValue(Type argumentType)
{
    if (argumentType.getJavaType() == boolean.class) {
        return true;
    }
    if (argumentType.getJavaType() == double.class) {
        return 33.33;
    }
    if (argumentType.getJavaType() == long.class) {
        return 42L;
    }
    if (argumentType.getJavaType() == Slice.class) {
        return Slices.utf8Slice("test");
    }
    if (argumentType.getJavaType() == Block.class) {
        BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, 4);
        blockBuilder.appendNull();
        blockBuilder.writeLong(99);
        blockBuilder.appendNull();
        blockBuilder.writeLong(100);
        return blockBuilder.build();
    }
    throw new IllegalArgumentException("Unsupported argument type: " + argumentType);
}
 
Example 3
Source File: ValueBuffer.java    From presto with Apache License 2.0 6 votes vote down vote up
private static Object normalizeValue(Type type, @Nullable Object value)
{
    if (value == null) {
        return value;
    }

    Class<?> javaType = type.getJavaType();
    if (javaType.isPrimitive()) {
        checkArgument(Primitives.wrap(javaType).isInstance(value), "Type %s incompatible with %s", type, value);
        return value;
    }
    if (javaType == Slice.class) {
        if (value instanceof Slice) {
            return value;
        }
        if (value instanceof String) {
            return utf8Slice(((String) value));
        }
        if (value instanceof byte[]) {
            return wrappedBuffer((byte[]) value);
        }
    }
    throw new IllegalArgumentException(format("Type %s incompatible with %s", type, value));
}
 
Example 4
Source File: FastutilSetHelper.java    From presto with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Set<?> toFastutilHashSet(Set<?> set, Type type, Metadata metadata)
{
    // 0.25 as the load factor is chosen because the argument set is assumed to be small (<10000),
    // and the return set is assumed to be read-heavy.
    // The performance of InCodeGenerator heavily depends on the load factor being small.
    Class<?> javaElementType = type.getJavaType();
    if (javaElementType == long.class) {
        return new LongOpenCustomHashSet((Collection<Long>) set, 0.25f, new LongStrategy(metadata, type));
    }
    if (javaElementType == double.class) {
        return new DoubleOpenCustomHashSet((Collection<Double>) set, 0.25f, new DoubleStrategy(metadata, type));
    }
    if (javaElementType == boolean.class) {
        return new BooleanOpenHashSet((Collection<Boolean>) set, 0.25f);
    }
    else if (!type.getJavaType().isPrimitive()) {
        return new ObjectOpenCustomHashSet<>(set, 0.25f, new ObjectStrategy(metadata, type));
    }
    else {
        throw new UnsupportedOperationException("Unsupported native type in set: " + type.getJavaType() + " with type " + type.getTypeSignature());
    }
}
 
Example 5
Source File: PrometheusRecordCursor.java    From presto with Apache License 2.0 6 votes vote down vote up
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 instanceof VarcharType) ? slice.toStringUtf8() : slice.getBytes();
        }

        return TypeUtils.readNativeValue(type, block, position);
    }
}
 
Example 6
Source File: TwoNullableValueStateMapping.java    From presto with Apache License 2.0 5 votes vote down vote up
public static AccumulatorStateSerializer<?> getStateSerializer(Type firstType, Type secondType)
{
    Class<?> firstJavaType = firstType.getJavaType();

    if (firstJavaType == boolean.class) {
        return new BooleanAndBlockPositionStateSerializer(firstType, secondType);
    }
    if (firstJavaType == long.class) {
        return new LongAndBlockPositionStateSerializer(firstType, secondType);
    }
    if (firstJavaType == double.class) {
        return new DoubleAndBlockPositionStateSerializer(firstType, secondType);
    }
    return new ObjectAndBlockPositionStateSerializer(firstType, secondType);
}
 
Example 7
Source File: LiteralFunction.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type parameterType = boundVariables.getTypeVariable("F");
    Type type = boundVariables.getTypeVariable("T");

    MethodHandle methodHandle = null;
    if (parameterType.getJavaType() == type.getJavaType()) {
        methodHandle = MethodHandles.identity(parameterType.getJavaType());
    }

    if (parameterType.getJavaType() == Slice.class) {
        if (type.getJavaType() == Block.class) {
            methodHandle = READ_BLOCK.bindTo(metadata.getBlockEncodingSerde());
        }
        else if (type.getJavaType() != Slice.class) {
            methodHandle = READ_BLOCK_VALUE.bindTo(metadata.getBlockEncodingSerde()).bindTo(type);
        }
    }

    checkArgument(methodHandle != null,
            "Expected type %s to use (or can be converted into) Java type %s, but Java type is %s",
            type,
            parameterType.getJavaType(),
            type.getJavaType());

    return new ScalarFunctionImplementation(
            false,
            ImmutableList.of(valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
            methodHandle);
}
 
Example 8
Source File: BytecodeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static BytecodeNode generateWrite(CallSiteBinder callSiteBinder, Scope scope, Variable wasNullVariable, Type type)
{
    Class<?> valueJavaType = type.getJavaType();
    if (!valueJavaType.isPrimitive() && valueJavaType != Slice.class) {
        valueJavaType = Object.class;
    }
    String methodName = "write" + Primitives.wrap(valueJavaType).getSimpleName();

    // the stack contains [output, value]

    // We should be able to insert the code to get the output variable and compute the value
    // at the right place instead of assuming they are in the stack. We should also not need to
    // use temp variables to re-shuffle the stack to the right shape before Type.writeXXX is called
    // Unfortunately, because of the assumptions made by try_cast, we can't get around it yet.
    // TODO: clean up once try_cast is fixed
    Variable tempValue = scope.createTempVariable(valueJavaType);
    Variable tempOutput = scope.createTempVariable(BlockBuilder.class);
    return new BytecodeBlock()
            .comment("if (wasNull)")
            .append(new IfStatement()
                    .condition(wasNullVariable)
                    .ifTrue(new BytecodeBlock()
                            .comment("output.appendNull();")
                            .pop(valueJavaType)
                            .invokeInterface(BlockBuilder.class, "appendNull", BlockBuilder.class)
                            .pop())
                    .ifFalse(new BytecodeBlock()
                            .comment("%s.%s(output, %s)", type.getTypeSignature(), methodName, valueJavaType.getSimpleName())
                            .putVariable(tempValue)
                            .putVariable(tempOutput)
                            .append(loadConstant(callSiteBinder.bind(type, Type.class)))
                            .getVariable(tempOutput)
                            .getVariable(tempValue)
                            .invokeInterface(Type.class, methodName, void.class, BlockBuilder.class, valueJavaType)));
}
 
Example 9
Source File: StdUdfWrapper.java    From transport with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Class getJavaTypeForNullability(Type prestoType, boolean nullableArgument) {
  if (nullableArgument) {
    return ClassUtils.primitiveToWrapper(prestoType.getJavaType());
  } else {
    return prestoType.getJavaType();
  }
}
 
Example 10
Source File: JSONSchemaHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public Object extractField(int index, Object currentRecord) {
    try {
        Map jsonObject = (Map) currentRecord;
        PulsarColumnHandle pulsarColumnHandle = columnHandles.get(index);

        String[] fieldNames = pulsarColumnHandle.getFieldNames();
        Object field = jsonObject.get(fieldNames[0]);
        if (field == null) {
            return null;
        }
        for (int i = 1; i < fieldNames.length; i++) {
            field = ((Map) field).get(fieldNames[i]);
            if (field == null) {
                return null;
            }
        }

        Type type = pulsarColumnHandle.getType();

        Class<?> javaType = type.getJavaType();

        if (javaType == double.class) {
            return ((BigDecimal) field).doubleValue();
        }

        return field;
    } catch (Exception ex) {
        log.debug(ex, "%s", ex);
    }
    return null;
}
 
Example 11
Source File: AbstractTestType.java    From presto with Apache License 2.0 5 votes vote down vote up
/**
 * @return a non-null value, represented in native container type
 */
private static Object getNonNullValueForType(Type type)
{
    if (type.getJavaType() == boolean.class) {
        return true;
    }
    if (type.getJavaType() == long.class) {
        return 1L;
    }
    if (type.getJavaType() == double.class) {
        return 1.0;
    }
    if (type.getJavaType() == Slice.class) {
        return Slices.utf8Slice("_");
    }
    if (type instanceof ArrayType) {
        ArrayType arrayType = (ArrayType) type;
        Type elementType = arrayType.getElementType();
        Object elementNonNullValue = getNonNullValueForType(elementType);
        return arrayBlockOf(elementType, elementNonNullValue);
    }
    if (type instanceof MapType) {
        MapType mapType = (MapType) type;
        Type keyType = mapType.getKeyType();
        Type valueType = mapType.getValueType();
        Object keyNonNullValue = getNonNullValueForType(keyType);
        Object valueNonNullValue = getNonNullValueForType(valueType);
        Map<?, ?> map = ImmutableMap.of(keyNonNullValue, valueNonNullValue);
        return mapBlockOf(keyType, valueType, map);
    }
    if (type instanceof RowType) {
        RowType rowType = (RowType) type;
        List<Type> elementTypes = rowType.getTypeParameters();
        Object[] elementNonNullValues = elementTypes.stream().map(AbstractTestType::getNonNullValueForType).toArray(Object[]::new);
        return toRow(elementTypes, elementNonNullValues);
    }
    throw new IllegalStateException("Unsupported Java type " + type.getJavaType() + " (for type " + type + ")");
}
 
Example 12
Source File: TypeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static long hashPosition(MethodHandle methodHandle, Type type, Block block, int position)
{
    if (block.isNull(position)) {
        return NULL_HASH_CODE;
    }
    try {
        if (type.getJavaType() == boolean.class) {
            return (long) methodHandle.invoke(type.getBoolean(block, position));
        }
        if (type.getJavaType() == long.class) {
            return (long) methodHandle.invoke(type.getLong(block, position));
        }
        if (type.getJavaType() == double.class) {
            return (long) methodHandle.invoke(type.getDouble(block, position));
        }
        if (type.getJavaType() == Slice.class) {
            return (long) methodHandle.invoke(type.getSlice(block, position));
        }
        if (!type.getJavaType().isPrimitive()) {
            return (long) methodHandle.invoke(type.getObject(block, position));
        }
        throw new UnsupportedOperationException("Unsupported native container type: " + type.getJavaType() + " with type " + type.getTypeSignature());
    }
    catch (Throwable throwable) {
        throwIfUnchecked(throwable);
        throw new RuntimeException(throwable);
    }
}
 
Example 13
Source File: BigQueryResultPageSource.java    From presto with Apache License 2.0 4 votes vote down vote up
private void appendTo(Type type, Object value, BlockBuilder output)
{
    if (value == null) {
        output.appendNull();
        return;
    }

    Class<?> javaType = type.getJavaType();
    try {
        if (javaType == boolean.class) {
            type.writeBoolean(output, (Boolean) value);
        }
        else if (javaType == long.class) {
            if (type.equals(BIGINT)) {
                type.writeLong(output, ((Number) value).longValue());
            }
            else if (type.equals(INTEGER)) {
                type.writeLong(output, ((Number) value).intValue());
            }
            else if (type.equals(DATE)) {
                type.writeLong(output, ((Number) value).intValue());
            }
            else if (type.equals(TIMESTAMP)) {
                type.writeLong(output, toPrestoTimestamp(((Utf8) value).toString()));
            }
            else if (type.equals(TIME_WITH_TIME_ZONE)) {
                type.writeLong(output, DateTimeEncoding.packDateTimeWithZone(((Long) value).longValue() / 1000, TimeZoneKey.UTC_KEY));
            }
            else if (type.equals(TIMESTAMP_WITH_TIME_ZONE)) {
                type.writeLong(output, DateTimeEncoding.packDateTimeWithZone(((Long) value).longValue() / 1000, TimeZoneKey.UTC_KEY));
            }
            else {
                throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Unhandled type for %s: %s", javaType.getSimpleName(), type));
            }
        }
        else if (javaType == double.class) {
            type.writeDouble(output, ((Number) value).doubleValue());
        }
        else if (javaType == Slice.class) {
            writeSlice(output, type, value);
        }
        else if (javaType == Block.class) {
            writeBlock(output, type, value);
        }
        else {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Unhandled type for %s: %s", javaType.getSimpleName(), type));
        }
    }
    catch (ClassCastException ignore) {
        // returns null instead of raising exception
        output.appendNull();
    }
}
 
Example 14
Source File: MongoPageSource.java    From presto with Apache License 2.0 4 votes vote down vote up
private void appendTo(Type type, Object value, BlockBuilder output)
{
    if (value == null) {
        output.appendNull();
        return;
    }

    Class<?> javaType = type.getJavaType();
    try {
        if (javaType == boolean.class) {
            type.writeBoolean(output, (Boolean) value);
        }
        else if (javaType == long.class) {
            if (type.equals(BIGINT)) {
                type.writeLong(output, ((Number) value).longValue());
            }
            else if (type.equals(INTEGER)) {
                type.writeLong(output, ((Number) value).intValue());
            }
            else if (type.equals(SMALLINT)) {
                type.writeLong(output, Shorts.checkedCast(((Number) value).longValue()));
            }
            else if (type.equals(TINYINT)) {
                type.writeLong(output, SignedBytes.checkedCast(((Number) value).longValue()));
            }
            else if (type.equals(REAL)) {
                //noinspection NumericCastThatLosesPrecision
                type.writeLong(output, floatToIntBits(((float) ((Number) value).doubleValue())));
            }
            else if (type instanceof DecimalType) {
                type.writeLong(output, encodeShortScaledValue(((Decimal128) value).bigDecimalValue(), ((DecimalType) type).getScale()));
            }
            else if (type.equals(DATE)) {
                long utcMillis = ((Date) value).getTime();
                type.writeLong(output, TimeUnit.MILLISECONDS.toDays(utcMillis));
            }
            else if (type.equals(TIME)) {
                type.writeLong(output, UTC_CHRONOLOGY.millisOfDay().get(((Date) value).getTime()));
            }
            else if (type.equals(TIMESTAMP)) {
                // TODO provide correct TIMESTAMP mapping, and respecting session.isLegacyTimestamp()
                type.writeLong(output, ((Date) value).getTime());
            }
            else if (type.equals(TIMESTAMP_WITH_TIME_ZONE)) {
                type.writeLong(output, packDateTimeWithZone(((Date) value).getTime(), UTC_KEY));
            }
            else {
                throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type for " + javaType.getSimpleName() + ":" + type.getTypeSignature());
            }
        }
        else if (javaType == double.class) {
            type.writeDouble(output, ((Number) value).doubleValue());
        }
        else if (javaType == Slice.class) {
            writeSlice(output, type, value);
        }
        else if (javaType == Block.class) {
            writeBlock(output, type, value);
        }
        else {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type for " + javaType.getSimpleName() + ":" + type.getTypeSignature());
        }
    }
    catch (ClassCastException ignore) {
        // TODO remove (fail clearly), or hide behind a toggle
        // returns null instead of raising exception
        output.appendNull();
    }
}
 
Example 15
Source File: HiveCoercionRecordCursor.java    From presto with Apache License 2.0 4 votes vote down vote up
private static void rewriteBlock(
        Type fromType,
        Type toType,
        Block block,
        int position,
        BlockBuilder blockBuilder,
        Coercer coercer,
        BridgingRecordCursor bridgingRecordCursor)
{
    Class<?> fromJavaType = fromType.getJavaType();
    if (fromJavaType == long.class) {
        bridgingRecordCursor.setValue(fromType.getLong(block, position));
    }
    else if (fromJavaType == double.class) {
        bridgingRecordCursor.setValue(fromType.getDouble(block, position));
    }
    else if (fromJavaType == boolean.class) {
        bridgingRecordCursor.setValue(fromType.getBoolean(block, position));
    }
    else if (fromJavaType == Slice.class) {
        bridgingRecordCursor.setValue(fromType.getSlice(block, position));
    }
    else if (fromJavaType == Block.class) {
        bridgingRecordCursor.setValue(fromType.getObject(block, position));
    }
    else {
        bridgingRecordCursor.setValue(null);
    }
    coercer.reset();
    Class<?> toJaveType = toType.getJavaType();
    if (coercer.isNull(bridgingRecordCursor, 0)) {
        blockBuilder.appendNull();
    }
    else if (toJaveType == long.class) {
        toType.writeLong(blockBuilder, coercer.getLong(bridgingRecordCursor, 0));
    }
    else if (toJaveType == double.class) {
        toType.writeDouble(blockBuilder, coercer.getDouble(bridgingRecordCursor, 0));
    }
    else if (toJaveType == boolean.class) {
        toType.writeBoolean(blockBuilder, coercer.getBoolean(bridgingRecordCursor, 0));
    }
    else if (toJaveType == Slice.class) {
        toType.writeSlice(blockBuilder, coercer.getSlice(bridgingRecordCursor, 0));
    }
    else if (toJaveType == Block.class) {
        toType.writeObject(blockBuilder, coercer.getObject(bridgingRecordCursor, 0));
    }
    else {
        throw new PrestoException(NOT_SUPPORTED, format("Unsupported coercion from %s to %s", fromType.getDisplayName(), toType.getDisplayName()));
    }
    coercer.reset();
    bridgingRecordCursor.close();
}
 
Example 16
Source File: LazyRecordPageSource.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public Page getNextPage()
{
    if (!closed) {
        for (int i = 0; i < ROWS_PER_REQUEST && !pageBuilder.isFull() && pageBuilder.getPositionCount() < maxRowsPerPage; i++) {
            if (!cursor.advanceNextPosition()) {
                closed = true;
                break;
            }

            pageBuilder.declarePosition();
            for (int column = 0; column < types.size(); column++) {
                BlockBuilder output = pageBuilder.getBlockBuilder(column);
                if (cursor.isNull(column)) {
                    output.appendNull();
                }
                else {
                    Type type = types.get(column);
                    Class<?> javaType = type.getJavaType();
                    if (javaType == boolean.class) {
                        type.writeBoolean(output, cursor.getBoolean(column));
                    }
                    else if (javaType == long.class) {
                        type.writeLong(output, cursor.getLong(column));
                    }
                    else if (javaType == double.class) {
                        type.writeDouble(output, cursor.getDouble(column));
                    }
                    else if (javaType == Slice.class) {
                        Slice slice = cursor.getSlice(column);
                        type.writeSlice(output, slice, 0, slice.length());
                    }
                    else {
                        type.writeObject(output, cursor.getObject(column));
                    }
                }
            }
        }
    }

    if ((closed && !pageBuilder.isEmpty()) || pageBuilder.isFull() || pageBuilder.getPositionCount() >= maxRowsPerPage) {
        Page page = pageBuilder.build();
        pageBuilder.reset();
        return lazyWrapper(page);
    }

    return null;
}
 
Example 17
Source File: TupleDomainOrcPredicate.java    From presto with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics)
{
    if (rowCount == 0) {
        return Domain.none(type);
    }

    if (columnStatistics == null) {
        return Domain.all(type);
    }

    if (columnStatistics.hasNumberOfValues() && columnStatistics.getNumberOfValues() == 0) {
        return Domain.onlyNull(type);
    }

    boolean hasNullValue = columnStatistics.getNumberOfValues() != rowCount;

    if (type.getJavaType() == boolean.class && columnStatistics.getBooleanStatistics() != null) {
        BooleanStatistics booleanStatistics = columnStatistics.getBooleanStatistics();

        boolean hasTrueValues = (booleanStatistics.getTrueValueCount() != 0);
        boolean hasFalseValues = (columnStatistics.getNumberOfValues() != booleanStatistics.getTrueValueCount());
        if (hasTrueValues && hasFalseValues) {
            return Domain.all(BOOLEAN);
        }
        if (hasTrueValues) {
            return Domain.create(ValueSet.of(BOOLEAN, true), hasNullValue);
        }
        if (hasFalseValues) {
            return Domain.create(ValueSet.of(BOOLEAN, false), hasNullValue);
        }
    }
    else if (isShortDecimal(type) && columnStatistics.getDecimalStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getDecimalStatistics(), value -> rescale(value, (DecimalType) type).unscaledValue().longValue());
    }
    else if (isLongDecimal(type) && columnStatistics.getDecimalStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getDecimalStatistics(), value -> encodeUnscaledValue(rescale(value, (DecimalType) type).unscaledValue()));
    }
    else if (isCharType(type) && columnStatistics.getStringStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getStringStatistics(), value -> truncateToLengthAndTrimSpaces(value, type));
    }
    else if (isVarcharType(type) && columnStatistics.getStringStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getStringStatistics());
    }
    else if (type instanceof DateType && columnStatistics.getDateStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getDateStatistics(), value -> (long) value);
    }
    else if (type.getJavaType() == long.class && columnStatistics.getIntegerStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getIntegerStatistics());
    }
    else if (type.getJavaType() == double.class && columnStatistics.getDoubleStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getDoubleStatistics());
    }
    else if (REAL.equals(type) && columnStatistics.getDoubleStatistics() != null) {
        return createDomain(type, hasNullValue, columnStatistics.getDoubleStatistics(), value -> (long) floatToRawIntBits(value.floatValue()));
    }
    return Domain.create(ValueSet.all(type), hasNullValue);
}
 
Example 18
Source File: Row.java    From presto with Apache License 2.0 4 votes vote down vote up
private static Object nativeContainerToOrcValue(Type type, Object nativeValue)
{
    if (nativeValue == null) {
        return null;
    }
    if (type instanceof DecimalType) {
        BigInteger unscaledValue;
        DecimalType decimalType = (DecimalType) type;
        if (decimalType.isShort()) {
            unscaledValue = BigInteger.valueOf((long) nativeValue);
        }
        else {
            unscaledValue = Decimals.decodeUnscaledValue((Slice) nativeValue);
        }
        return HiveDecimal.create(unscaledValue, decimalType.getScale());
    }
    if (type.getJavaType() == boolean.class) {
        return nativeValue;
    }
    if (type.getJavaType() == long.class) {
        return nativeValue;
    }
    if (type.getJavaType() == double.class) {
        return nativeValue;
    }
    if (type.getJavaType() == Slice.class) {
        Slice slice = (Slice) nativeValue;
        return type instanceof VarcharType ? slice.toStringUtf8() : slice.getBytes();
    }
    if (isArrayType(type)) {
        Block arrayBlock = (Block) nativeValue;
        Type elementType = type.getTypeParameters().get(0);
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < arrayBlock.getPositionCount(); i++) {
            list.add(nativeContainerToOrcValue(elementType, getNativeContainerValue(elementType, arrayBlock, i)));
        }
        return list;
    }
    if (isMapType(type)) {
        Block mapBlock = (Block) nativeValue;
        Type keyType = type.getTypeParameters().get(0);
        Type valueType = type.getTypeParameters().get(1);
        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < mapBlock.getPositionCount(); i += 2) {
            Object key = nativeContainerToOrcValue(keyType, getNativeContainerValue(keyType, mapBlock, i));
            Object value = nativeContainerToOrcValue(valueType, getNativeContainerValue(valueType, mapBlock, i + 1));
            map.put(key, value);
        }
        return map;
    }
    throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unimplemented type: " + type);
}
 
Example 19
Source File: ArrayJoin.java    From presto with Apache License 2.0 4 votes vote down vote up
private static ScalarFunctionImplementation specializeArrayJoin(BoundVariables types, Metadata metadata, List<Boolean> nullableArguments, MethodHandle methodHandle)
{
    Type type = types.getTypeVariable("T");
    List<ArgumentProperty> argumentProperties = nullableArguments.stream()
            .map(nullable -> nullable
                    ? valueTypeArgumentProperty(USE_BOXED_TYPE)
                    : valueTypeArgumentProperty(RETURN_NULL_ON_NULL))
            .collect(toImmutableList());

    if (type instanceof UnknownType) {
        return new ScalarFunctionImplementation(
                false,
                argumentProperties,
                methodHandle.bindTo(null),
                Optional.of(STATE_FACTORY));
    }
    else {
        try {
            ResolvedFunction resolvedFunction = metadata.getCoercion(type, VARCHAR);
            MethodHandle cast = metadata.getScalarFunctionInvoker(resolvedFunction, Optional.empty()).getMethodHandle();

            MethodHandle getter;
            Class<?> elementType = type.getJavaType();
            if (elementType == boolean.class) {
                getter = GET_BOOLEAN;
            }
            else if (elementType == double.class) {
                getter = GET_DOUBLE;
            }
            else if (elementType == long.class) {
                getter = GET_LONG;
            }
            else if (elementType == Slice.class) {
                getter = GET_SLICE;
            }
            else {
                throw new UnsupportedOperationException("Unsupported type: " + elementType.getName());
            }

            // if the cast doesn't take a ConnectorSession, create an adapter that drops the provided session
            if (cast.type().parameterArray()[0] != ConnectorSession.class) {
                cast = MethodHandles.dropArguments(cast, 0, ConnectorSession.class);
            }

            // Adapt a target cast that takes (ConnectorSession, ?) to one that takes (Block, int, ConnectorSession), which will be invoked by the implementation
            // The first two arguments (Block, int) are filtered through the element type's getXXX method to produce the underlying value that needs to be passed to
            // the cast.
            cast = MethodHandles.permuteArguments(cast, MethodType.methodType(Slice.class, cast.type().parameterArray()[1], cast.type().parameterArray()[0]), 1, 0);
            cast = MethodHandles.dropArguments(cast, 1, int.class);
            cast = MethodHandles.dropArguments(cast, 1, Block.class);
            cast = MethodHandles.foldArguments(cast, getter.bindTo(type));

            MethodHandle target = MethodHandles.insertArguments(methodHandle, 0, cast);
            return new ScalarFunctionImplementation(
                    false,
                    argumentProperties,
                    target,
                    Optional.of(STATE_FACTORY));
        }
        catch (PrestoException e) {
            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Input type %s not supported", type), e);
        }
    }
}
 
Example 20
Source File: BlackHolePageSourceProvider.java    From presto with Apache License 2.0 4 votes vote down vote up
private Block createZeroBlock(Type type, int rowsCount, Slice constantSlice)
{
    checkArgument(isSupportedType(type), "Unsupported type [%s]", type);

    Slice slice;
    // do not exceed varchar limit
    if (isVarcharType(type) && !((VarcharType) type).isUnbounded()) {
        slice = constantSlice.slice(0, Math.min(((VarcharType) type).getBoundedLength(), constantSlice.length()));
    }
    else if (isLongDecimal(type)) {
        slice = encodeScaledValue(ZERO);
    }
    else {
        slice = constantSlice;
    }

    BlockBuilder builder;
    if (type instanceof FixedWidthType) {
        builder = type.createBlockBuilder(null, rowsCount);
    }
    else {
        builder = type.createBlockBuilder(null, rowsCount, slice.length());
    }

    for (int i = 0; i < rowsCount; i++) {
        Class<?> javaType = type.getJavaType();
        if (javaType == boolean.class) {
            type.writeBoolean(builder, false);
        }
        else if (javaType == long.class) {
            type.writeLong(builder, 0);
        }
        else if (javaType == double.class) {
            type.writeDouble(builder, 0.0);
        }
        else if (javaType == Slice.class) {
            requireNonNull(slice, "slice is null");
            type.writeSlice(builder, slice, 0, slice.length());
        }
        else {
            throw new UnsupportedOperationException("Unknown javaType: " + javaType.getName());
        }
    }
    return builder.build();
}