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

The following examples show how to use io.prestosql.spi.type.Type. 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: MongoPageSource.java    License: Apache License 2.0 6 votes vote down vote up
private void writeSlice(BlockBuilder output, Type type, Object value)
{
    if (type instanceof VarcharType) {
        type.writeSlice(output, utf8Slice(toVarcharValue(value)));
    }
    else if (type instanceof CharType) {
        type.writeSlice(output, truncateToLengthAndTrimSpaces(utf8Slice((String) value), ((CharType) type)));
    }
    else if (type.equals(OBJECT_ID)) {
        type.writeSlice(output, wrappedBuffer(((ObjectId) value).toByteArray()));
    }
    else if (type instanceof VarbinaryType) {
        if (value instanceof Binary) {
            type.writeSlice(output, wrappedBuffer(((Binary) value).getData()));
        }
        else {
            output.appendNull();
        }
    }
    else if (type instanceof DecimalType) {
        type.writeSlice(output, encodeScaledValue(((Decimal128) value).bigDecimalValue(), ((DecimalType) type).getScale()));
    }
    else {
        throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type for Slice: " + type.getTypeSignature());
    }
}
 
Example 2
Source Project: presto   Source File: StatementAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasNestedBoundedCharacterType(Type type)
{
    if (type instanceof ArrayType) {
        return hasBoundedCharacterType(((ArrayType) type).getElementType());
    }

    if (type instanceof MapType) {
        return hasBoundedCharacterType(((MapType) type).getKeyType()) || hasBoundedCharacterType(((MapType) type).getValueType());
    }

    if (type instanceof RowType) {
        for (Type fieldType : type.getTypeParameters()) {
            if (hasBoundedCharacterType(fieldType)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 3
Source Project: presto   Source File: ArraysOverlapFunction.java    License: Apache License 2.0 6 votes vote down vote up
private static IntComparator intBlockCompare(Type type, Block block)
{
    return new AbstractIntComparator()
    {
        @Override
        public int compare(int left, int right)
        {
            if (block.isNull(left) && block.isNull(right)) {
                return 0;
            }
            if (block.isNull(left)) {
                return 1;
            }
            if (block.isNull(right)) {
                return -1;
            }
            return type.compareTo(block, left, block, right);
        }
    };
}
 
Example 4
Source Project: presto   Source File: PreparedStatementBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public static PreparedStatement create(
        Connection connection,
        String sql,
        List<String> columnNames,
        List<Type> types,
        Set<Integer> uuidColumnIndexes,
        TupleDomain<Integer> tupleDomain)
        throws SQLException
{
    checkArgument(!isNullOrEmpty(sql), "sql is null or empty");

    List<ValueBuffer> bindValues = new ArrayList<>(256);
    sql += getWhereClause(tupleDomain, columnNames, types, uuidColumnIndexes, bindValues);

    PreparedStatement statement = connection.prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
    enableStreamingResults(statement);

    // bind values to statement
    int bindIndex = 1;
    for (ValueBuffer value : bindValues) {
        bindField(value, statement, bindIndex, uuidColumnIndexes.contains(value.getColumnIndex()));
        bindIndex++;
    }
    return statement;
}
 
Example 5
private List<RowExpression> getProjections(Type type)
{
    ImmutableList.Builder<RowExpression> builder = ImmutableList.builder();
    if (type == BIGINT) {
        for (int i = 0; i < columnCount; i++) {
            builder.add(rowExpression("bigint" + i + " + 5"));
        }
    }
    else if (type == VARCHAR) {
        for (int i = 0; i < columnCount; i++) {
            // alternatively use identity expression rowExpression("varchar" + i, type) or
            // rowExpression("substr(varchar" + i + ", 1, 1)", type)
            builder.add(rowExpression("concat(varchar" + i + ", 'foo')"));
        }
    }
    return builder.build();
}
 
Example 6
Source Project: presto   Source File: QueryStateMachine.java    License: Apache License 2.0 6 votes vote down vote up
public void setColumns(List<String> columnNames, List<Type> columnTypes)
{
    requireNonNull(columnNames, "columnNames is null");
    requireNonNull(columnTypes, "columnTypes is null");
    checkArgument(columnNames.size() == columnTypes.size(), "columnNames and columnTypes must be the same size");

    Optional<QueryOutputInfo> queryOutputInfo;
    List<Consumer<QueryOutputInfo>> outputInfoListeners;
    synchronized (this) {
        checkState(this.columnNames == null && this.columnTypes == null, "output fields already set");
        this.columnNames = ImmutableList.copyOf(columnNames);
        this.columnTypes = ImmutableList.copyOf(columnTypes);

        queryOutputInfo = getQueryOutputInfo();
        outputInfoListeners = ImmutableList.copyOf(this.outputInfoListeners);
    }
    queryOutputInfo.ifPresent(info -> fireStateChanged(info, outputInfoListeners));
}
 
Example 7
Source Project: presto   Source File: PlanBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public PlanNode spatialJoin(
        SpatialJoinNode.Type type,
        PlanNode left,
        PlanNode right,
        List<Symbol> outputSymbols,
        Expression filter,
        Optional<Symbol> leftPartitionSymbol,
        Optional<Symbol> rightPartitionSymbol,
        Optional<String> kdbTree)
{
    return new SpatialJoinNode(
            idAllocator.getNextId(),
            type,
            left,
            right,
            outputSymbols,
            filter,
            leftPartitionSymbol,
            rightPartitionSymbol,
            kdbTree);
}
 
Example 8
Source Project: presto   Source File: AggregateFunction.java    License: Apache License 2.0 6 votes vote down vote up
public AggregateFunction(
        String aggregateFunctionName,
        Type outputType,
        List<ConnectorExpression> inputs,
        List<SortItem> sortItems,
        boolean isDistinct,
        Optional<ConnectorExpression> filter)
{
    if (isDistinct && inputs.isEmpty()) {
        throw new IllegalArgumentException("DISTINCT requires inputs");
    }

    this.functionName = requireNonNull(aggregateFunctionName, "name is null");
    this.outputType = requireNonNull(outputType, "outputType is null");
    requireNonNull(inputs, "inputs is null");
    requireNonNull(sortItems, "sortOrder is null");
    this.inputs = List.copyOf(inputs);
    this.sortItems = List.copyOf(sortItems);
    this.isDistinct = isDistinct;
    this.filter = requireNonNull(filter, "filter is null");
}
 
Example 9
Source Project: presto   Source File: TestCanonicalizeExpressionRewriter.java    License: Apache License 2.0 6 votes vote down vote up
private static void assertRewritten(String from, String to)
{
    assertExpressionEquals(
            rewrite(
                    PlanBuilder.expression(from),
                    TEST_SESSION,
                    METADATA,
                    TYPE_ANALYZER,
                    TypeProvider.copyOf(ImmutableMap.<Symbol, Type>builder()
                            .put(new Symbol("x"), BIGINT)
                            .put(new Symbol("a"), BIGINT)
                            .build())),
            PlanBuilder.expression(to),
            SymbolAliases.builder()
                    .put("x", new SymbolReference("x"))
                    .put("a", new SymbolReference("a"))
                    .build());
}
 
Example 10
Source Project: presto   Source File: DynamicFilterSourceOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void finish()
{
    if (finished) {
        // NOTE: finish() may be called multiple times (see comment at Driver::processInternal).
        return;
    }
    finished = true;
    if (valueSets == null) {
        return; // the predicate became too large.
    }

    ImmutableMap.Builder<DynamicFilterId, Domain> domainsBuilder = new ImmutableMap.Builder<>();
    for (int channelIndex = 0; channelIndex < channels.size(); ++channelIndex) {
        Block block = blockBuilders[channelIndex].build();
        Type type = channels.get(channelIndex).type;
        domainsBuilder.put(channels.get(channelIndex).filterId, convertToDomain(type, block));
    }
    valueSets = null;
    blockBuilders = null;
    dynamicPredicateConsumer.accept(TupleDomain.withColumnDomains(domainsBuilder.build()));
}
 
Example 11
Source Project: presto   Source File: TestDriver.java    License: Apache License 2.0 6 votes vote down vote up
@Test(invocationCount = 1_000, timeOut = 10_000)
public void testConcurrentClose()
{
    List<Type> types = ImmutableList.of(VARCHAR, BIGINT, BIGINT);
    OperatorContext operatorContext = driverContext.addOperatorContext(0, new PlanNodeId("test"), "values");
    ValuesOperator source = new ValuesOperator(operatorContext, rowPagesBuilder(types)
            .addSequencePage(10, 20, 30, 40)
            .build());

    Operator sink = createSinkOperator(types);
    Driver driver = Driver.createDriver(driverContext, source, sink);
    // let these threads race
    scheduledExecutor.submit(() -> driver.processFor(new Duration(1, TimeUnit.NANOSECONDS))); // don't want to call isFinishedInternal in processFor
    scheduledExecutor.submit(() -> driver.close());
    while (!driverContext.isDone()) {
        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS);
    }
}
 
Example 12
Source Project: presto   Source File: PrestoThriftPageResult.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public Page toPage(List<Type> columnTypes)
{
    if (rowCount == 0) {
        return null;
    }
    checkArgument(columnBlocks.size() == columnTypes.size(), "columns and types have different sizes");
    int numberOfColumns = columnBlocks.size();
    if (numberOfColumns == 0) {
        // request/response with no columns, used for queries like "select count star"
        return new Page(rowCount);
    }
    Block[] blocks = new Block[numberOfColumns];
    for (int i = 0; i < numberOfColumns; i++) {
        blocks[i] = columnBlocks.get(i).toBlock(columnTypes.get(i));
    }
    return new Page(blocks);
}
 
Example 13
Source Project: presto   Source File: TestHiveTypeTranslator.java    License: Apache License 2.0 6 votes vote down vote up
protected TestHiveTypeTranslator(TypeTranslator typeTranslator, Map<Type, HiveType> overwriteTranslation)
{
    this.typeTranslator = requireNonNull(typeTranslator, "typeTranslator is null");

    ImmutableMap<Type, HiveType> hiveTypeTranslationMap = ImmutableMap.<Type, HiveType>builder()
            .put(BIGINT, HiveType.HIVE_LONG)
            .put(INTEGER, HiveType.HIVE_INT)
            .put(SMALLINT, HiveType.HIVE_SHORT)
            .put(TINYINT, HiveType.HIVE_BYTE)
            .put(DOUBLE, HiveType.HIVE_DOUBLE)
            .put(createVarcharType(3), HiveType.valueOf("varchar(3)"))
            .put(VARCHAR, HiveType.HIVE_STRING)
            .put(DATE, HiveType.HIVE_DATE)
            .put(TIMESTAMP, HiveType.HIVE_TIMESTAMP)
            .put(createDecimalType(5, 3), HiveType.valueOf("decimal(5,3)"))
            .put(VARBINARY, HiveType.HIVE_BINARY)
            .put(new ArrayType(TIMESTAMP), HiveType.valueOf("array<timestamp>"))
            .put(TYPE_MANAGER.getType(mapType(BOOLEAN.getTypeSignature(), VARBINARY.getTypeSignature())), HiveType.valueOf("map<boolean,binary>"))
            .put(RowType.from(ImmutableList.of(field("col0", INTEGER), field("col1", VARBINARY))),
                    HiveType.valueOf("struct<col0:int,col1:binary>"))
            .build();

    typeTranslationMap = new HashMap<>();
    typeTranslationMap.putAll(hiveTypeTranslationMap);
    typeTranslationMap.putAll(overwriteTranslation);
}
 
Example 14
Source Project: presto   Source File: StreamingAggregationOperator.java    License: Apache License 2.0 6 votes vote down vote up
public static OperatorFactory createOperatorFactory(
        int operatorId,
        PlanNodeId planNodeId,
        List<Type> sourceTypes,
        List<Type> groupByTypes,
        List<Integer> groupByChannels,
        Step step,
        List<AccumulatorFactory> accumulatorFactories,
        JoinCompiler joinCompiler)
{
    return createAdapterOperatorFactory(new Factory(
            operatorId,
            planNodeId,
            sourceTypes,
            groupByTypes,
            groupByChannels,
            step,
            accumulatorFactories,
            joinCompiler));
}
 
Example 15
Source Project: presto   Source File: TypedSet.java    License: Apache License 2.0 6 votes vote down vote up
public TypedSet(Type elementType, Optional<MethodHandle> elementIsDistinctFrom, BlockBuilder blockBuilder, int expectedSize, String functionName, Optional<DataSize> maxBlockMemory)
{
    checkArgument(expectedSize >= 0, "expectedSize must not be negative");
    this.elementType = requireNonNull(elementType, "elementType must not be null");
    this.elementIsDistinctFrom = requireNonNull(elementIsDistinctFrom, "elementIsDistinctFrom is null");
    elementIsDistinctFrom.ifPresent(methodHandle -> checkArgument(methodHandle.type().equals(MethodType.methodType(boolean.class, Block.class, int.class, Block.class, int.class))));
    this.elementBlock = requireNonNull(blockBuilder, "blockBuilder must not be null");
    this.functionName = functionName;
    this.maxBlockMemoryInBytes = maxBlockMemory.map(value -> value.toBytes()).orElse(Long.MAX_VALUE);

    initialElementBlockOffset = elementBlock.getPositionCount();
    initialElementBlockSizeInBytes = elementBlock.getSizeInBytes();

    this.size = 0;
    this.hashCapacity = arraySize(expectedSize, FILL_RATIO);
    this.maxFill = calculateMaxFill(hashCapacity);
    this.hashMask = hashCapacity - 1;

    blockPositionByHash = new IntArrayList(hashCapacity);
    blockPositionByHash.size(hashCapacity);
    for (int i = 0; i < hashCapacity; i++) {
        blockPositionByHash.set(i, EMPTY_SLOT);
    }

    this.containsNullElement = false;
}
 
Example 16
Source Project: presto   Source File: TestPagesSerde.java    License: Apache License 2.0 6 votes vote down vote up
private static int serializedSize(List<? extends Type> types, Page expectedPage)
{
    PagesSerde serde = new TestingPagesSerdeFactory().createPagesSerde();
    DynamicSliceOutput sliceOutput = new DynamicSliceOutput(1024);
    writePages(serde, sliceOutput, expectedPage);
    Slice slice = sliceOutput.slice();

    Iterator<Page> pageIterator = readPages(serde, slice.getInput());
    if (pageIterator.hasNext()) {
        assertPageEquals(types, pageIterator.next(), expectedPage);
    }
    else {
        assertEquals(expectedPage.getPositionCount(), 0);
    }
    assertFalse(pageIterator.hasNext());

    return slice.length();
}
 
Example 17
Source Project: presto   Source File: BindCodeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BytecodeNode generateExpression(ResolvedFunction resolvedFunction, BytecodeGeneratorContext context, Type returnType, List<RowExpression> arguments)
{
    // Bind expression is used to generate captured lambda.
    // It takes the captured values and the uncaptured lambda, and produces captured lambda as the output.
    // The uncaptured lambda is just a method, and does not have a stack representation during execution.
    // As a result, the bind expression generates the captured lambda in one step.
    int numCaptures = arguments.size() - 1;
    LambdaDefinitionExpression lambda = (LambdaDefinitionExpression) arguments.get(numCaptures);
    checkState(compiledLambdaMap.containsKey(lambda), "lambda expressions map does not contain this lambda definition");
    CompiledLambda compiledLambda = compiledLambdaMap.get(lambda);

    return LambdaBytecodeGenerator.generateLambda(
            context,
            arguments.subList(0, numCaptures),
            compiledLambda,
            lambdaInterface);
}
 
Example 18
Source Project: presto   Source File: RcFileWriter.java    License: Apache License 2.0 6 votes vote down vote up
public RcFileWriter(
        SliceOutput output,
        List<Type> types,
        RcFileEncoding encoding,
        Optional<String> codecName,
        RcFileCodecFactory codecFactory,
        Map<String, String> metadata,
        boolean validate)
        throws IOException
{
    this(
            output,
            types,
            encoding,
            codecName,
            codecFactory,
            metadata,
            DEFAULT_TARGET_MIN_ROW_GROUP_SIZE,
            DEFAULT_TARGET_MAX_ROW_GROUP_SIZE,
            validate);
}
 
Example 19
Source Project: presto   Source File: StateCompiler.java    License: Apache License 2.0 6 votes vote down vote up
private StateField(String name, Class<?> type, Object initialValue, String getterName, Optional<Type> sqlType)
{
    this.name = requireNonNull(name, "name is null");
    checkArgument(!name.isEmpty(), "name is empty");
    this.type = requireNonNull(type, "type is null");
    this.getterName = requireNonNull(getterName, "getterName is null");
    this.initialValue = initialValue;
    checkArgument(sqlType != null, "sqlType is null");
    if (sqlType.isPresent()) {
        checkArgument(
                type.isAssignableFrom(sqlType.get().getJavaType()) ||
                        ((type == byte.class) && TINYINT.equals(sqlType.get())) ||
                        ((type == int.class) && INTEGER.equals(sqlType.get())),
                "Stack type (%s) and provided sql type (%s) are incompatible", type.getName(), sqlType.get().getDisplayName());
    }
    else {
        sqlType = sqlTypeFromStackType(type);
    }
    this.sqlType = sqlType;
}
 
Example 20
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 21
Source Project: presto   Source File: OrcTester.java    License: Apache License 2.0 6 votes vote down vote up
private void testRoundTripType(Type type, List<?> readValues)
        throws Exception
{
    // forward order
    assertRoundTrip(type, readValues);

    // reverse order
    if (reverseTestsEnabled) {
        assertRoundTrip(type, reverse(readValues));
    }

    if (nullTestsEnabled) {
        // forward order with nulls
        assertRoundTrip(type, insertNullEvery(5, readValues));

        // reverse order with nulls
        if (reverseTestsEnabled) {
            assertRoundTrip(type, insertNullEvery(5, reverse(readValues)));
        }
    }
}
 
Example 22
Source Project: presto   Source File: RaptorMetadata.java    License: Apache License 2.0 5 votes vote down vote up
private static ColumnMetadata hiddenColumn(String name, Type type)
{
    return ColumnMetadata.builder()
            .setName(name)
            .setType(type)
            .setHidden(true)
            .build();
}
 
Example 23
Source Project: presto   Source File: PostgreSqlClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public WriteMapping toWriteMapping(ConnectorSession session, Type type)
{
    if (VARBINARY.equals(type)) {
        return WriteMapping.sliceMapping("bytea", varbinaryWriteFunction());
    }
    if (TIME.equals(type)) {
        return WriteMapping.longMapping("time", timeWriteFunction(session));
    }
    if (TIMESTAMP.equals(type)) {
        return WriteMapping.longMapping("timestamp", timestampWriteFunction(session));
    }
    if (TIMESTAMP_WITH_TIME_ZONE.equals(type)) {
        return WriteMapping.longMapping("timestamptz", timestampWithTimeZoneWriteFunction());
    }
    if (TinyintType.TINYINT.equals(type)) {
        return WriteMapping.longMapping("smallint", tinyintWriteFunction());
    }
    if (type.equals(jsonType)) {
        return WriteMapping.sliceMapping("jsonb", typedVarcharWriteFunction("json"));
    }
    if (type.equals(uuidType)) {
        return WriteMapping.sliceMapping("uuid", uuidWriteFunction());
    }
    if (type instanceof ArrayType && getArrayMapping(session) == AS_ARRAY) {
        Type elementType = ((ArrayType) type).getElementType();
        String elementDataType = toWriteMapping(session, elementType).getDataType();
        return WriteMapping.objectMapping(elementDataType + "[]", arrayWriteFunction(session, elementType, getArrayElementPgTypeName(session, this, elementType)));
    }
    return super.toWriteMapping(session, type);
}
 
Example 24
Source Project: presto   Source File: ArrayGreaterThanOperator.java    License: Apache License 2.0 5 votes vote down vote up
@TypeParameter("T")
@SqlType(StandardTypes.BOOLEAN)
public static boolean greaterThan(
        @OperatorDependency(operator = GREATER_THAN, argumentTypes = {"T", "T"}) MethodHandle greaterThanFunction,
        @TypeParameter("T") Type type,
        @SqlType("array(T)") Block leftArray,
        @SqlType("array(T)") Block rightArray)
{
    int len = Math.min(leftArray.getPositionCount(), rightArray.getPositionCount());
    int index = 0;
    while (index < len) {
        checkElementNotNull(leftArray.isNull(index), ARRAY_NULL_ELEMENT_MSG);
        checkElementNotNull(rightArray.isNull(index), ARRAY_NULL_ELEMENT_MSG);
        Object leftElement = readNativeValue(type, leftArray, index);
        Object rightElement = readNativeValue(type, rightArray, index);
        try {
            if ((boolean) greaterThanFunction.invoke(leftElement, rightElement)) {
                return true;
            }
            if ((boolean) greaterThanFunction.invoke(rightElement, leftElement)) {
                return false;
            }
        }
        catch (Throwable t) {
            throw internalError(t);
        }
        index++;
    }

    return leftArray.getPositionCount() > rightArray.getPositionCount();
}
 
Example 25
Source Project: presto   Source File: BenchmarkColumnReaders.java    License: Apache License 2.0 5 votes vote down vote up
public void setup(Type type)
        throws Exception
{
    this.type = type;
    temporaryDirectory = createTempDir();
    orcFile = new File(temporaryDirectory, randomUUID().toString());
    writeOrcColumnPresto(orcFile, NONE, type, createValues(), new OrcWriterStats());

    OrcDataSource dataSource = new FileOrcDataSource(orcFile, new OrcReaderOptions());
    DiskRange diskRange = new DiskRange(0, toIntExact(dataSource.getSize()));
    dataSource = new CachingOrcDataSource(dataSource, desiredOffset -> diskRange);
    this.dataSource = dataSource;
}
 
Example 26
Source Project: presto   Source File: ShardCompactor.java    License: Apache License 2.0 5 votes vote down vote up
public SortedRowSource(ConnectorPageSource pageSource, List<Type> columnTypes, List<Integer> sortIndexes, List<SortOrder> sortOrders)
{
    this.pageSource = requireNonNull(pageSource, "pageSource is null");
    this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null"));
    this.sortIndexes = ImmutableList.copyOf(requireNonNull(sortIndexes, "sortIndexes is null"));
    this.sortOrders = ImmutableList.copyOf(requireNonNull(sortOrders, "sortOrders is null"));

    currentPage = pageSource.getNextPage();
    currentPosition = 0;
}
 
Example 27
Source Project: presto   Source File: TestBlockAndPositionNullConvention.java    License: Apache License 2.0 5 votes vote down vote up
@TypeParameter("E")
@SqlNullable
@SqlType("E")
public static Boolean speciailizedBoolean(@TypeParameter("E") Type type, @SqlNullable @SqlType("E") Boolean bool)
{
    return bool;
}
 
Example 28
Source Project: presto   Source File: FormatFunction.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodHandle castToVarchar(Metadata metadata, Type type)
{
    try {
        ResolvedFunction cast = metadata.getCoercion(type, VARCHAR);
        return metadata.getScalarFunctionInvoker(cast, Optional.empty()).getMethodHandle();
    }
    catch (OperatorNotFoundException e) {
        return null;
    }
}
 
Example 29
Source Project: presto   Source File: SliceDirectColumnWriter.java    License: Apache License 2.0 5 votes vote down vote up
public SliceDirectColumnWriter(OrcColumnId columnId, Type type, CompressionKind compression, int bufferSize, Supplier<SliceColumnStatisticsBuilder> statisticsBuilderSupplier)
{
    this.columnId = requireNonNull(columnId, "columnId is null");
    this.type = requireNonNull(type, "type is null");
    this.compressed = requireNonNull(compression, "compression is null") != NONE;
    this.columnEncoding = new ColumnEncoding(DIRECT_V2, 0);
    this.lengthStream = createLengthOutputStream(compression, bufferSize);
    this.dataStream = new ByteArrayOutputStream(compression, bufferSize);
    this.presentStream = new PresentOutputStream(compression, bufferSize);
    this.statisticsBuilderSupplier = statisticsBuilderSupplier;
    statisticsBuilder = statisticsBuilderSupplier.get();
}
 
Example 30
Source Project: presto   Source File: SimplePagesHashStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean positionEqualsRowIgnoreNulls(int leftBlockIndex, int leftPosition, int rightPosition, Page rightPage)
{
    for (int i = 0; i < hashChannels.size(); i++) {
        int hashChannel = hashChannels.get(i);
        Type type = types.get(hashChannel);
        Block leftBlock = channels.get(hashChannel).get(leftBlockIndex);
        Block rightBlock = rightPage.getBlock(i);
        if (!type.equalTo(leftBlock, leftPosition, rightBlock, rightPosition)) {
            return false;
        }
    }
    return true;
}