Search in sources :

Example 6 with Assignments

use of com.facebook.presto.spi.plan.Assignments in project presto by prestodb.

the class RowExpressionRewriteRuleSet method translateAssignments.

private Optional<Assignments> translateAssignments(Assignments assignments, Rule.Context context) {
    Assignments.Builder builder = Assignments.builder();
    assignments.getMap().entrySet().stream().forEach(entry -> builder.put(entry.getKey(), rewriter.rewrite(entry.getValue(), context)));
    Assignments rewritten = builder.build();
    if (rewritten.equals(assignments)) {
        return Optional.empty();
    }
    return Optional.of(rewritten);
}
Also used : Assignments(com.facebook.presto.spi.plan.Assignments)

Example 7 with Assignments

use of com.facebook.presto.spi.plan.Assignments in project presto by prestodb.

the class LogicalPlanner method buildInternalInsertPlan.

private RelationPlan buildInternalInsertPlan(TableHandle tableHandle, List<ColumnHandle> columnHandles, Query query, Analysis analysis, WriterTarget target) {
    TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle);
    List<ColumnMetadata> visibleTableColumns = tableMetadata.getColumns().stream().filter(column -> !column.isHidden()).collect(toImmutableList());
    List<String> visibleTableColumnNames = visibleTableColumns.stream().map(ColumnMetadata::getName).collect(toImmutableList());
    RelationPlan plan = createRelationPlan(analysis, query);
    Map<String, ColumnHandle> columns = metadata.getColumnHandles(session, tableHandle);
    Assignments.Builder assignments = Assignments.builder();
    for (ColumnMetadata column : tableMetadata.getColumns()) {
        if (column.isHidden()) {
            continue;
        }
        VariableReferenceExpression output = variableAllocator.newVariable(getSourceLocation(query), column.getName(), column.getType());
        int index = columnHandles.indexOf(columns.get(column.getName()));
        if (index < 0) {
            Expression cast = new Cast(new NullLiteral(), column.getType().getTypeSignature().toString());
            assignments.put(output, castToRowExpression(cast));
        } else {
            VariableReferenceExpression input = plan.getVariable(index);
            Type tableType = column.getType();
            Type queryType = input.getType();
            if (queryType.equals(tableType) || metadata.getFunctionAndTypeManager().isTypeOnlyCoercion(queryType, tableType)) {
                assignments.put(output, castToRowExpression(createSymbolReference(input)));
            } else {
                Expression cast = new Cast(createSymbolReference(input), tableType.getTypeSignature().toString());
                assignments.put(output, castToRowExpression(cast));
            }
        }
    }
    ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), plan.getRoot(), assignments.build());
    List<Field> fields = visibleTableColumns.stream().map(column -> Field.newUnqualified(query.getLocation(), column.getName(), column.getType())).collect(toImmutableList());
    Scope scope = Scope.builder().withRelationType(RelationId.anonymous(), new RelationType(fields)).build();
    plan = new RelationPlan(projectNode, scope, projectNode.getOutputVariables());
    Optional<NewTableLayout> newTableLayout = metadata.getInsertLayout(session, tableHandle);
    Optional<NewTableLayout> preferredShuffleLayout = metadata.getPreferredShuffleLayoutForInsert(session, tableHandle);
    String catalogName = tableHandle.getConnectorId().getCatalogName();
    TableStatisticsMetadata statisticsMetadata = metadata.getStatisticsCollectionMetadataForWrite(session, catalogName, tableMetadata.getMetadata());
    return createTableWriterPlan(analysis, plan, target, visibleTableColumnNames, visibleTableColumns, newTableLayout, preferredShuffleLayout, statisticsMetadata);
}
Also used : WarningCollector(com.facebook.presto.spi.WarningCollector) FINAL(com.facebook.presto.spi.plan.LimitNode.Step.FINAL) NOT_FOUND(com.facebook.presto.spi.StandardErrorCode.NOT_FOUND) Analyze(com.facebook.presto.sql.tree.Analyze) Field(com.facebook.presto.sql.analyzer.Field) CachingStatsProvider(com.facebook.presto.cost.CachingStatsProvider) ValuesNode(com.facebook.presto.spi.plan.ValuesNode) TableStatisticAggregation(com.facebook.presto.sql.planner.StatisticsAggregationPlanner.TableStatisticAggregation) Delete(com.facebook.presto.sql.tree.Delete) Map(java.util.Map) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) AggregationNode.singleGroupingSet(com.facebook.presto.spi.plan.AggregationNode.singleGroupingSet) Query(com.facebook.presto.sql.tree.Query) Explain(com.facebook.presto.sql.tree.Explain) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) LimitNode(com.facebook.presto.spi.plan.LimitNode) NullLiteral(com.facebook.presto.sql.tree.NullLiteral) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ProjectNode(com.facebook.presto.spi.plan.ProjectNode) DeleteHandle(com.facebook.presto.sql.planner.plan.TableWriterNode.DeleteHandle) ExpressionTreeUtils.getSourceLocation(com.facebook.presto.sql.analyzer.ExpressionTreeUtils.getSourceLocation) TableStatisticsMetadata(com.facebook.presto.spi.statistics.TableStatisticsMetadata) SystemSessionProperties(com.facebook.presto.SystemSessionProperties) PlanOptimizer(com.facebook.presto.sql.planner.optimizations.PlanOptimizer) LambdaArgumentDeclaration(com.facebook.presto.sql.tree.LambdaArgumentDeclaration) SystemSessionProperties.isPrintStatsForNonJoinQuery(com.facebook.presto.SystemSessionProperties.isPrintStatsForNonJoinQuery) NewTableLayout(com.facebook.presto.metadata.NewTableLayout) Assignments(com.facebook.presto.spi.plan.Assignments) ArrayList(java.util.ArrayList) Identifier(com.facebook.presto.sql.tree.Identifier) LinkedHashMap(java.util.LinkedHashMap) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) TableHandle(com.facebook.presto.spi.TableHandle) Cast(com.facebook.presto.sql.tree.Cast) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) MetadataUtil.toSchemaTableName(com.facebook.presto.metadata.MetadataUtil.toSchemaTableName) PlanNodeIdAllocator(com.facebook.presto.spi.plan.PlanNodeIdAllocator) Session(com.facebook.presto.Session) InsertReference(com.facebook.presto.sql.planner.plan.TableWriterNode.InsertReference) StatsProvider(com.facebook.presto.cost.StatsProvider) RefreshMaterializedViewReference(com.facebook.presto.sql.planner.plan.TableWriterNode.RefreshMaterializedViewReference) NodeRef(com.facebook.presto.sql.tree.NodeRef) Scope(com.facebook.presto.sql.analyzer.Scope) ColumnHandle(com.facebook.presto.spi.ColumnHandle) TableScanNode(com.facebook.presto.spi.plan.TableScanNode) SemiJoinNode(com.facebook.presto.sql.planner.plan.SemiJoinNode) Metadata(com.facebook.presto.metadata.Metadata) ExpressionTreeUtils.createSymbolReference(com.facebook.presto.sql.analyzer.ExpressionTreeUtils.createSymbolReference) OriginalExpressionUtils.castToRowExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToRowExpression) TableMetadata(com.facebook.presto.metadata.TableMetadata) AggregationNode(com.facebook.presto.spi.plan.AggregationNode) ExplainAnalyzeNode(com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) TableWriterNode(com.facebook.presto.sql.planner.plan.TableWriterNode) Expressions.constant(com.facebook.presto.sql.relational.Expressions.constant) StatsCalculator(com.facebook.presto.cost.StatsCalculator) StatisticAggregations(com.facebook.presto.sql.planner.plan.StatisticAggregations) RefreshMaterializedView(com.facebook.presto.sql.tree.RefreshMaterializedView) CostProvider(com.facebook.presto.cost.CostProvider) OutputNode(com.facebook.presto.sql.planner.plan.OutputNode) RelationId(com.facebook.presto.sql.analyzer.RelationId) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CostCalculator(com.facebook.presto.cost.CostCalculator) String.format(java.lang.String.format) SqlParser(com.facebook.presto.sql.parser.SqlParser) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) NOT_SUPPORTED(com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED) Entry(java.util.Map.Entry) Analysis(com.facebook.presto.sql.analyzer.Analysis) Optional(java.util.Optional) ConnectorId(com.facebook.presto.spi.ConnectorId) CachingCostProvider(com.facebook.presto.cost.CachingCostProvider) WriterTarget(com.facebook.presto.sql.planner.plan.TableWriterNode.WriterTarget) PrestoException(com.facebook.presto.spi.PrestoException) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) ImmutableList(com.google.common.collect.ImmutableList) PlanChecker(com.facebook.presto.sql.planner.sanity.PlanChecker) Verify.verify(com.google.common.base.Verify.verify) Objects.requireNonNull(java.util.Objects.requireNonNull) Type(com.facebook.presto.common.type.Type) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) CreateTableAsSelect(com.facebook.presto.sql.tree.CreateTableAsSelect) ROW_COUNT(com.facebook.presto.spi.statistics.TableStatisticType.ROW_COUNT) PlanNodeSearcher(com.facebook.presto.sql.planner.optimizations.PlanNodeSearcher) RelationType(com.facebook.presto.sql.analyzer.RelationType) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) DeleteNode(com.facebook.presto.sql.planner.plan.DeleteNode) Insert(com.facebook.presto.sql.tree.Insert) PlanNode(com.facebook.presto.spi.plan.PlanNode) Expression(com.facebook.presto.sql.tree.Expression) CreateName(com.facebook.presto.sql.planner.plan.TableWriterNode.CreateName) StatsAndCosts(com.facebook.presto.cost.StatsAndCosts) TableFinishNode(com.facebook.presto.sql.planner.plan.TableFinishNode) Streams.zip(com.google.common.collect.Streams.zip) StatisticsWriterNode(com.facebook.presto.sql.planner.plan.StatisticsWriterNode) Statement(com.facebook.presto.sql.tree.Statement) Cast(com.facebook.presto.sql.tree.Cast) TableStatisticsMetadata(com.facebook.presto.spi.statistics.TableStatisticsMetadata) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) NewTableLayout(com.facebook.presto.metadata.NewTableLayout) Assignments(com.facebook.presto.spi.plan.Assignments) Field(com.facebook.presto.sql.analyzer.Field) RelationType(com.facebook.presto.sql.analyzer.RelationType) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) TableMetadata(com.facebook.presto.metadata.TableMetadata) ColumnHandle(com.facebook.presto.spi.ColumnHandle) Type(com.facebook.presto.common.type.Type) RelationType(com.facebook.presto.sql.analyzer.RelationType) Scope(com.facebook.presto.sql.analyzer.Scope) OriginalExpressionUtils.castToRowExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToRowExpression) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Expression(com.facebook.presto.sql.tree.Expression) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) ProjectNode(com.facebook.presto.spi.plan.ProjectNode) NullLiteral(com.facebook.presto.sql.tree.NullLiteral)

