Search in sources :

Example 21 with CallExpression

use of com.facebook.presto.spi.relation.CallExpression in project presto by prestodb.

the class StatisticAggregations method split.

private Parts split(PlanVariableAllocator variableAllocator, FunctionAndTypeManager functionAndTypeManager, boolean intermediate) {
    ImmutableMap.Builder<VariableReferenceExpression, Aggregation> finalOrIntermediateAggregations = ImmutableMap.builder();
    ImmutableMap.Builder<VariableReferenceExpression, Aggregation> partialAggregations = ImmutableMap.builder();
    for (Map.Entry<VariableReferenceExpression, Aggregation> entry : aggregations.entrySet()) {
        Aggregation originalAggregation = entry.getValue();
        FunctionHandle functionHandle = originalAggregation.getFunctionHandle();
        InternalAggregationFunction function = functionAndTypeManager.getAggregateFunctionImplementation(functionHandle);
        // create partial aggregation
        VariableReferenceExpression partialVariable = variableAllocator.newVariable(entry.getValue().getCall().getSourceLocation(), functionAndTypeManager.getFunctionMetadata(functionHandle).getName().getObjectName(), function.getIntermediateType());
        partialAggregations.put(partialVariable, new Aggregation(new CallExpression(originalAggregation.getCall().getSourceLocation(), originalAggregation.getCall().getDisplayName(), functionHandle, function.getIntermediateType(), originalAggregation.getArguments()), originalAggregation.getFilter(), originalAggregation.getOrderBy(), originalAggregation.isDistinct(), originalAggregation.getMask()));
        // create final aggregation
        finalOrIntermediateAggregations.put(entry.getKey(), new Aggregation(new CallExpression(originalAggregation.getCall().getSourceLocation(), originalAggregation.getCall().getDisplayName(), functionHandle, intermediate ? function.getIntermediateType() : function.getFinalType(), ImmutableList.of(partialVariable)), Optional.empty(), Optional.empty(), false, Optional.empty()));
    }
    StatisticAggregations finalOrIntermediateAggregation = new StatisticAggregations(finalOrIntermediateAggregations.build(), groupingVariables);
    return new Parts(intermediate ? Optional.empty() : Optional.of(finalOrIntermediateAggregation), intermediate ? Optional.of(finalOrIntermediateAggregation) : Optional.empty(), new StatisticAggregations(partialAggregations.build(), groupingVariables));
}
Also used : Aggregation(com.facebook.presto.spi.plan.AggregationNode.Aggregation) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) InternalAggregationFunction(com.facebook.presto.operator.aggregation.InternalAggregationFunction) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) CallExpression(com.facebook.presto.spi.relation.CallExpression) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 22 with CallExpression

use of com.facebook.presto.spi.relation.CallExpression in project presto by prestodb.

the class TestPageProcessorCompiler method testSanityFilterOnDictionary.

@Test
public void testSanityFilterOnDictionary() {
    FunctionAndTypeManager functionAndTypeManager = createTestMetadataManager().getFunctionAndTypeManager();
    CallExpression lengthVarchar = new CallExpression("length", functionAndTypeManager.lookupFunction("length", fromTypes(VARCHAR)), BIGINT, ImmutableList.of(field(0, VARCHAR)));
    FunctionHandle lessThan = functionAndTypeManager.resolveOperator(LESS_THAN, fromTypes(BIGINT, BIGINT));
    CallExpression filter = new CallExpression(LESS_THAN.name(), lessThan, BOOLEAN, ImmutableList.of(lengthVarchar, constant(10L, BIGINT)));
    PageProcessor processor = compiler.compilePageProcessor(TEST_SESSION.getSqlFunctionProperties(), Optional.of(filter), ImmutableList.of(field(0, VARCHAR)), false, MAX_BATCH_SIZE).get();
    Page page = new Page(createDictionaryBlock(createExpectedValues(10), 100));
    Page outputPage = getOnlyElement(processor.process(null, new DriverYieldSignal(), newSimpleAggregatedMemoryContext().newLocalMemoryContext(PageProcessor.class.getSimpleName()), page)).orElseThrow(() -> new AssertionError("page is not present"));
    assertEquals(outputPage.getPositionCount(), 100);
    assertTrue(outputPage.getBlock(0) instanceof DictionaryBlock);
    DictionaryBlock dictionaryBlock = (DictionaryBlock) outputPage.getBlock(0);
    assertEquals(dictionaryBlock.getDictionary().getPositionCount(), 10);
    // test filter caching
    Page outputPage2 = getOnlyElement(processor.process(null, new DriverYieldSignal(), newSimpleAggregatedMemoryContext().newLocalMemoryContext(PageProcessor.class.getSimpleName()), page)).orElseThrow(() -> new AssertionError("page is not present"));
    assertEquals(outputPage2.getPositionCount(), 100);
    assertTrue(outputPage2.getBlock(0) instanceof DictionaryBlock);
    DictionaryBlock dictionaryBlock2 = (DictionaryBlock) outputPage2.getBlock(0);
    // both output pages must have the same dictionary
    assertEquals(dictionaryBlock2.getDictionary(), dictionaryBlock.getDictionary());
}
Also used : PageProcessor(com.facebook.presto.operator.project.PageProcessor) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) DictionaryBlock(com.facebook.presto.common.block.DictionaryBlock) BlockAssertions.createLongDictionaryBlock(com.facebook.presto.block.BlockAssertions.createLongDictionaryBlock) DriverYieldSignal(com.facebook.presto.operator.DriverYieldSignal) Page(com.facebook.presto.common.Page) CallExpression(com.facebook.presto.spi.relation.CallExpression) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) Test(org.testng.annotations.Test)

Example 23 with CallExpression

use of com.facebook.presto.spi.relation.CallExpression in project presto by prestodb.

the class ExtractSpatialJoins method addPartitioningNodes.

private static PlanNode addPartitioningNodes(Context context, FunctionAndTypeManager functionAndTypeManager, PlanNode node, VariableReferenceExpression partitionVariable, KdbTree kdbTree, RowExpression geometry, Optional<RowExpression> radius) {
    Assignments.Builder projections = Assignments.builder();
    for (VariableReferenceExpression outputVariable : node.getOutputVariables()) {
        projections.put(outputVariable, outputVariable);
    }
    FunctionHandle castFunctionHandle = functionAndTypeManager.lookupCast(CAST, VARCHAR.getTypeSignature(), KDB_TREE.getTypeSignature());
    ImmutableList.Builder partitioningArgumentsBuilder = ImmutableList.builder().add(new CallExpression(partitionVariable.getSourceLocation(), CAST.name(), castFunctionHandle, KDB_TREE, ImmutableList.of(Expressions.constant(utf8Slice(KdbTreeUtils.toJson(kdbTree)), VARCHAR)))).add(geometry);
    radius.map(partitioningArgumentsBuilder::add);
    List<RowExpression> partitioningArguments = partitioningArgumentsBuilder.build();
    String spatialPartitionsFunctionName = "spatial_partitions";
    FunctionHandle functionHandle = functionAndTypeManager.lookupFunction(spatialPartitionsFunctionName, fromTypes(partitioningArguments.stream().map(RowExpression::getType).collect(toImmutableList())));
    CallExpression partitioningFunction = new CallExpression(partitionVariable.getSourceLocation(), spatialPartitionsFunctionName, functionHandle, new ArrayType(INTEGER), partitioningArguments);
    VariableReferenceExpression partitionsVariable = context.getVariableAllocator().newVariable(partitioningFunction);
    projections.put(partitionsVariable, partitioningFunction);
    return new UnnestNode(node.getSourceLocation(), context.getIdAllocator().getNextId(), new ProjectNode(node.getSourceLocation(), context.getIdAllocator().getNextId(), node, projections.build(), LOCAL), node.getOutputVariables(), ImmutableMap.of(partitionsVariable, ImmutableList.of(partitionVariable)), Optional.empty());
}
Also used : ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Assignments(com.facebook.presto.spi.plan.Assignments) RowExpression(com.facebook.presto.spi.relation.RowExpression) ArrayType(com.facebook.presto.common.type.ArrayType) UnnestNode(com.facebook.presto.sql.planner.plan.UnnestNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) ProjectNode(com.facebook.presto.spi.plan.ProjectNode) SpatialJoinUtils.getFlippedFunctionHandle(com.facebook.presto.util.SpatialJoinUtils.getFlippedFunctionHandle) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) CallExpression(com.facebook.presto.spi.relation.CallExpression)

Example 24 with CallExpression

use of com.facebook.presto.spi.relation.CallExpression in project presto by prestodb.

the class TestPageProcessor method testExpressionProfiler.