Example 8 with Assignments

use of com.facebook.presto.spi.plan.Assignments in project presto by prestodb.

the class QueryPlanner method explicitCoercionVariables.

private PlanBuilder explicitCoercionVariables(PlanBuilder subPlan, List<VariableReferenceExpression> alreadyCoerced, Iterable<? extends Expression> uncoerced) {
    TranslationMap translations = subPlan.copyTranslations();
    Assignments assignments = Assignments.builder().putAll(coerce(uncoerced, subPlan, translations)).putAll(identitiesAsSymbolReferences(alreadyCoerced)).build();
    return new PlanBuilder(translations, new ProjectNode(subPlan.getRoot().getSourceLocation(), idAllocator.getNextId(), subPlan.getRoot(), assignments, LOCAL));
}
Also used : Assignments(com.facebook.presto.spi.plan.Assignments) ProjectNode(com.facebook.presto.spi.plan.ProjectNode)

Example 9 with Assignments

use of com.facebook.presto.spi.plan.Assignments in project presto by prestodb.

the class QueryPlanner method aggregate.

private PlanBuilder aggregate(PlanBuilder subPlan, QuerySpecification node) {
    if (!analysis.isAggregation(node)) {
        return subPlan;
    }
    // 1. Pre-project all scalar inputs (arguments and non-trivial group by expressions)
    Set<Expression> groupByExpressions = ImmutableSet.copyOf(analysis.getGroupByExpressions(node));
    ImmutableList.Builder<Expression> arguments = ImmutableList.builder();
    analysis.getAggregates(node).stream().map(FunctionCall::getArguments).flatMap(List::stream).filter(// lambda expression is generated at execution time
    exp -> !(exp instanceof LambdaExpression)).forEach(arguments::add);
    analysis.getAggregates(node).stream().map(FunctionCall::getOrderBy).filter(Optional::isPresent).map(Optional::get).map(OrderBy::getSortItems).flatMap(List::stream).map(SortItem::getSortKey).forEach(arguments::add);
    // filter expressions need to be projected first
    analysis.getAggregates(node).stream().map(FunctionCall::getFilter).filter(Optional::isPresent).map(Optional::get).forEach(arguments::add);
    Iterable<Expression> inputs = Iterables.concat(groupByExpressions, arguments.build());
    subPlan = handleSubqueries(subPlan, node, inputs);
    if (!Iterables.isEmpty(inputs)) {
        // avoid an empty projection if the only aggregation is COUNT (which has no arguments)
        subPlan = project(subPlan, inputs);
    }
    // 2. Aggregate
    // 2.a. Rewrite aggregate arguments
    TranslationMap argumentTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToVariableMap);
    ImmutableList.Builder<VariableReferenceExpression> aggregationArgumentsBuilder = ImmutableList.builder();
    for (Expression argument : arguments.build()) {
        VariableReferenceExpression variable = subPlan.translate(argument);
        argumentTranslations.put(argument, variable);
        aggregationArgumentsBuilder.add(variable);
    }
    List<VariableReferenceExpression> aggregationArguments = aggregationArgumentsBuilder.build();
    // 2.b. Rewrite grouping columns
    TranslationMap groupingTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToVariableMap);
    Map<VariableReferenceExpression, VariableReferenceExpression> groupingSetMappings = new LinkedHashMap<>();
    for (Expression expression : groupByExpressions) {
        VariableReferenceExpression input = subPlan.translate(expression);
        VariableReferenceExpression output = variableAllocator.newVariable(expression, analysis.getTypeWithCoercions(expression), "gid");
        groupingTranslations.put(expression, output);
        groupingSetMappings.put(output, input);
    }
    // This tracks the grouping sets before complex expressions are considered (see comments below)
    // It's also used to compute the descriptors needed to implement grouping()
    List<Set<FieldId>> columnOnlyGroupingSets = ImmutableList.of(ImmutableSet.of());
    List<List<VariableReferenceExpression>> groupingSets = ImmutableList.of(ImmutableList.of());
    if (node.getGroupBy().isPresent()) {
        // For the purpose of "distinct", we need to canonicalize column references that may have varying
        // syntactic forms (e.g., "t.a" vs "a"). Thus we need to enumerate grouping sets based on the underlying
        // fieldId associated with each column reference expression.
        // The catch is that simple group-by expressions can be arbitrary expressions (this is a departure from the SQL specification).
        // But, they don't affect the number of grouping sets or the behavior of "distinct" . We can compute all the candidate
        // grouping sets in terms of fieldId, dedup as appropriate and then cross-join them with the complex expressions.
        Analysis.GroupingSetAnalysis groupingSetAnalysis = analysis.getGroupingSets(node);
        columnOnlyGroupingSets = enumerateGroupingSets(groupingSetAnalysis);
        if (node.getGroupBy().get().isDistinct()) {
            columnOnlyGroupingSets = columnOnlyGroupingSets.stream().distinct().collect(toImmutableList());
        }
        // add in the complex expressions an turn materialize the grouping sets in terms of plan columns
        ImmutableList.Builder<List<VariableReferenceExpression>> groupingSetBuilder = ImmutableList.builder();
        for (Set<FieldId> groupingSet : columnOnlyGroupingSets) {
            ImmutableList.Builder<VariableReferenceExpression> columns = ImmutableList.builder();
            groupingSetAnalysis.getComplexExpressions().stream().map(groupingTranslations::get).forEach(columns::add);
            groupingSet.stream().map(field -> groupingTranslations.get(new FieldReference(field.getFieldIndex()))).forEach(columns::add);
            groupingSetBuilder.add(columns.build());
        }
        groupingSets = groupingSetBuilder.build();
    }
    // 2.c. Generate GroupIdNode (multiple grouping sets) or ProjectNode (single grouping set)
    Optional<VariableReferenceExpression> groupIdVariable = Optional.empty();
    if (groupingSets.size() > 1) {
        groupIdVariable = Optional.of(variableAllocator.newVariable("groupId", BIGINT));
        GroupIdNode groupId = new GroupIdNode(subPlan.getRoot().getSourceLocation(), idAllocator.getNextId(), subPlan.getRoot(), groupingSets, groupingSetMappings, aggregationArguments, groupIdVariable.get());
        subPlan = new PlanBuilder(groupingTranslations, groupId);
    } else {
        Assignments.Builder assignments = Assignments.builder();
        aggregationArguments.stream().map(AssignmentUtils::identityAsSymbolReference).forEach(assignments::put);
        groupingSetMappings.forEach((key, value) -> assignments.put(key, castToRowExpression(asSymbolReference(value))));
        ProjectNode project = new ProjectNode(subPlan.getRoot().getSourceLocation(), idAllocator.getNextId(), subPlan.getRoot(), assignments.build(), LOCAL);
        subPlan = new PlanBuilder(groupingTranslations, project);
    }
    TranslationMap aggregationTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToVariableMap);
    aggregationTranslations.copyMappingsFrom(groupingTranslations);
    // 2.d. Rewrite aggregates
    ImmutableMap.Builder<VariableReferenceExpression, Aggregation> aggregationsBuilder = ImmutableMap.builder();
    boolean needPostProjectionCoercion = false;
    for (FunctionCall aggregate : analysis.getAggregates(node)) {
        Expression rewritten = argumentTranslations.rewrite(aggregate);
        VariableReferenceExpression newVariable = variableAllocator.newVariable(rewritten, analysis.getType(aggregate));
        // Therefore we can end up with this implicit cast, and have to move it into a post-projection
        if (rewritten instanceof Cast) {
            rewritten = ((Cast) rewritten).getExpression();
            needPostProjectionCoercion = true;
        }
        aggregationTranslations.put(aggregate, newVariable);
        FunctionCall rewrittenFunction = (FunctionCall) rewritten;
        aggregationsBuilder.put(newVariable, new Aggregation(new CallExpression(getSourceLocation(rewrittenFunction), aggregate.getName().getSuffix(), analysis.getFunctionHandle(aggregate), analysis.getType(aggregate), rewrittenFunction.getArguments().stream().map(OriginalExpressionUtils::castToRowExpression).collect(toImmutableList())), rewrittenFunction.getFilter().map(OriginalExpressionUtils::castToRowExpression), rewrittenFunction.getOrderBy().map(orderBy -> toOrderingScheme(orderBy, variableAllocator.getTypes())), rewrittenFunction.isDistinct(), Optional.empty()));
    }
    Map<VariableReferenceExpression, Aggregation> aggregations = aggregationsBuilder.build();
    ImmutableSet.Builder<Integer> globalGroupingSets = ImmutableSet.builder();
    for (int i = 0; i < groupingSets.size(); i++) {
        if (groupingSets.get(i).isEmpty()) {
            globalGroupingSets.add(i);
        }
    }
    ImmutableList.Builder<VariableReferenceExpression> groupingKeys = ImmutableList.builder();
    groupingSets.stream().flatMap(List::stream).distinct().forEach(groupingKeys::add);
    groupIdVariable.ifPresent(groupingKeys::add);
    AggregationNode aggregationNode = new AggregationNode(subPlan.getRoot().getSourceLocation(), idAllocator.getNextId(), subPlan.getRoot(), aggregations, groupingSets(groupingKeys.build(), groupingSets.size(), globalGroupingSets.build()), ImmutableList.of(), AggregationNode.Step.SINGLE, Optional.empty(), groupIdVariable);
    subPlan = new PlanBuilder(aggregationTranslations, aggregationNode);
    // TODO: this is a hack, we should change type coercions to coerce the inputs to functions/operators instead of coercing the output
    if (needPostProjectionCoercion) {
        ImmutableList.Builder<Expression> alreadyCoerced = ImmutableList.builder();
        alreadyCoerced.addAll(groupByExpressions);
        groupIdVariable.map(ExpressionTreeUtils::createSymbolReference).ifPresent(alreadyCoerced::add);
        subPlan = explicitCoercionFields(subPlan, alreadyCoerced.build(), analysis.getAggregates(node));
    }
    // 4. Project and re-write all grouping functions
    return handleGroupingOperations(subPlan, node, groupIdVariable, columnOnlyGroupingSets);
}
Also used : FINAL(com.facebook.presto.spi.plan.LimitNode.Step.FINAL) AggregationNode(com.facebook.presto.spi.plan.AggregationNode) SortNode(com.facebook.presto.sql.planner.plan.SortNode) OriginalExpressionUtils(com.facebook.presto.sql.relational.OriginalExpressionUtils) FrameBound(com.facebook.presto.sql.tree.FrameBound) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Field(com.facebook.presto.sql.analyzer.Field) WindowNodeUtil.toBoundType(com.facebook.presto.sql.planner.optimizations.WindowNodeUtil.toBoundType) ValuesNode(com.facebook.presto.spi.plan.ValuesNode) Delete(com.facebook.presto.sql.tree.Delete) Map(java.util.Map) LOCAL(com.facebook.presto.spi.plan.ProjectNode.Locality.LOCAL) AggregationNode.singleGroupingSet(com.facebook.presto.spi.plan.AggregationNode.singleGroupingSet) CallExpression(com.facebook.presto.spi.relation.CallExpression) OrderingScheme(com.facebook.presto.spi.plan.OrderingScheme) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) OffsetNode(com.facebook.presto.sql.planner.plan.OffsetNode) SymbolReference(com.facebook.presto.sql.tree.SymbolReference) AssignmentUtils.identitiesAsSymbolReferences(com.facebook.presto.sql.planner.plan.AssignmentUtils.identitiesAsSymbolReferences) RelationId(com.facebook.presto.sql.analyzer.RelationId) ImmutableSet(com.google.common.collect.ImmutableSet) Query(com.facebook.presto.sql.tree.Query) WindowNodeUtil.toWindowType(com.facebook.presto.sql.planner.optimizations.WindowNodeUtil.toWindowType) SortOrder(com.facebook.presto.common.block.SortOrder) QuerySpecification(com.facebook.presto.sql.tree.QuerySpecification) ImmutableMap(com.google.common.collect.ImmutableMap) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) Ordering(com.facebook.presto.spi.plan.Ordering) ExpressionTreeUtils(com.facebook.presto.sql.analyzer.ExpressionTreeUtils) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Node(com.facebook.presto.sql.tree.Node) Set(java.util.Set) SortItem(com.facebook.presto.sql.tree.SortItem) Sets(com.google.common.collect.Sets) LimitNode(com.facebook.presto.spi.plan.LimitNode) SystemSessionProperties.isSkipRedundantSort(com.facebook.presto.SystemSessionProperties.isSkipRedundantSort) List(java.util.List) Window(com.facebook.presto.sql.tree.Window) ProjectNode(com.facebook.presto.spi.plan.ProjectNode) ExpressionTreeUtils.getSourceLocation(com.facebook.presto.sql.analyzer.ExpressionTreeUtils.getSourceLocation) FieldId(com.facebook.presto.sql.analyzer.FieldId) Analysis(com.facebook.presto.sql.analyzer.Analysis) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) PlannerUtils.toOrderingScheme(com.facebook.presto.sql.planner.PlannerUtils.toOrderingScheme) IntStream(java.util.stream.IntStream) Iterables(com.google.common.collect.Iterables) LambdaArgumentDeclaration(com.facebook.presto.sql.tree.LambdaArgumentDeclaration) PlannerUtils.toSortOrder(com.facebook.presto.sql.planner.PlannerUtils.toSortOrder) GroupIdNode(com.facebook.presto.sql.planner.plan.GroupIdNode) Assignments(com.facebook.presto.spi.plan.Assignments) Expressions.call(com.facebook.presto.sql.relational.Expressions.call) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WindowFrame(com.facebook.presto.sql.tree.WindowFrame) FilterNode(com.facebook.presto.spi.plan.FilterNode) AssignmentUtils(com.facebook.presto.sql.planner.plan.AssignmentUtils) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) TableHandle(com.facebook.presto.spi.TableHandle) Cast(com.facebook.presto.sql.tree.Cast) Type(com.facebook.presto.common.type.Type) RowExpression(com.facebook.presto.spi.relation.RowExpression) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) GroupingOperation(com.facebook.presto.sql.tree.GroupingOperation) OrderBy(com.facebook.presto.sql.tree.OrderBy) PlanNodeIdAllocator(com.facebook.presto.spi.plan.PlanNodeIdAllocator) WindowNode(com.facebook.presto.sql.planner.plan.WindowNode) Session(com.facebook.presto.Session) NodeLocation(com.facebook.presto.sql.tree.NodeLocation) NodeUtils.getSortItemsFromOrderBy(com.facebook.presto.sql.NodeUtils.getSortItemsFromOrderBy) RelationType(com.facebook.presto.sql.analyzer.RelationType) Offset(com.facebook.presto.sql.tree.Offset) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) DeleteNode(com.facebook.presto.sql.planner.plan.DeleteNode) NodeRef(com.facebook.presto.sql.tree.NodeRef) Streams.stream(com.google.common.collect.Streams.stream) Scope(com.facebook.presto.sql.analyzer.Scope) PlanNode(com.facebook.presto.spi.plan.PlanNode) AggregationNode.groupingSets(com.facebook.presto.spi.plan.AggregationNode.groupingSets) Expression(com.facebook.presto.sql.tree.Expression) ColumnHandle(com.facebook.presto.spi.ColumnHandle) TableScanNode(com.facebook.presto.spi.plan.TableScanNode) FieldReference(com.facebook.presto.sql.tree.FieldReference) Aggregation(com.facebook.presto.spi.plan.AggregationNode.Aggregation) OriginalExpressionUtils.asSymbolReference(com.facebook.presto.sql.relational.OriginalExpressionUtils.asSymbolReference) Metadata(com.facebook.presto.metadata.Metadata) OriginalExpressionUtils.castToRowExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToRowExpression) Assignments(com.facebook.presto.spi.plan.Assignments) LinkedHashMap(java.util.LinkedHashMap) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Optional(java.util.Optional) ImmutableMap(com.google.common.collect.ImmutableMap) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Analysis(com.facebook.presto.sql.analyzer.Analysis) OriginalExpressionUtils(com.facebook.presto.sql.relational.OriginalExpressionUtils) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) Cast(com.facebook.presto.sql.tree.Cast) AggregationNode.singleGroupingSet(com.facebook.presto.spi.plan.AggregationNode.singleGroupingSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Aggregation(com.facebook.presto.spi.plan.AggregationNode.Aggregation) GroupIdNode(com.facebook.presto.sql.planner.plan.GroupIdNode) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) CallExpression(com.facebook.presto.spi.relation.CallExpression) FieldReference(com.facebook.presto.sql.tree.FieldReference) AggregationNode(com.facebook.presto.spi.plan.AggregationNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) CallExpression(com.facebook.presto.spi.relation.CallExpression) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) RowExpression(com.facebook.presto.spi.relation.RowExpression) Expression(com.facebook.presto.sql.tree.Expression) OriginalExpressionUtils.castToRowExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToRowExpression) FieldId(com.facebook.presto.sql.analyzer.FieldId) ProjectNode(com.facebook.presto.spi.plan.ProjectNode)