@Test
public void testExpressionProfiler() {
    MetadataManager metadata = createTestMetadataManager();
    CallExpression add10Expression = call(ADD.name(), metadata.getFunctionAndTypeManager().resolveOperator(ADD, fromTypes(BIGINT, BIGINT)), BIGINT, field(0, BIGINT), constant(10L, BIGINT));
    TestingTicker testingTicker = new TestingTicker();
    PageFunctionCompiler functionCompiler = new PageFunctionCompiler(metadata, 0);
    Supplier<PageProjection> projectionSupplier = functionCompiler.compileProjection(SESSION.getSqlFunctionProperties(), add10Expression, Optional.empty());
    PageProjection projection = projectionSupplier.get();
    Page page = new Page(createLongSequenceBlock(1, 11));
    ExpressionProfiler profiler = new ExpressionProfiler(testingTicker, SPLIT_RUN_QUANTA);
    for (int i = 0; i < 100; i++) {
        profiler.start();
        Work<List<Block>> work = projection.project(SESSION.getSqlFunctionProperties(), new DriverYieldSignal(), page, SelectedPositions.positionsRange(0, page.getPositionCount()));
        if (i < 10) {
            // increment the ticker with a large value to mark the expression as expensive
            testingTicker.increment(10, SECONDS);
            profiler.stop(page.getPositionCount());
            assertTrue(profiler.isExpressionExpensive());
        } else {
            testingTicker.increment(0, NANOSECONDS);
            profiler.stop(page.getPositionCount());
            assertFalse(profiler.isExpressionExpensive());
        }
        work.process();
    }
}
Also used : MetadataManager(com.facebook.presto.metadata.MetadataManager) MetadataManager.createTestMetadataManager(com.facebook.presto.metadata.MetadataManager.createTestMetadataManager) TestingTicker(com.facebook.airlift.testing.TestingTicker) PageFunctionCompiler(com.facebook.presto.sql.gen.PageFunctionCompiler) DriverYieldSignal(com.facebook.presto.operator.DriverYieldSignal) Page(com.facebook.presto.common.Page) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) SelectedPositions.positionsList(com.facebook.presto.operator.project.SelectedPositions.positionsList) CallExpression(com.facebook.presto.spi.relation.CallExpression) ExpressionProfiler(com.facebook.presto.sql.gen.ExpressionProfiler) Test(org.testng.annotations.Test)

Example 25 with CallExpression

use of com.facebook.presto.spi.relation.CallExpression in project presto by prestodb.

the class ExtractSpatialJoins method tryCreateSpatialJoin.

private static Result tryCreateSpatialJoin(Context context, JoinNode joinNode, RowExpression filter, PlanNodeId nodeId, List<VariableReferenceExpression> outputVariables, CallExpression spatialComparison, Metadata metadata, SplitManager splitManager, PageSourceManager pageSourceManager) {
    FunctionMetadata spatialComparisonMetadata = metadata.getFunctionAndTypeManager().getFunctionMetadata(spatialComparison.getFunctionHandle());
    checkArgument(spatialComparison.getArguments().size() == 2 && spatialComparisonMetadata.getOperatorType().isPresent());
    PlanNode leftNode = joinNode.getLeft();
    PlanNode rightNode = joinNode.getRight();
    List<VariableReferenceExpression> leftVariables = leftNode.getOutputVariables();
    List<VariableReferenceExpression> rightVariables = rightNode.getOutputVariables();
    RowExpression radius;
    Optional<VariableReferenceExpression> newRadiusVariable;
    CallExpression newComparison;
    if (spatialComparisonMetadata.getOperatorType().get() == OperatorType.LESS_THAN || spatialComparisonMetadata.getOperatorType().get() == OperatorType.LESS_THAN_OR_EQUAL) {
        // ST_Distance(a, b) <= r
        radius = spatialComparison.getArguments().get(1);
        Set<VariableReferenceExpression> radiusVariables = extractUnique(radius);
        if (radiusVariables.isEmpty() || (rightVariables.containsAll(radiusVariables) && containsNone(leftVariables, radiusVariables))) {
            newRadiusVariable = newRadiusVariable(context, radius);
            newComparison = new CallExpression(spatialComparison.getSourceLocation(), spatialComparison.getDisplayName(), spatialComparison.getFunctionHandle(), spatialComparison.getType(), ImmutableList.of(spatialComparison.getArguments().get(0), mapToExpression(newRadiusVariable, radius)));
        } else {
            return Result.empty();
        }
    } else {
        // r >= ST_Distance(a, b)
        radius = spatialComparison.getArguments().get(0);
        Set<VariableReferenceExpression> radiusVariables = extractUnique(radius);
        if (radiusVariables.isEmpty() || (rightVariables.containsAll(radiusVariables) && containsNone(leftVariables, radiusVariables))) {
            newRadiusVariable = newRadiusVariable(context, radius);
            OperatorType flippedOperatorType = flip(spatialComparisonMetadata.getOperatorType().get());
            FunctionHandle flippedHandle = getFlippedFunctionHandle(spatialComparison, metadata.getFunctionAndTypeManager());
            newComparison = new CallExpression(spatialComparison.getSourceLocation(), // TODO verify if this is the correct function displayName
            flippedOperatorType.getOperator(), flippedHandle, spatialComparison.getType(), ImmutableList.of(spatialComparison.getArguments().get(1), mapToExpression(newRadiusVariable, radius)));
        } else {
            return Result.empty();
        }
    }
    RowExpression newFilter = replaceExpression(filter, ImmutableMap.of(spatialComparison, newComparison));
    PlanNode newRightNode = newRadiusVariable.map(variable -> addProjection(context, rightNode, variable, radius)).orElse(rightNode);
    JoinNode newJoinNode = new JoinNode(joinNode.getSourceLocation(), joinNode.getId(), joinNode.getType(), leftNode, newRightNode, joinNode.getCriteria(), joinNode.getOutputVariables(), Optional.of(newFilter), joinNode.getLeftHashVariable(), joinNode.getRightHashVariable(), joinNode.getDistributionType(), joinNode.getDynamicFilters());
    return tryCreateSpatialJoin(context, newJoinNode, newFilter, nodeId, outputVariables, (CallExpression) newComparison.getArguments().get(0), Optional.of(newComparison.getArguments().get(1)), metadata, splitManager, pageSourceManager);
}
Also used : FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) WarningCollector(com.facebook.presto.spi.WarningCollector) Page(com.facebook.presto.common.Page) SpatialJoinNode(com.facebook.presto.sql.planner.plan.SpatialJoinNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) TypeSignature(com.facebook.presto.common.type.TypeSignature) MoreFutures.getFutureValue(com.facebook.airlift.concurrent.MoreFutures.getFutureValue) NOT_PARTITIONED(com.facebook.presto.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED) SpatialJoinUtils.getFlippedFunctionHandle(com.facebook.presto.util.SpatialJoinUtils.getFlippedFunctionHandle) Pattern(com.facebook.presto.matching.Pattern) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Capture(com.facebook.presto.matching.Capture) SpatialJoinUtils.flip(com.facebook.presto.util.SpatialJoinUtils.flip) Map(java.util.Map) UNGROUPED_SCHEDULING(com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING) LOCAL(com.facebook.presto.spi.plan.ProjectNode.Locality.LOCAL) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) SystemSessionProperties.isSpatialJoinEnabled(com.facebook.presto.SystemSessionProperties.isSpatialJoinEnabled) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) CallExpression(com.facebook.presto.spi.relation.CallExpression) Splitter(com.google.common.base.Splitter) SplitSource(com.facebook.presto.split.SplitSource) Lifespan(com.facebook.presto.execution.Lifespan) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) SplitManager(com.facebook.presto.split.SplitManager) String.format(java.lang.String.format) KDB_TREE(com.facebook.presto.common.type.KdbTreeType.KDB_TREE) UncheckedIOException(java.io.UncheckedIOException) FunctionMetadata(com.facebook.presto.spi.function.FunctionMetadata) List(java.util.List) SpatialJoinUtils.extractSupportedSpatialFunctions(com.facebook.presto.util.SpatialJoinUtils.extractSupportedSpatialFunctions) KdbTreeUtils(com.facebook.presto.geospatial.KdbTreeUtils) ProjectNode(com.facebook.presto.spi.plan.ProjectNode) Capture.newCapture(com.facebook.presto.matching.Capture.newCapture) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) Optional(java.util.Optional) CAST(com.facebook.presto.metadata.CastType.CAST) VariablesExtractor.extractUnique(com.facebook.presto.sql.planner.VariablesExtractor.extractUnique) INNER(com.facebook.presto.sql.planner.plan.JoinNode.Type.INNER) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) Iterables(com.google.common.collect.Iterables) TableLayoutResult(com.facebook.presto.metadata.TableLayoutResult) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) Captures(com.facebook.presto.matching.Captures) Assignments(com.facebook.presto.spi.plan.Assignments) Result(com.facebook.presto.sql.planner.iterative.Rule.Result) PrestoException(com.facebook.presto.spi.PrestoException) Patterns.join(com.facebook.presto.sql.planner.plan.Patterns.join) TypeSignatureProvider.fromTypes(com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes) Patterns.filter(com.facebook.presto.sql.planner.plan.Patterns.filter) FilterNode(com.facebook.presto.spi.plan.FilterNode) SplitBatch(com.facebook.presto.split.SplitSource.SplitBatch) RowExpressionNodeInliner(com.facebook.presto.expressions.RowExpressionNodeInliner) ImmutableList(com.google.common.collect.ImmutableList) PageSourceManager(com.facebook.presto.split.PageSourceManager) Verify.verify(com.google.common.base.Verify.verify) Objects.requireNonNull(java.util.Objects.requireNonNull) SpatialJoinUtils.extractSupportedSpatialComparisons(com.facebook.presto.util.SpatialJoinUtils.extractSupportedSpatialComparisons) ArrayType(com.facebook.presto.common.type.ArrayType) TableHandle(com.facebook.presto.spi.TableHandle) Expressions(com.facebook.presto.sql.relational.Expressions) KdbTree(com.facebook.presto.geospatial.KdbTree) UnnestNode(com.facebook.presto.sql.planner.plan.UnnestNode) Type(com.facebook.presto.common.type.Type) RowExpression(com.facebook.presto.spi.relation.RowExpression) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) INVALID_SPATIAL_PARTITIONING(com.facebook.presto.spi.StandardErrorCode.INVALID_SPATIAL_PARTITIONING) SystemSessionProperties.getSpatialPartitioningTableName(com.facebook.presto.SystemSessionProperties.getSpatialPartitioningTableName) Session(com.facebook.presto.Session) Rule(com.facebook.presto.sql.planner.iterative.Rule) Constraint(com.facebook.presto.spi.Constraint) IOException(java.io.IOException) OperatorType(com.facebook.presto.common.function.OperatorType) Patterns.source(com.facebook.presto.sql.planner.plan.Patterns.source) PlanNode(com.facebook.presto.spi.plan.PlanNode) ConnectorPageSource(com.facebook.presto.spi.ConnectorPageSource) TypeSignature.parseTypeSignature(com.facebook.presto.common.type.TypeSignature.parseTypeSignature) LEFT(com.facebook.presto.sql.planner.plan.JoinNode.Type.LEFT) ColumnHandle(com.facebook.presto.spi.ColumnHandle) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) Split(com.facebook.presto.metadata.Split) Context(com.facebook.presto.sql.planner.iterative.Rule.Context) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Metadata(com.facebook.presto.metadata.Metadata) RowExpressionNodeInliner.replaceExpression(com.facebook.presto.expressions.RowExpressionNodeInliner.replaceExpression) FunctionMetadata(com.facebook.presto.spi.function.FunctionMetadata) PlanNode(com.facebook.presto.spi.plan.PlanNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) SpatialJoinNode(com.facebook.presto.sql.planner.plan.SpatialJoinNode) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) RowExpression(com.facebook.presto.spi.relation.RowExpression) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpatialJoinUtils.getFlippedFunctionHandle(com.facebook.presto.util.SpatialJoinUtils.getFlippedFunctionHandle) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) OperatorType(com.facebook.presto.common.function.OperatorType)