Example 10 with Assignments

use of com.facebook.presto.spi.plan.Assignments in project presto by prestodb.

the class RelationPlanner method visitAliasedRelation.

@Override
protected RelationPlan visitAliasedRelation(AliasedRelation node, Void context) {
    RelationPlan subPlan = process(node.getRelation(), context);
    PlanNode root = subPlan.getRoot();
    List<VariableReferenceExpression> mappings = subPlan.getFieldMappings();
    if (node.getColumnNames() != null) {
        ImmutableList.Builder<VariableReferenceExpression> newMappings = ImmutableList.builder();
        Assignments.Builder assignments = Assignments.builder();
        // project only the visible columns from the underlying relation
        for (int i = 0; i < subPlan.getDescriptor().getAllFieldCount(); i++) {
            Field field = subPlan.getDescriptor().getFieldByIndex(i);
            if (!field.isHidden()) {
                VariableReferenceExpression aliasedColumn = variableAllocator.newVariable(mappings.get(i).getSourceLocation(), field);
                assignments.put(aliasedColumn, castToRowExpression(asSymbolReference(subPlan.getFieldMappings().get(i))));
                newMappings.add(aliasedColumn);
            }
        }
        root = new ProjectNode(getSourceLocation(node.getLocation()), idAllocator.getNextId(), subPlan.getRoot(), assignments.build(), LOCAL);
        mappings = newMappings.build();
    }
    return new RelationPlan(root, analysis.getScope(node), mappings);
}
Also used : Field(com.facebook.presto.sql.analyzer.Field) PlanNode(com.facebook.presto.spi.plan.PlanNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Assignments(com.facebook.presto.spi.plan.Assignments) ProjectNode(com.facebook.presto.spi.plan.ProjectNode)

Aggregations

Assignments (com.facebook.presto.spi.plan.Assignments)25 VariableReferenceExpression (com.facebook.presto.spi.relation.VariableReferenceExpression)23 ProjectNode (com.facebook.presto.spi.plan.ProjectNode)22 OriginalExpressionUtils.castToRowExpression (com.facebook.presto.sql.relational.OriginalExpressionUtils.castToRowExpression)12 PlanNode (com.facebook.presto.spi.plan.PlanNode)11 RowExpression (com.facebook.presto.spi.relation.RowExpression)11 Expression (com.facebook.presto.sql.tree.Expression)10 CallExpression (com.facebook.presto.spi.relation.CallExpression)8 ImmutableList (com.google.common.collect.ImmutableList)8 Cast (com.facebook.presto.sql.tree.Cast)7 SymbolReference (com.facebook.presto.sql.tree.SymbolReference)7 Map (java.util.Map)6 Type (com.facebook.presto.common.type.Type)5 AggregationNode (com.facebook.presto.spi.plan.AggregationNode)5 FilterNode (com.facebook.presto.spi.plan.FilterNode)5 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)5 ImmutableMap (com.google.common.collect.ImmutableMap)5 Session (com.facebook.presto.Session)4 Field (com.facebook.presto.sql.analyzer.Field)4 TupleDomain (com.facebook.presto.common.predicate.TupleDomain)3