Aggregations

CallExpression (com.facebook.presto.spi.relation.CallExpression)64 RowExpression (com.facebook.presto.spi.relation.RowExpression)33 VariableReferenceExpression (com.facebook.presto.spi.relation.VariableReferenceExpression)33 Test (org.testng.annotations.Test)22 AggregationNode (com.facebook.presto.spi.plan.AggregationNode)20 FunctionHandle (com.facebook.presto.spi.function.FunctionHandle)19 ImmutableList (com.google.common.collect.ImmutableList)18 FunctionAndTypeManager (com.facebook.presto.metadata.FunctionAndTypeManager)16 Type (com.facebook.presto.common.type.Type)14 Map (java.util.Map)14 ConstantExpression (com.facebook.presto.spi.relation.ConstantExpression)13 ImmutableMap (com.google.common.collect.ImmutableMap)13 Optional (java.util.Optional)12 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)11 OperatorType (com.facebook.presto.common.function.OperatorType)10 Aggregation (com.facebook.presto.spi.plan.AggregationNode.Aggregation)10 PlanNode (com.facebook.presto.spi.plan.PlanNode)10 ProjectNode (com.facebook.presto.spi.plan.ProjectNode)10 SpecialFormExpression (com.facebook.presto.spi.relation.SpecialFormExpression)10 Page (com.facebook.presto.common.Page)8